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