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