* code formatting
[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 $wgTitleCache = array();
13
14 define ( 'GAID_FOR_UPDATE', 1 );
15
16 # Title::newFromTitle maintains a cache to avoid
17 # expensive re-normalization of commonly used titles.
18 # On a batch operation this can become a memory leak
19 # if not bounded. After hitting this many titles,
20 # reset the cache.
21 define( 'MW_TITLECACHE_MAX', 1000 );
22
23 /**
24 * Title class
25 * - Represents a title, which may contain an interwiki designation or namespace
26 * - Can fetch various kinds of data from the database, albeit inefficiently.
27 *
28 * @package MediaWiki
29 */
30 class Title {
31 /**
32 * All member variables should be considered private
33 * Please use the accessor functions
34 */
35
36 /**#@+
37 * @access private
38 */
39
40 var $mTextform; # Text form (spaces not underscores) of the main part
41 var $mUrlform; # URL-encoded form of the main part
42 var $mDbkeyform; # Main part with underscores
43 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
44 var $mInterwiki; # Interwiki prefix (or null string)
45 var $mFragment; # Title fragment (i.e. the bit after the #)
46 var $mArticleID; # Article ID, fetched from the link cache on demand
47 var $mLatestID; # ID of most recent revision
48 var $mRestrictions; # Array of groups allowed to edit this article
49 # Only null or "sysop" are supported
50 var $mRestrictionsLoaded; # Boolean for initialisation on demand
51 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
52 var $mDefaultNamespace; # Namespace index when there is no namespace
53 # Zero except in {{transclusion}} tags
54 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
55 /**#@-*/
56
57
58 /**
59 * Constructor
60 * @access private
61 */
62 /* private */ function Title() {
63 $this->mInterwiki = $this->mUrlform =
64 $this->mTextform = $this->mDbkeyform = '';
65 $this->mArticleID = -1;
66 $this->mNamespace = NS_MAIN;
67 $this->mRestrictionsLoaded = false;
68 $this->mRestrictions = array();
69 # Dont change the following, NS_MAIN is hardcoded in several place
70 # See bug #696
71 $this->mDefaultNamespace = NS_MAIN;
72 $this->mWatched = NULL;
73 $this->mLatestID = false;
74 }
75
76 /**
77 * Create a new Title from a prefixed DB key
78 * @param string $key The database key, which has underscores
79 * instead of spaces, possibly including namespace and
80 * interwiki prefixes
81 * @return Title the new object, or NULL on an error
82 * @static
83 * @access public
84 */
85 /* static */ function newFromDBkey( $key ) {
86 $t = new Title();
87 $t->mDbkeyform = $key;
88 if( $t->secureAndSplit() )
89 return $t;
90 else
91 return NULL;
92 }
93
94 /**
95 * Create a new Title from text, such as what one would
96 * find in a link. Decodes any HTML entities in the text.
97 *
98 * @param string $text the link text; spaces, prefixes,
99 * and an initial ':' indicating the main namespace
100 * are accepted
101 * @param int $defaultNamespace the namespace to use if
102 * none is specified by a prefix
103 * @return Title the new object, or NULL on an error
104 * @static
105 * @access public
106 */
107 function newFromText( $text, $defaultNamespace = NS_MAIN ) {
108 global $wgTitleCache;
109 $fname = 'Title::newFromText';
110 wfProfileIn( $fname );
111
112 if( is_object( $text ) ) {
113 wfDebugDieBacktrace( 'Title::newFromText given an object' );
114 }
115
116 /**
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
120 * caching them.
121 *
122 * In theory these are value objects and won't get changed...
123 */
124 if( $defaultNamespace == NS_MAIN && isset( $wgTitleCache[$text] ) ) {
125 wfProfileOut( $fname );
126 return $wgTitleCache[$text];
127 }
128
129 /**
130 * Convert things like &eacute; &#257; or &#x3017; into real text...
131 */
132 $filteredText = Sanitizer::decodeCharReferences( $text );
133
134 $t =& new Title();
135 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
136 $t->mDefaultNamespace = $defaultNamespace;
137
138 if( $t->secureAndSplit() ) {
139 if( $defaultNamespace == NS_MAIN ) {
140 if( count( $wgTitleCache ) >= MW_TITLECACHE_MAX ) {
141 # Avoid memory leaks on mass operations...
142 $wgTitleCache = array();
143 }
144 $wgTitleCache[$text] =& $t;
145 }
146 wfProfileOut( $fname );
147 return $t;
148 } else {
149 wfProfileOut( $fname );
150 $ret = NULL;
151 return $ret;
152 }
153 }
154
155 /**
156 * Create a new Title from URL-encoded text. Ensures that
157 * the given title's length does not exceed the maximum.
158 * @param string $url the title, as might be taken from a URL
159 * @return Title the new object, or NULL on an error
160 * @static
161 * @access public
162 */
163 function newFromURL( $url ) {
164 $t = new Title();
165
166 # For compatibility with old buggy URLs. "+" is not valid in titles,
167 # but some URLs used it as a space replacement and they still come
168 # from some external search tools.
169 $s = str_replace( '+', ' ', $url );
170
171 $t->mDbkeyform = str_replace( ' ', '_', $s );
172 if( $t->secureAndSplit() ) {
173 return $t;
174 } else {
175 return NULL;
176 }
177 }
178
179 /**
180 * Create a new Title from an article ID
181 *
182 * @todo This is inefficiently implemented, the page row is requested
183 * but not used for anything else
184 *
185 * @param int $id the page_id corresponding to the Title to create
186 * @return Title the new object, or NULL on an error
187 * @access public
188 * @static
189 */
190 function newFromID( $id ) {
191 $fname = 'Title::newFromID';
192 $dbr =& wfGetDB( DB_SLAVE );
193 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
194 array( 'page_id' => $id ), $fname );
195 if ( $row !== false ) {
196 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
197 } else {
198 $title = NULL;
199 }
200 return $title;
201 }
202
203 /**
204 * Create a new Title from a namespace index and a DB key.
205 * It's assumed that $ns and $title are *valid*, for instance when
206 * they came directly from the database or a special page name.
207 * For convenience, spaces are converted to underscores so that
208 * eg user_text fields can be used directly.
209 *
210 * @param int $ns the namespace of the article
211 * @param string $title the unprefixed database key form
212 * @return Title the new object
213 * @static
214 * @access public
215 */
216 function &makeTitle( $ns, $title ) {
217 $t =& new Title();
218 $t->mInterwiki = '';
219 $t->mFragment = '';
220 $t->mNamespace = intval( $ns );
221 $t->mDbkeyform = str_replace( ' ', '_', $title );
222 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
223 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
224 $t->mTextform = str_replace( '_', ' ', $title );
225 return $t;
226 }
227
228 /**
229 * Create a new Title frrom a namespace index and a DB key.
230 * The parameters will be checked for validity, which is a bit slower
231 * than makeTitle() but safer for user-provided data.
232 *
233 * @param int $ns the namespace of the article
234 * @param string $title the database key form
235 * @return Title the new object, or NULL on an error
236 * @static
237 * @access public
238 */
239 function makeTitleSafe( $ns, $title ) {
240 $t = new Title();
241 $t->mDbkeyform = Title::makeName( $ns, $title );
242 if( $t->secureAndSplit() ) {
243 return $t;
244 } else {
245 return NULL;
246 }
247 }
248
249 /**
250 * Create a new Title for the Main Page
251 *
252 * @static
253 * @return Title the new object
254 * @access public
255 */
256 function newMainPage() {
257 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
258 }
259
260 /**
261 * Create a new Title for a redirect
262 * @param string $text the redirect title text
263 * @return Title the new object, or NULL if the text is not a
264 * valid redirect
265 * @static
266 * @access public
267 */
268 function newFromRedirect( $text ) {
269 global $wgMwRedir;
270 $rt = NULL;
271 if ( $wgMwRedir->matchStart( $text ) ) {
272 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
273 # categories are escaped using : for example one can enter:
274 # #REDIRECT [[:Category:Music]]. Need to remove it.
275 if ( substr($m[1],0,1) == ':') {
276 # We don't want to keep the ':'
277 $m[1] = substr( $m[1], 1 );
278 }
279
280 $rt = Title::newFromText( $m[1] );
281 # Disallow redirects to Special:Userlogout
282 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL && preg_match( '/^Userlogout/i', $rt->getText() ) ) {
283 $rt = NULL;
284 }
285 }
286 }
287 return $rt;
288 }
289
290 #----------------------------------------------------------------------------
291 # Static functions
292 #----------------------------------------------------------------------------
293
294 /**
295 * Get the prefixed DB key associated with an ID
296 * @param int $id the page_id of the article
297 * @return Title an object representing the article, or NULL
298 * if no such article was found
299 * @static
300 * @access public
301 */
302 function nameOf( $id ) {
303 $fname = 'Title::nameOf';
304 $dbr =& wfGetDB( DB_SLAVE );
305
306 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
307 if ( $s === false ) { return NULL; }
308
309 $n = Title::makeName( $s->page_namespace, $s->page_title );
310 return $n;
311 }
312
313 /**
314 * Get a regex character class describing the legal characters in a link
315 * @return string the list of characters, not delimited
316 * @static
317 * @access public
318 */
319 function legalChars() {
320 global $wgLegalTitleChars;
321 return $wgLegalTitleChars;
322 }
323
324 /**
325 * Get a string representation of a title suitable for
326 * including in a search index
327 *
328 * @param int $ns a namespace index
329 * @param string $title text-form main part
330 * @return string a stripped-down title string ready for the
331 * search index
332 */
333 /* static */ function indexTitle( $ns, $title ) {
334 global $wgContLang;
335 require_once( 'SearchEngine.php' );
336
337 $lc = SearchEngine::legalSearchChars() . '&#;';
338 $t = $wgContLang->stripForSearch( $title );
339 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
340 $t = strtolower( $t );
341
342 # Handle 's, s'
343 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
344 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
345
346 $t = preg_replace( "/\\s+/", ' ', $t );
347
348 if ( $ns == NS_IMAGE ) {
349 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
350 }
351 return trim( $t );
352 }
353
354 /*
355 * Make a prefixed DB key from a DB key and a namespace index
356 * @param int $ns numerical representation of the namespace
357 * @param string $title the DB key form the title
358 * @return string the prefixed form of the title
359 */
360 /* static */ function makeName( $ns, $title ) {
361 global $wgContLang;
362
363 $n = $wgContLang->getNsText( $ns );
364 return $n == '' ? $title : "$n:$title";
365 }
366
367 /**
368 * Returns the URL associated with an interwiki prefix
369 * @param string $key the interwiki prefix (e.g. "MeatBall")
370 * @return the associated URL, containing "$1", which should be
371 * replaced by an article title
372 * @static (arguably)
373 * @access public
374 */
375 function getInterwikiLink( $key, $transludeonly = false ) {
376 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
377 $fname = 'Title::getInterwikiLink';
378
379 wfProfileIn( $fname );
380
381 $key = strtolower( $key );
382
383 $k = $wgDBname.':interwiki:'.$key;
384 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
385 wfProfileOut( $fname );
386 return $wgTitleInterwikiCache[$k]->iw_url;
387 }
388
389 $s = $wgMemc->get( $k );
390 # Ignore old keys with no iw_local
391 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
392 $wgTitleInterwikiCache[$k] = $s;
393 wfProfileOut( $fname );
394 return $s->iw_url;
395 }
396
397 $dbr =& wfGetDB( DB_SLAVE );
398 $res = $dbr->select( 'interwiki',
399 array( 'iw_url', 'iw_local', 'iw_trans' ),
400 array( 'iw_prefix' => $key ), $fname );
401 if( !$res ) {
402 wfProfileOut( $fname );
403 return '';
404 }
405
406 $s = $dbr->fetchObject( $res );
407 if( !$s ) {
408 # Cache non-existence: create a blank object and save it to memcached
409 $s = (object)false;
410 $s->iw_url = '';
411 $s->iw_local = 0;
412 $s->iw_trans = 0;
413 }
414 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
415 $wgTitleInterwikiCache[$k] = $s;
416
417 wfProfileOut( $fname );
418 return $s->iw_url;
419 }
420
421 /**
422 * Determine whether the object refers to a page within
423 * this project.
424 *
425 * @return bool TRUE if this is an in-project interwiki link
426 * or a wikilink, FALSE otherwise
427 * @access public
428 */
429 function isLocal() {
430 global $wgTitleInterwikiCache, $wgDBname;
431
432 if ( $this->mInterwiki != '' ) {
433 # Make sure key is loaded into cache
434 $this->getInterwikiLink( $this->mInterwiki );
435 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
436 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
437 } else {
438 return true;
439 }
440 }
441
442 /**
443 * Determine whether the object refers to a page within
444 * this project and is transcludable.
445 *
446 * @return bool TRUE if this is transcludable
447 * @access public
448 */
449 function isTrans() {
450 global $wgTitleInterwikiCache, $wgDBname;
451
452 if ($this->mInterwiki == '' || !$this->isLocal())
453 return false;
454 # Make sure key is loaded into cache
455 $this->getInterwikiLink( $this->mInterwiki );
456 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
457 return (bool)($wgTitleInterwikiCache[$k]->iw_trans);
458 }
459
460 /**
461 * Update the page_touched field for an array of title objects
462 * @todo Inefficient unless the IDs are already loaded into the
463 * link cache
464 * @param array $titles an array of Title objects to be touched
465 * @param string $timestamp the timestamp to use instead of the
466 * default current time
467 * @static
468 * @access public
469 */
470 function touchArray( $titles, $timestamp = '' ) {
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 global $wgUser;
1613 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1614 return true;
1615 }
1616
1617 /**
1618 * Move page to a title which is at present a redirect to the
1619 * source page
1620 *
1621 * @param Title &$nt the page to move to, which should currently
1622 * be a redirect
1623 * @access private
1624 */
1625 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1626 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1627 $fname = 'Title::moveOverExistingRedirect';
1628 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1629
1630 if ( $reason ) {
1631 $comment .= ": $reason";
1632 }
1633
1634 $now = wfTimestampNow();
1635 $rand = wfRandom();
1636 $newid = $nt->getArticleID();
1637 $oldid = $this->getArticleID();
1638 $dbw =& wfGetDB( DB_MASTER );
1639 $links = $dbw->tableName( 'links' );
1640
1641 # Delete the old redirect. We don't save it to history since
1642 # by definition if we've got here it's rather uninteresting.
1643 # We have to remove it so that the next step doesn't trigger
1644 # a conflict on the unique namespace+title index...
1645 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1646
1647 # Save a null revision in the page's history notifying of the move
1648 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1649 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1650 true );
1651 $nullRevId = $nullRevision->insertOn( $dbw );
1652
1653 # Change the name of the target page:
1654 $dbw->update( 'page',
1655 /* SET */ array(
1656 'page_touched' => $dbw->timestamp($now),
1657 'page_namespace' => $nt->getNamespace(),
1658 'page_title' => $nt->getDBkey(),
1659 'page_latest' => $nullRevId,
1660 ),
1661 /* WHERE */ array( 'page_id' => $oldid ),
1662 $fname
1663 );
1664 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1665
1666 # Recreate the redirect, this time in the other direction.
1667 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1668 $redirectArticle = new Article( $this );
1669 $newid = $redirectArticle->insertOn( $dbw );
1670 $redirectRevision = new Revision( array(
1671 'page' => $newid,
1672 'comment' => $comment,
1673 'text' => $redirectText ) );
1674 $revid = $redirectRevision->insertOn( $dbw );
1675 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1676 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1677
1678 # Log the move
1679 $log = new LogPage( 'move' );
1680 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1681
1682 # Now, we record the link from the redirect to the new title.
1683 # It should have no other outgoing links...
1684 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1685 $dbw->insert( 'pagelinks',
1686 array(
1687 'pl_from' => $newid,
1688 'pl_namespace' => $nt->getNamespace(),
1689 'pl_title' => $nt->getDbKey() ),
1690 $fname );
1691
1692 # Purge squid
1693 if ( $wgUseSquid ) {
1694 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1695 $u = new SquidUpdate( $urls );
1696 $u->doUpdate();
1697 }
1698 }
1699
1700 /**
1701 * Move page to non-existing title.
1702 * @param Title &$nt the new Title
1703 * @param int &$newid set to be the new article ID
1704 * @access private
1705 */
1706 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1707 global $wgUser, $wgLinkCache, $wgUseSquid;
1708 global $wgMwRedir;
1709 $fname = 'MovePageForm::moveToNewTitle';
1710 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1711 if ( $reason ) {
1712 $comment .= ": $reason";
1713 }
1714
1715 $newid = $nt->getArticleID();
1716 $oldid = $this->getArticleID();
1717 $dbw =& wfGetDB( DB_MASTER );
1718 $now = $dbw->timestamp();
1719 wfSeedRandom();
1720 $rand = wfRandom();
1721
1722 # Save a null revision in the page's history notifying of the move
1723 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1724 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1725 true );
1726 $nullRevId = $nullRevision->insertOn( $dbw );
1727
1728 # Rename cur entry
1729 $dbw->update( 'page',
1730 /* SET */ array(
1731 'page_touched' => $now,
1732 'page_namespace' => $nt->getNamespace(),
1733 'page_title' => $nt->getDBkey(),
1734 'page_latest' => $nullRevId,
1735 ),
1736 /* WHERE */ array( 'page_id' => $oldid ),
1737 $fname
1738 );
1739
1740 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1741
1742 # Insert redirect
1743 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1744 $redirectArticle = new Article( $this );
1745 $newid = $redirectArticle->insertOn( $dbw );
1746 $redirectRevision = new Revision( array(
1747 'page' => $newid,
1748 'comment' => $comment,
1749 'text' => $redirectText ) );
1750 $revid = $redirectRevision->insertOn( $dbw );
1751 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1752 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1753
1754 # Log the move
1755 $log = new LogPage( 'move' );
1756 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1757
1758 # Purge caches as per article creation
1759 Article::onArticleCreate( $nt );
1760
1761 # Record the just-created redirect's linking to the page
1762 $dbw->insert( 'pagelinks',
1763 array(
1764 'pl_from' => $newid,
1765 'pl_namespace' => $nt->getNamespace(),
1766 'pl_title' => $nt->getDBkey() ),
1767 $fname );
1768
1769 # Non-existent target may have had broken links to it; these must
1770 # now be touched to update link coloring.
1771 $nt->touchLinks();
1772
1773 # Purge old title from squid
1774 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1775 $titles = $nt->getLinksTo();
1776 if ( $wgUseSquid ) {
1777 $urls = $this->getSquidURLs();
1778 foreach ( $titles as $linkTitle ) {
1779 $urls[] = $linkTitle->getInternalURL();
1780 }
1781 $u = new SquidUpdate( $urls );
1782 $u->doUpdate();
1783 }
1784 }
1785
1786 /**
1787 * Checks if $this can be moved to a given Title
1788 * - Selects for update, so don't call it unless you mean business
1789 *
1790 * @param Title &$nt the new title to check
1791 * @access public
1792 */
1793 function isValidMoveTarget( $nt ) {
1794
1795 $fname = 'Title::isValidMoveTarget';
1796 $dbw =& wfGetDB( DB_MASTER );
1797
1798 # Is it a redirect?
1799 $id = $nt->getArticleID();
1800 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1801 array( 'page_is_redirect','old_text','old_flags' ),
1802 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1803 $fname, 'FOR UPDATE' );
1804
1805 if ( !$obj || 0 == $obj->page_is_redirect ) {
1806 # Not a redirect
1807 return false;
1808 }
1809 $text = Revision::getRevisionText( $obj );
1810
1811 # Does the redirect point to the source?
1812 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1813 $redirTitle = Title::newFromText( $m[1] );
1814 if( !is_object( $redirTitle ) ||
1815 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1816 return false;
1817 }
1818 } else {
1819 # Fail safe
1820 return false;
1821 }
1822
1823 # Does the article have a history?
1824 $row = $dbw->selectRow( array( 'page', 'revision'),
1825 array( 'rev_id' ),
1826 array( 'page_namespace' => $nt->getNamespace(),
1827 'page_title' => $nt->getDBkey(),
1828 'page_id=rev_page AND page_latest != rev_id'
1829 ), $fname, 'FOR UPDATE'
1830 );
1831
1832 # Return true if there was no history
1833 return $row === false;
1834 }
1835
1836 /**
1837 * Create a redirect; fails if the title already exists; does
1838 * not notify RC
1839 *
1840 * @param Title $dest the destination of the redirect
1841 * @param string $comment the comment string describing the move
1842 * @return bool true on success
1843 * @access public
1844 */
1845 function createRedirect( $dest, $comment ) {
1846 global $wgUser;
1847 if ( $this->getArticleID() ) {
1848 return false;
1849 }
1850
1851 $fname = 'Title::createRedirect';
1852 $dbw =& wfGetDB( DB_MASTER );
1853
1854 $article = new Article( $this );
1855 $newid = $article->insertOn( $dbw );
1856 $revision = new Revision( array(
1857 'page' => $newid,
1858 'comment' => $comment,
1859 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1860 ) );
1861 $revisionId = $revision->insertOn( $dbw );
1862 $article->updateRevisionOn( $dbw, $revision, 0 );
1863
1864 # Link table
1865 $dbw->insert( 'pagelinks',
1866 array(
1867 'pl_from' => $newid,
1868 'pl_namespace' => $dest->getNamespace(),
1869 'pl_title' => $dest->getDbKey()
1870 ), $fname
1871 );
1872
1873 Article::onArticleCreate( $this );
1874 return true;
1875 }
1876
1877 /**
1878 * Get categories to which this Title belongs and return an array of
1879 * categories' names.
1880 *
1881 * @return array an array of parents in the form:
1882 * $parent => $currentarticle
1883 * @access public
1884 */
1885 function getParentCategories() {
1886 global $wgContLang,$wgUser;
1887
1888 $titlekey = $this->getArticleId();
1889 $sk =& $wgUser->getSkin();
1890 $parents = array();
1891 $dbr =& wfGetDB( DB_SLAVE );
1892 $categorylinks = $dbr->tableName( 'categorylinks' );
1893
1894 # NEW SQL
1895 $sql = "SELECT * FROM $categorylinks"
1896 ." WHERE cl_from='$titlekey'"
1897 ." AND cl_from <> '0'"
1898 ." ORDER BY cl_sortkey";
1899
1900 $res = $dbr->query ( $sql ) ;
1901
1902 if($dbr->numRows($res) > 0) {
1903 while ( $x = $dbr->fetchObject ( $res ) )
1904 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1905 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1906 $dbr->freeResult ( $res ) ;
1907 } else {
1908 $data = '';
1909 }
1910 return $data;
1911 }
1912
1913 /**
1914 * Get a tree of parent categories
1915 * @param array $children an array with the children in the keys, to check for circular refs
1916 * @return array
1917 * @access public
1918 */
1919 function getParentCategoryTree( $children = array() ) {
1920 $parents = $this->getParentCategories();
1921
1922 if($parents != '') {
1923 foreach($parents as $parent => $current)
1924 {
1925 if ( array_key_exists( $parent, $children ) ) {
1926 # Circular reference
1927 $stack[$parent] = array();
1928 } else {
1929 $nt = Title::newFromText($parent);
1930 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1931 }
1932 }
1933 return $stack;
1934 } else {
1935 return array();
1936 }
1937 }
1938
1939
1940 /**
1941 * Get an associative array for selecting this title from
1942 * the "cur" table
1943 *
1944 * @return array
1945 * @access public
1946 */
1947 function curCond() {
1948 wfDebugDieBacktrace( 'curCond called' );
1949 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1950 }
1951
1952 /**
1953 * Get an associative array for selecting this title from the
1954 * "old" table
1955 *
1956 * @return array
1957 * @access public
1958 */
1959 function oldCond() {
1960 wfDebugDieBacktrace( 'oldCond called' );
1961 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1962 }
1963
1964 /**
1965 * Get the revision ID of the previous revision
1966 *
1967 * @param integer $revision Revision ID. Get the revision that was before this one.
1968 * @return interger $oldrevision|false
1969 */
1970 function getPreviousRevisionID( $revision ) {
1971 $dbr =& wfGetDB( DB_SLAVE );
1972 return $dbr->selectField( 'revision', 'rev_id',
1973 'rev_page=' . intval( $this->getArticleId() ) .
1974 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
1975 }
1976
1977 /**
1978 * Get the revision ID of the next revision
1979 *
1980 * @param integer $revision Revision ID. Get the revision that was after this one.
1981 * @return interger $oldrevision|false
1982 */
1983 function getNextRevisionID( $revision ) {
1984 $dbr =& wfGetDB( DB_SLAVE );
1985 return $dbr->selectField( 'revision', 'rev_id',
1986 'rev_page=' . intval( $this->getArticleId() ) .
1987 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
1988 }
1989
1990 /**
1991 * Compare with another title.
1992 *
1993 * @param Title $title
1994 * @return bool
1995 */
1996 function equals( $title ) {
1997 return $this->getInterwiki() == $title->getInterwiki()
1998 && $this->getNamespace() == $title->getNamespace()
1999 && $this->getDbkey() == $title->getDbkey();
2000 }
2001
2002 /**
2003 * Check if page exists
2004 * @return bool
2005 */
2006 function exists() {
2007 return $this->getArticleId() != 0;
2008 }
2009
2010 /**
2011 * Should a link should be displayed as a known link, just based on its title?
2012 *
2013 * Currently, a self-link with a fragment and special pages are in
2014 * this category. Special pages never exist in the database.
2015 */
2016 function isAlwaysKnown() {
2017 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2018 || NS_SPECIAL == $this->mNamespace;
2019 }
2020
2021 /**
2022 * Update page_touched timestamps on pages linking to this title.
2023 * In principal, this could be backgrounded and could also do squid
2024 * purging.
2025 */
2026 function touchLinks() {
2027 $fname = 'Title::touchLinks';
2028
2029 $dbw =& wfGetDB( DB_MASTER );
2030
2031 $res = $dbw->select( 'pagelinks',
2032 array( 'pl_from' ),
2033 array(
2034 'pl_namespace' => $this->getNamespace(),
2035 'pl_title' => $this->getDbKey() ),
2036 $fname );
2037 if ( 0 == $dbw->numRows( $res ) ) {
2038 return;
2039 }
2040
2041 $arr = array();
2042 $toucharr = array();
2043 while( $row = $dbw->fetchObject( $res ) ) {
2044 $toucharr[] = $row->pl_from;
2045 }
2046 if (!count($toucharr))
2047 return;
2048 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2049 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2050 }
2051
2052 function trackbackURL() {
2053 global $wgTitle, $wgScriptPath, $wgServer;
2054
2055 return "$wgServer$wgScriptPath/trackback.php?article="
2056 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2057 }
2058
2059 function trackbackRDF() {
2060 $url = htmlspecialchars($this->getFullURL());
2061 $title = htmlspecialchars($this->getText());
2062 $tburl = $this->trackbackURL();
2063
2064 return "
2065 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2066 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2067 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2068 <rdf:Description
2069 rdf:about=\"$url\"
2070 dc:identifier=\"$url\"
2071 dc:title=\"$title\"
2072 trackback:ping=\"$tburl\" />
2073 </rdf:RDF>";
2074 }
2075 }
2076 ?>