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