fixes from live site
[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, $transludeonly = false ) {
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 ) && isset($s->iw_trans)) {
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', 'iw_trans' ),
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 $s->iw_trans = 0;
424 }
425 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
426 $wgTitleInterwikiCache[$k] = $s;
427
428 wfProfileOut( $fname );
429 return $s->iw_url;
430 }
431
432 /**
433 * Determine whether the object refers to a page within
434 * this project.
435 *
436 * @return bool TRUE if this is an in-project interwiki link
437 * or a wikilink, FALSE otherwise
438 * @access public
439 */
440 function isLocal() {
441 global $wgTitleInterwikiCache, $wgDBname;
442
443 if ( $this->mInterwiki != '' ) {
444 # Make sure key is loaded into cache
445 $this->getInterwikiLink( $this->mInterwiki );
446 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
447 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
448 } else {
449 return true;
450 }
451 }
452
453 /**
454 * Determine whether the object refers to a page within
455 * this project and is transcludable.
456 *
457 * @return bool TRUE if this is transcludable
458 * @access public
459 */
460 function isTrans() {
461 global $wgTitleInterwikiCache, $wgDBname;
462
463 if ($this->mInterwiki == '' || !$this->isLocal())
464 return false;
465 # Make sure key is loaded into cache
466 $this->getInterwikiLink( $this->mInterwiki );
467 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
468 return (bool)($wgTitleInterwikiCache[$k]->iw_trans);
469 }
470
471 /**
472 * Update the page_touched field for an array of title objects
473 * @todo Inefficient unless the IDs are already loaded into the
474 * link cache
475 * @param array $titles an array of Title objects to be touched
476 * @param string $timestamp the timestamp to use instead of the
477 * default current time
478 * @static
479 * @access public
480 */
481 function touchArray( $titles, $timestamp = '' ) {
482 if ( count( $titles ) == 0 ) {
483 return;
484 }
485 $dbw =& wfGetDB( DB_MASTER );
486 if ( $timestamp == '' ) {
487 $timestamp = $dbw->timestamp();
488 }
489 $page = $dbw->tableName( 'page' );
490 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
491 $first = true;
492
493 foreach ( $titles as $title ) {
494 if ( ! $first ) {
495 $sql .= ',';
496 }
497 $first = false;
498 $sql .= $title->getArticleID();
499 }
500 $sql .= ')';
501 if ( ! $first ) {
502 $dbw->query( $sql, 'Title::touchArray' );
503 }
504 }
505
506 #----------------------------------------------------------------------------
507 # Other stuff
508 #----------------------------------------------------------------------------
509
510 /** Simple accessors */
511 /**
512 * Get the text form (spaces not underscores) of the main part
513 * @return string
514 * @access public
515 */
516 function getText() { return $this->mTextform; }
517 /**
518 * Get the URL-encoded form of the main part
519 * @return string
520 * @access public
521 */
522 function getPartialURL() { return $this->mUrlform; }
523 /**
524 * Get the main part with underscores
525 * @return string
526 * @access public
527 */
528 function getDBkey() { return $this->mDbkeyform; }
529 /**
530 * Get the namespace index, i.e. one of the NS_xxxx constants
531 * @return int
532 * @access public
533 */
534 function getNamespace() { return $this->mNamespace; }
535 /**
536 * Get the interwiki prefix (or null string)
537 * @return string
538 * @access public
539 */
540 function getInterwiki() { return $this->mInterwiki; }
541 /**
542 * Get the Title fragment (i.e. the bit after the #)
543 * @return string
544 * @access public
545 */
546 function getFragment() { return $this->mFragment; }
547 /**
548 * Get the default namespace index, for when there is no namespace
549 * @return int
550 * @access public
551 */
552 function getDefaultNamespace() { return $this->mDefaultNamespace; }
553
554 /**
555 * Get title for search index
556 * @return string a stripped-down title string ready for the
557 * search index
558 */
559 function getIndexTitle() {
560 return Title::indexTitle( $this->mNamespace, $this->mTextform );
561 }
562
563 /**
564 * Get the prefixed database key form
565 * @return string the prefixed title, with underscores and
566 * any interwiki and namespace prefixes
567 * @access public
568 */
569 function getPrefixedDBkey() {
570 $s = $this->prefix( $this->mDbkeyform );
571 $s = str_replace( ' ', '_', $s );
572 return $s;
573 }
574
575 /**
576 * Get the prefixed title with spaces.
577 * This is the form usually used for display
578 * @return string the prefixed title, with spaces
579 * @access public
580 */
581 function getPrefixedText() {
582 global $wgContLang;
583 if ( empty( $this->mPrefixedText ) ) {
584 $s = $this->prefix( $this->mTextform );
585 $s = str_replace( '_', ' ', $s );
586 $this->mPrefixedText = $s;
587 }
588 return $this->mPrefixedText;
589 }
590
591 /**
592 * Get the prefixed title with spaces, plus any fragment
593 * (part beginning with '#')
594 * @return string the prefixed title, with spaces and
595 * the fragment, including '#'
596 * @access public
597 */
598 function getFullText() {
599 global $wgContLang;
600 $text = $this->getPrefixedText();
601 if( '' != $this->mFragment ) {
602 $text .= '#' . $this->mFragment;
603 }
604 return $text;
605 }
606
607 /**
608 * Get a URL-encoded title (not an actual URL) including interwiki
609 * @return string the URL-encoded form
610 * @access public
611 */
612 function getPrefixedURL() {
613 $s = $this->prefix( $this->mDbkeyform );
614 $s = str_replace( ' ', '_', $s );
615
616 $s = wfUrlencode ( $s ) ;
617
618 # Cleaning up URL to make it look nice -- is this safe?
619 $s = str_replace( '%28', '(', $s );
620 $s = str_replace( '%29', ')', $s );
621
622 return $s;
623 }
624
625 /**
626 * Get a real URL referring to this title, with interwiki link and
627 * fragment
628 *
629 * @param string $query an optional query string, not used
630 * for interwiki links
631 * @return string the URL
632 * @access public
633 */
634 function getFullURL( $query = '' ) {
635 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
636
637 if ( '' == $this->mInterwiki ) {
638 return $wgServer . $this->getLocalUrl( $query );
639 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki ) ) {
640 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
641 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
642 } else {
643 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
644 }
645
646 $namespace = $wgContLang->getNsText( $this->mNamespace );
647 if ( '' != $namespace ) {
648 # Can this actually happen? Interwikis shouldn't be parsed.
649 $namepace .= ':';
650 }
651 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
652 if( $query != '' ) {
653 if( false === strpos( $url, '?' ) ) {
654 $url .= '?';
655 } else {
656 $url .= '&';
657 }
658 $url .= $query;
659 }
660 if ( '' != $this->mFragment ) {
661 $url .= '#' . $this->mFragment;
662 }
663 return $url;
664 }
665
666 /**
667 * Get a relative directory for putting an HTML version of this article into
668 */
669 function getHashedDirectory() {
670 global $wgMakeDumpLinks, $wgInputEncoding;
671 $dbkey = $this->getDBkey();
672
673 # Split into characters
674 if ( $wgInputEncoding == 'UTF-8' ) {
675 preg_match_all( '/./us', $dbkey, $m );
676 } else {
677 preg_match_all( '/./s', $dbkey, $m );
678 }
679 $chars = $m[0];
680 $length = count( $chars );
681 $dir = '';
682
683 for ( $i = 0; $i < $wgMakeDumpLinks; $i++ ) {
684 if ( $i ) {
685 $dir .= '/';
686 }
687 if ( $i >= $length ) {
688 $dir .= '_';
689 } elseif ( ord( $chars[$i] ) > 32 ) {
690 $dir .= strtolower( $chars[$i] );
691 } else {
692 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
693 }
694 }
695 return $dir;
696 }
697
698 function getHashedFilename() {
699 $dbkey = $this->getPrefixedDBkey();
700 $mainPage = Title::newMainPage();
701 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
702 return 'index.html';
703 }
704
705 $dir = $this->getHashedDirectory();
706
707 # Replace illegal charcters for Windows paths with underscores
708 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
709
710 # Work out lower case form. We assume we're on a system with case-insensitive
711 # filenames, so unless the case is of a special form, we have to disambiguate
712 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
713
714 # Make it mostly unique
715 if ( $lowerCase != $friendlyName ) {
716 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
717 }
718 # Handle colon specially by replacing it with tilde
719 # Thus we reduce the number of paths with hashes appended
720 $friendlyName = str_replace( ':', '~', $friendlyName );
721 return "$dir/$friendlyName.html";
722 }
723
724 /**
725 * Get a URL with no fragment or server name
726 * @param string $query an optional query string; if not specified,
727 * $wgArticlePath will be used.
728 * @return string the URL
729 * @access public
730 */
731 function getLocalURL( $query = '' ) {
732 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $action;
733
734 if ( $this->isExternal() || $action == 'render' ) {
735 return $this->getFullURL();
736 }
737
738 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
739 if ( $wgMakeDumpLinks ) {
740 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
741 } elseif ( $query == '' ) {
742 $url = str_replace( '$1', $dbkey, $wgArticlePath );
743 } else {
744 global $wgActionPaths;
745 if( !empty( $wgActionPaths ) &&
746 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
747 $action = urldecode( $matches[2] );
748 if( isset( $wgActionPaths[$action] ) ) {
749 $query = $matches[1];
750 if( isset( $matches[4] ) ) $query .= $matches[4];
751 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
752 if( $query != '' ) $url .= '?' . $query;
753 return $url;
754 }
755 }
756 if ( $query == '-' ) {
757 $query = '';
758 }
759 $url = "{$wgScript}?title={$dbkey}&{$query}";
760 }
761 return $url;
762 }
763
764 /**
765 * Get an HTML-escaped version of the URL form, suitable for
766 * using in a link, without a server name or fragment
767 * @param string $query an optional query string
768 * @return string the URL
769 * @access public
770 */
771 function escapeLocalURL( $query = '' ) {
772 return htmlspecialchars( $this->getLocalURL( $query ) );
773 }
774
775 /**
776 * Get an HTML-escaped version of the URL form, suitable for
777 * using in a link, including the server name and fragment
778 *
779 * @return string the URL
780 * @param string $query an optional query string
781 * @access public
782 */
783 function escapeFullURL( $query = '' ) {
784 return htmlspecialchars( $this->getFullURL( $query ) );
785 }
786
787 /**
788 * Get the URL form for an internal link.
789 * - Used in various Squid-related code, in case we have a different
790 * internal hostname for the server from the exposed one.
791 *
792 * @param string $query an optional query string
793 * @return string the URL
794 * @access public
795 */
796 function getInternalURL( $query = '' ) {
797 global $wgInternalServer;
798 return $wgInternalServer . $this->getLocalURL( $query );
799 }
800
801 /**
802 * Get the edit URL for this Title
803 * @return string the URL, or a null string if this is an
804 * interwiki link
805 * @access public
806 */
807 function getEditURL() {
808 global $wgServer, $wgScript;
809
810 if ( '' != $this->mInterwiki ) { return ''; }
811 $s = $this->getLocalURL( 'action=edit' );
812
813 return $s;
814 }
815
816 /**
817 * Get the HTML-escaped displayable text form.
818 * Used for the title field in <a> tags.
819 * @return string the text, including any prefixes
820 * @access public
821 */
822 function getEscapedText() {
823 return htmlspecialchars( $this->getPrefixedText() );
824 }
825
826 /**
827 * Is this Title interwiki?
828 * @return boolean
829 * @access public
830 */
831 function isExternal() { return ( '' != $this->mInterwiki ); }
832
833 /**
834 * Does the title correspond to a protected article?
835 * @param string $what the action the page is protected from,
836 * by default checks move and edit
837 * @return boolean
838 * @access public
839 */
840 function isProtected($action = '') {
841 if ( -1 == $this->mNamespace ) { return true; }
842 if($action == 'edit' || $action == '') {
843 $a = $this->getRestrictions("edit");
844 if ( in_array( 'sysop', $a ) ) { return true; }
845 }
846 if($action == 'move' || $action == '') {
847 $a = $this->getRestrictions("move");
848 if ( in_array( 'sysop', $a ) ) { return true; }
849 }
850 return false;
851 }
852
853 /**
854 * Is $wgUser is watching this page?
855 * @return boolean
856 * @access public
857 */
858 function userIsWatching() {
859 global $wgUser;
860
861 if ( is_null( $this->mWatched ) ) {
862 if ( -1 == $this->mNamespace || 0 == $wgUser->getID()) {
863 $this->mWatched = false;
864 } else {
865 $this->mWatched = $wgUser->isWatched( $this );
866 }
867 }
868 return $this->mWatched;
869 }
870
871 /**
872 * Is $wgUser perform $action this page?
873 * @param string $action action that permission needs to be checked for
874 * @return boolean
875 * @access private
876 */
877 function userCan($action) {
878 $fname = 'Title::userCanEdit';
879 wfProfileIn( $fname );
880
881 global $wgUser;
882 if( NS_SPECIAL == $this->mNamespace ) {
883 wfProfileOut( $fname );
884 return false;
885 }
886 if( NS_MEDIAWIKI == $this->mNamespace &&
887 !$wgUser->isAllowed('editinterface') ) {
888 wfProfileOut( $fname );
889 return false;
890 }
891 if( $this->mDbkeyform == '_' ) {
892 # FIXME: Is this necessary? Shouldn't be allowed anyway...
893 wfProfileOut( $fname );
894 return false;
895 }
896
897 # protect global styles and js
898 if ( NS_MEDIAWIKI == $this->mNamespace
899 && preg_match("/\\.(css|js)$/", $this->mTextform )
900 && !$wgUser->isAllowed('editinterface') ) {
901 wfProfileOut( $fname );
902 return false;
903 }
904
905 # protect css/js subpages of user pages
906 # XXX: this might be better using restrictions
907 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
908 if( NS_USER == $this->mNamespace
909 && preg_match("/\\.(css|js)$/", $this->mTextform )
910 && !$wgUser->isAllowed('editinterface')
911 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
912 wfProfileOut( $fname );
913 return false;
914 }
915
916 foreach( $this->getRestrictions($action) as $right ) {
917 // Backwards compatibility, rewrite sysop -> protect
918 if ( $right == 'sysop' ) {
919 $right = 'protect';
920 }
921 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
922 wfProfileOut( $fname );
923 return false;
924 }
925 }
926
927 if( $action == 'move' && !$this->isMovable() ) {
928 wfProfileOut( $fname );
929 return false;
930 }
931
932 wfProfileOut( $fname );
933 return true;
934 }
935
936 /**
937 * Can $wgUser edit this page?
938 * @return boolean
939 * @access public
940 */
941 function userCanEdit() {
942 return $this->userCan('edit');
943 }
944
945 /**
946 * Can $wgUser move this page?
947 * @return boolean
948 * @access public
949 */
950 function userCanMove() {
951 return $this->userCan('move');
952 }
953
954 /**
955 * Would anybody with sufficient privileges be able to move this page?
956 * Some pages just aren't movable.
957 *
958 * @return boolean
959 * @access public
960 */
961 function isMovable() {
962 return Namespace::isMovable( $this->getNamespace() )
963 && $this->getInterwiki() == '';
964 }
965
966 /**
967 * Can $wgUser read this page?
968 * @return boolean
969 * @access public
970 */
971 function userCanRead() {
972 global $wgUser;
973
974 if( $wgUser->isAllowed('read') ) {
975 return true;
976 } else {
977 global $wgWhitelistRead;
978
979 /** If anon users can create an account,
980 they need to reach the login page first! */
981 if( $wgUser->isAllowed( 'createaccount' )
982 && $this->getNamespace() == NS_SPECIAL
983 && $this->getText() == 'Userlogin' ) {
984 return true;
985 }
986
987 /** some pages are explicitly allowed */
988 $name = $this->getPrefixedText();
989 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
990 return true;
991 }
992
993 # Compatibility with old settings
994 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
995 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
996 return true;
997 }
998 }
999 }
1000 return false;
1001 }
1002
1003 /**
1004 * Is this a talk page of some sort?
1005 * @return bool
1006 * @access public
1007 */
1008 function isTalkPage() {
1009 return Namespace::isTalk( $this->getNamespace() );
1010 }
1011
1012 /**
1013 * Is this a .css or .js subpage of a user page?
1014 * @return bool
1015 * @access public
1016 */
1017 function isCssJsSubpage() {
1018 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
1019 }
1020 /**
1021 * Is this a .css subpage of a user page?
1022 * @return bool
1023 * @access public
1024 */
1025 function isCssSubpage() {
1026 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1027 }
1028 /**
1029 * Is this a .js subpage of a user page?
1030 * @return bool
1031 * @access public
1032 */
1033 function isJsSubpage() {
1034 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1035 }
1036 /**
1037 * Protect css/js subpages of user pages: can $wgUser edit
1038 * this page?
1039 *
1040 * @return boolean
1041 * @todo XXX: this might be better using restrictions
1042 * @access public
1043 */
1044 function userCanEditCssJsSubpage() {
1045 global $wgUser;
1046 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1047 }
1048
1049 /**
1050 * Loads a string into mRestrictions array
1051 * @param string $res restrictions in string format
1052 * @access public
1053 */
1054 function loadRestrictions( $res ) {
1055 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1056 $temp = explode( '=', trim( $restrict ) );
1057 if(count($temp) == 1) {
1058 // old format should be treated as edit/move restriction
1059 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1060 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1061 } else {
1062 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1063 }
1064 }
1065 $this->mRestrictionsLoaded = true;
1066 }
1067
1068 /**
1069 * Accessor/initialisation for mRestrictions
1070 * @param string $action action that permission needs to be checked for
1071 * @return array the array of groups allowed to edit this article
1072 * @access public
1073 */
1074 function getRestrictions($action) {
1075 $id = $this->getArticleID();
1076 if ( 0 == $id ) { return array(); }
1077
1078 if ( ! $this->mRestrictionsLoaded ) {
1079 $dbr =& wfGetDB( DB_SLAVE );
1080 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1081 $this->loadRestrictions( $res );
1082 }
1083 if( isset( $this->mRestrictions[$action] ) ) {
1084 return $this->mRestrictions[$action];
1085 }
1086 return array();
1087 }
1088
1089 /**
1090 * Is there a version of this page in the deletion archive?
1091 * @return int the number of archived revisions
1092 * @access public
1093 */
1094 function isDeleted() {
1095 $fname = 'Title::isDeleted';
1096 if ( $this->getNamespace() < 0 ) {
1097 $n = 0;
1098 } else {
1099 $dbr =& wfGetDB( DB_SLAVE );
1100 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1101 'ar_title' => $this->getDBkey() ), $fname );
1102 }
1103 return (int)$n;
1104 }
1105
1106 /**
1107 * Get the article ID for this Title from the link cache,
1108 * adding it if necessary
1109 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1110 * for update
1111 * @return int the ID
1112 * @access public
1113 */
1114 function getArticleID( $flags = 0 ) {
1115 global $wgLinkCache;
1116
1117 if ( $flags & GAID_FOR_UPDATE ) {
1118 $oldUpdate = $wgLinkCache->forUpdate( true );
1119 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1120 $wgLinkCache->forUpdate( $oldUpdate );
1121 } else {
1122 if ( -1 == $this->mArticleID ) {
1123 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1124 }
1125 }
1126 return $this->mArticleID;
1127 }
1128
1129 function getLatestRevID() {
1130 if ($this->mLatestID !== false)
1131 return $this->mLatestID;
1132
1133 $db =& wfGetDB(DB_SLAVE);
1134 return $this->mLatestID = $db->selectField( 'revision',
1135 "max(rev_id)",
1136 array('rev_page' => $this->getArticleID()),
1137 'Title::getLatestRevID' );
1138 }
1139
1140 /**
1141 * This clears some fields in this object, and clears any associated
1142 * keys in the "bad links" section of $wgLinkCache.
1143 *
1144 * - This is called from Article::insertNewArticle() to allow
1145 * loading of the new page_id. It's also called from
1146 * Article::doDeleteArticle()
1147 *
1148 * @param int $newid the new Article ID
1149 * @access public
1150 */
1151 function resetArticleID( $newid ) {
1152 global $wgLinkCache;
1153 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1154
1155 if ( 0 == $newid ) { $this->mArticleID = -1; }
1156 else { $this->mArticleID = $newid; }
1157 $this->mRestrictionsLoaded = false;
1158 $this->mRestrictions = array();
1159 }
1160
1161 /**
1162 * Updates page_touched for this page; called from LinksUpdate.php
1163 * @return bool true if the update succeded
1164 * @access public
1165 */
1166 function invalidateCache() {
1167 if ( wfReadOnly() ) {
1168 return;
1169 }
1170
1171 $now = wfTimestampNow();
1172 $dbw =& wfGetDB( DB_MASTER );
1173 $success = $dbw->update( 'page',
1174 array( /* SET */
1175 'page_touched' => $dbw->timestamp()
1176 ), array( /* WHERE */
1177 'page_namespace' => $this->getNamespace() ,
1178 'page_title' => $this->getDBkey()
1179 ), 'Title::invalidateCache'
1180 );
1181 return $success;
1182 }
1183
1184 /**
1185 * Prefix some arbitrary text with the namespace or interwiki prefix
1186 * of this object
1187 *
1188 * @param string $name the text
1189 * @return string the prefixed text
1190 * @access private
1191 */
1192 /* private */ function prefix( $name ) {
1193 global $wgContLang;
1194
1195 $p = '';
1196 if ( '' != $this->mInterwiki ) {
1197 $p = $this->mInterwiki . ':';
1198 }
1199 if ( 0 != $this->mNamespace ) {
1200 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1201 }
1202 return $p . $name;
1203 }
1204
1205 /**
1206 * Secure and split - main initialisation function for this object
1207 *
1208 * Assumes that mDbkeyform has been set, and is urldecoded
1209 * and uses underscores, but not otherwise munged. This function
1210 * removes illegal characters, splits off the interwiki and
1211 * namespace prefixes, sets the other forms, and canonicalizes
1212 * everything.
1213 * @return bool true on success
1214 * @access private
1215 */
1216 /* private */ function secureAndSplit() {
1217 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1218 $fname = 'Title::secureAndSplit';
1219 wfProfileIn( $fname );
1220
1221 # Initialisation
1222 static $rxTc = false;
1223 if( !$rxTc ) {
1224 # % is needed as well
1225 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1226 }
1227
1228 $this->mInterwiki = $this->mFragment = '';
1229 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1230
1231 # Clean up whitespace
1232 #
1233 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1234 $t = trim( $t, '_' );
1235
1236 if ( '' == $t ) {
1237 wfProfileOut( $fname );
1238 return false;
1239 }
1240
1241 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1242 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1243 wfProfileOut( $fname );
1244 return false;
1245 }
1246
1247 $this->mDbkeyform = $t;
1248
1249 # Initial colon indicating main namespace
1250 if ( ':' == $t{0} ) {
1251 $r = substr( $t, 1 );
1252 $this->mNamespace = NS_MAIN;
1253 } else {
1254 # Namespace or interwiki prefix
1255 $firstPass = true;
1256 do {
1257 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1258 $p = $m[1];
1259 $lowerNs = strtolower( $p );
1260 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1261 # Canonical namespace
1262 $t = $m[2];
1263 $this->mNamespace = $ns;
1264 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1265 # Ordinary namespace
1266 $t = $m[2];
1267 $this->mNamespace = $ns;
1268 } elseif( $this->getInterwikiLink( $p ) ) {
1269 if( !$firstPass ) {
1270 # Can't make a local interwiki link to an interwiki link.
1271 # That's just crazy!
1272 wfProfileOut( $fname );
1273 return false;
1274 }
1275
1276 # Interwiki link
1277 $t = $m[2];
1278 $this->mInterwiki = $p;
1279
1280 # Redundant interwiki prefix to the local wiki
1281 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1282 if( $t == '' ) {
1283 # Can't have an empty self-link
1284 wfProfileOut( $fname );
1285 return false;
1286 }
1287 $this->mInterwiki = '';
1288 $firstPass = false;
1289 # Do another namespace split...
1290 continue;
1291 }
1292 }
1293 # If there's no recognized interwiki or namespace,
1294 # then let the colon expression be part of the title.
1295 }
1296 break;
1297 } while( true );
1298 $r = $t;
1299 }
1300
1301 # We already know that some pages won't be in the database!
1302 #
1303 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1304 $this->mArticleID = 0;
1305 }
1306 $f = strstr( $r, '#' );
1307 if ( false !== $f ) {
1308 $this->mFragment = substr( $f, 1 );
1309 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1310 # remove whitespace again: prevents "Foo_bar_#"
1311 # becoming "Foo_bar_"
1312 $r = preg_replace( '/_*$/', '', $r );
1313 }
1314
1315 # Reject illegal characters.
1316 #
1317 if( preg_match( $rxTc, $r ) ) {
1318 wfProfileOut( $fname );
1319 return false;
1320 }
1321
1322 /**
1323 * Pages with "/./" or "/../" appearing in the URLs will
1324 * often be unreachable due to the way web browsers deal
1325 * with 'relative' URLs. Forbid them explicitly.
1326 */
1327 if ( strpos( $r, '.' ) !== false &&
1328 ( $r === '.' || $r === '..' ||
1329 strpos( $r, './' ) === 0 ||
1330 strpos( $r, '../' ) === 0 ||
1331 strpos( $r, '/./' ) !== false ||
1332 strpos( $r, '/../' ) !== false ) )
1333 {
1334 wfProfileOut( $fname );
1335 return false;
1336 }
1337
1338 # We shouldn't need to query the DB for the size.
1339 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1340 if ( strlen( $r ) > 255 ) {
1341 wfProfileOut( $fname );
1342 return false;
1343 }
1344
1345 /**
1346 * Normally, all wiki links are forced to have
1347 * an initial capital letter so [[foo]] and [[Foo]]
1348 * point to the same place.
1349 *
1350 * Don't force it for interwikis, since the other
1351 * site might be case-sensitive.
1352 */
1353 if( $wgCapitalLinks && $this->mInterwiki == '') {
1354 $t = $wgContLang->ucfirst( $r );
1355 } else {
1356 $t = $r;
1357 }
1358
1359 /**
1360 * Can't make a link to a namespace alone...
1361 * "empty" local links can only be self-links
1362 * with a fragment identifier.
1363 */
1364 if( $t == '' &&
1365 $this->mInterwiki == '' &&
1366 $this->mNamespace != NS_MAIN ) {
1367 wfProfileOut( $fname );
1368 return false;
1369 }
1370
1371 # Fill fields
1372 $this->mDbkeyform = $t;
1373 $this->mUrlform = wfUrlencode( $t );
1374
1375 $this->mTextform = str_replace( '_', ' ', $t );
1376
1377 wfProfileOut( $fname );
1378 return true;
1379 }
1380
1381 /**
1382 * Get a Title object associated with the talk page of this article
1383 * @return Title the object for the talk page
1384 * @access public
1385 */
1386 function getTalkPage() {
1387 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1388 }
1389
1390 /**
1391 * Get a title object associated with the subject page of this
1392 * talk page
1393 *
1394 * @return Title the object for the subject page
1395 * @access public
1396 */
1397 function getSubjectPage() {
1398 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1399 }
1400
1401 /**
1402 * Get an array of Title objects linking to this Title
1403 * Also stores the IDs in the link cache.
1404 *
1405 * @param string $options may be FOR UPDATE
1406 * @return array the Title objects linking here
1407 * @access public
1408 */
1409 function getLinksTo( $options = '' ) {
1410 global $wgLinkCache;
1411 $id = $this->getArticleID();
1412
1413 if ( $options ) {
1414 $db =& wfGetDB( DB_MASTER );
1415 } else {
1416 $db =& wfGetDB( DB_SLAVE );
1417 }
1418
1419 $res = $db->select( array( 'page', 'pagelinks' ),
1420 array( 'page_namespace', 'page_title', 'page_id' ),
1421 array(
1422 'pl_from=page_id',
1423 'pl_namespace' => $this->getNamespace(),
1424 'pl_title' => $this->getDbKey() ),
1425 'Title::getLinksTo',
1426 $options );
1427
1428 $retVal = array();
1429 if ( $db->numRows( $res ) ) {
1430 while ( $row = $db->fetchObject( $res ) ) {
1431 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1432 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1433 $retVal[] = $titleObj;
1434 }
1435 }
1436 }
1437 $db->freeResult( $res );
1438 return $retVal;
1439 }
1440
1441 /**
1442 * Get an array of Title objects referring to non-existent articles linked from this page
1443 *
1444 * @param string $options may be FOR UPDATE
1445 * @return array the Title objects
1446 * @access public
1447 */
1448 function getBrokenLinksFrom( $options = '' ) {
1449 global $wgLinkCache;
1450
1451 if ( $options ) {
1452 $db =& wfGetDB( DB_MASTER );
1453 } else {
1454 $db =& wfGetDB( DB_SLAVE );
1455 }
1456
1457 $res = $db->safeQuery(
1458 "SELECT pl_namespace, pl_title
1459 FROM !
1460 LEFT JOIN !
1461 ON pl_namespace=page_namespace
1462 AND pl_title=page_title
1463 WHERE pl_from=?
1464 AND page_namespace IS NULL
1465 !",
1466 $db->tableName( 'pagelinks' ),
1467 $db->tableName( 'page' ),
1468 $this->getArticleId(),
1469 $options );
1470
1471 $retVal = array();
1472 if ( $db->numRows( $res ) ) {
1473 while ( $row = $db->fetchObject( $res ) ) {
1474 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1475 }
1476 }
1477 $db->freeResult( $res );
1478 return $retVal;
1479 }
1480
1481
1482 /**
1483 * Get a list of URLs to purge from the Squid cache when this
1484 * page changes
1485 *
1486 * @return array the URLs
1487 * @access public
1488 */
1489 function getSquidURLs() {
1490 return array(
1491 $this->getInternalURL(),
1492 $this->getInternalURL( 'action=history' )
1493 );
1494 }
1495
1496 /**
1497 * Move this page without authentication
1498 * @param Title &$nt the new page Title
1499 * @access public
1500 */
1501 function moveNoAuth( &$nt ) {
1502 return $this->moveTo( $nt, false );
1503 }
1504
1505 /**
1506 * Check whether a given move operation would be valid.
1507 * Returns true if ok, or a message key string for an error message
1508 * if invalid. (Scarrrrry ugly interface this.)
1509 * @param Title &$nt the new title
1510 * @param bool $auth indicates whether $wgUser's permissions
1511 * should be checked
1512 * @return mixed true on success, message name on failure
1513 * @access public
1514 */
1515 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1516 global $wgUser;
1517 if( !$this or !$nt ) {
1518 return 'badtitletext';
1519 }
1520 if( $this->equals( $nt ) ) {
1521 return 'selfmove';
1522 }
1523 if( !$this->isMovable() || !$nt->isMovable() ) {
1524 return 'immobile_namespace';
1525 }
1526
1527 $fname = 'Title::move';
1528 $oldid = $this->getArticleID();
1529 $newid = $nt->getArticleID();
1530
1531 if ( strlen( $nt->getDBkey() ) < 1 ) {
1532 return 'articleexists';
1533 }
1534 if ( ( '' == $this->getDBkey() ) ||
1535 ( !$oldid ) ||
1536 ( '' == $nt->getDBkey() ) ) {
1537 return 'badarticleerror';
1538 }
1539
1540 if ( $auth && (
1541 !$this->userCanEdit() || !$nt->userCanEdit() ||
1542 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1543 return 'protectedpage';
1544 }
1545
1546 # The move is allowed only if (1) the target doesn't exist, or
1547 # (2) the target is a redirect to the source, and has no history
1548 # (so we can undo bad moves right after they're done).
1549
1550 if ( 0 != $newid ) { # Target exists; check for validity
1551 if ( ! $this->isValidMoveTarget( $nt ) ) {
1552 return 'articleexists';
1553 }
1554 }
1555 return true;
1556 }
1557
1558 /**
1559 * Move a title to a new location
1560 * @param Title &$nt the new title
1561 * @param bool $auth indicates whether $wgUser's permissions
1562 * should be checked
1563 * @return mixed true on success, message name on failure
1564 * @access public
1565 */
1566 function moveTo( &$nt, $auth = true, $reason = '' ) {
1567 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1568 if( is_string( $err ) ) {
1569 return $err;
1570 }
1571
1572 $pageid = $this->getArticleID();
1573 if( $nt->exists() ) {
1574 $this->moveOverExistingRedirect( $nt, $reason );
1575 $pageCountChange = 0;
1576 } else { # Target didn't exist, do normal move.
1577 $this->moveToNewTitle( $nt, $newid, $reason );
1578 $pageCountChange = 1;
1579 }
1580 $redirid = $this->getArticleID();
1581
1582 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1583 $dbw =& wfGetDB( DB_MASTER );
1584 $categorylinks = $dbw->tableName( 'categorylinks' );
1585 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1586 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1587 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1588 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1589
1590 # Update watchlists
1591
1592 $oldnamespace = $this->getNamespace() & ~1;
1593 $newnamespace = $nt->getNamespace() & ~1;
1594 $oldtitle = $this->getDBkey();
1595 $newtitle = $nt->getDBkey();
1596
1597 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1598 WatchedItem::duplicateEntries( $this, $nt );
1599 }
1600
1601 # Update search engine
1602 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1603 $u->doUpdate();
1604 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1605 $u->doUpdate();
1606
1607 # Update site_stats
1608 if ( $this->getNamespace() == NS_MAIN and $nt->getNamespace() != NS_MAIN ) {
1609 # Moved out of main namespace
1610 # not viewed, edited, removing
1611 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1612 } elseif ( $this->getNamespace() != NS_MAIN and $nt->getNamespace() == NS_MAIN ) {
1613 # Moved into main namespace
1614 # not viewed, edited, adding
1615 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1616 } elseif ( $pageCountChange ) {
1617 # Added redirect
1618 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1619 } else{
1620 $u = false;
1621 }
1622 if ( $u ) {
1623 $u->doUpdate();
1624 }
1625
1626 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1627 return true;
1628 }
1629
1630 /**
1631 * Move page to a title which is at present a redirect to the
1632 * source page
1633 *
1634 * @param Title &$nt the page to move to, which should currently
1635 * be a redirect
1636 * @access private
1637 */
1638 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1639 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1640 $fname = 'Title::moveOverExistingRedirect';
1641 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1642
1643 if ( $reason ) {
1644 $comment .= ": $reason";
1645 }
1646
1647 $now = wfTimestampNow();
1648 $rand = wfRandom();
1649 $newid = $nt->getArticleID();
1650 $oldid = $this->getArticleID();
1651 $dbw =& wfGetDB( DB_MASTER );
1652 $links = $dbw->tableName( 'links' );
1653
1654 # Delete the old redirect. We don't save it to history since
1655 # by definition if we've got here it's rather uninteresting.
1656 # We have to remove it so that the next step doesn't trigger
1657 # a conflict on the unique namespace+title index...
1658 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1659
1660 # Save a null revision in the page's history notifying of the move
1661 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1662 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1663 true );
1664 $nullRevId = $nullRevision->insertOn( $dbw );
1665
1666 # Change the name of the target page:
1667 $dbw->update( 'page',
1668 /* SET */ array(
1669 'page_touched' => $dbw->timestamp($now),
1670 'page_namespace' => $nt->getNamespace(),
1671 'page_title' => $nt->getDBkey(),
1672 'page_latest' => $nullRevId,
1673 ),
1674 /* WHERE */ array( 'page_id' => $oldid ),
1675 $fname
1676 );
1677 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1678
1679 # Recreate the redirect, this time in the other direction.
1680 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1681 $redirectArticle = new Article( $this );
1682 $newid = $redirectArticle->insertOn( $dbw );
1683 $redirectRevision = new Revision( array(
1684 'page' => $newid,
1685 'comment' => $comment,
1686 'text' => $redirectText ) );
1687 $revid = $redirectRevision->insertOn( $dbw );
1688 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1689 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1690
1691 # Log the move
1692 $log = new LogPage( 'move' );
1693 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1694
1695 # Now, we record the link from the redirect to the new title.
1696 # It should have no other outgoing links...
1697 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1698 $dbw->insert( 'pagelinks',
1699 array(
1700 'pl_from' => $newid,
1701 'pl_namespace' => $nt->getNamespace(),
1702 'pl_title' => $nt->getDbKey() ),
1703 $fname );
1704
1705 # Purge squid
1706 if ( $wgUseSquid ) {
1707 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1708 $u = new SquidUpdate( $urls );
1709 $u->doUpdate();
1710 }
1711 }
1712
1713 /**
1714 * Move page to non-existing title.
1715 * @param Title &$nt the new Title
1716 * @param int &$newid set to be the new article ID
1717 * @access private
1718 */
1719 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1720 global $wgUser, $wgLinkCache, $wgUseSquid;
1721 global $wgMwRedir;
1722 $fname = 'MovePageForm::moveToNewTitle';
1723 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1724 if ( $reason ) {
1725 $comment .= ": $reason";
1726 }
1727
1728 $newid = $nt->getArticleID();
1729 $oldid = $this->getArticleID();
1730 $dbw =& wfGetDB( DB_MASTER );
1731 $now = $dbw->timestamp();
1732 wfSeedRandom();
1733 $rand = wfRandom();
1734
1735 # Save a null revision in the page's history notifying of the move
1736 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1737 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1738 true );
1739 $nullRevId = $nullRevision->insertOn( $dbw );
1740
1741 # Rename cur entry
1742 $dbw->update( 'page',
1743 /* SET */ array(
1744 'page_touched' => $now,
1745 'page_namespace' => $nt->getNamespace(),
1746 'page_title' => $nt->getDBkey(),
1747 'page_latest' => $nullRevId,
1748 ),
1749 /* WHERE */ array( 'page_id' => $oldid ),
1750 $fname
1751 );
1752
1753 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1754
1755 # Insert redirect
1756 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1757 $redirectArticle = new Article( $this );
1758 $newid = $redirectArticle->insertOn( $dbw );
1759 $redirectRevision = new Revision( array(
1760 'page' => $newid,
1761 'comment' => $comment,
1762 'text' => $redirectText ) );
1763 $revid = $redirectRevision->insertOn( $dbw );
1764 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1765 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1766
1767 # Log the move
1768 $log = new LogPage( 'move' );
1769 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1770
1771 # Purge caches as per article creation
1772 Article::onArticleCreate( $nt );
1773
1774 # Record the just-created redirect's linking to the page
1775 $dbw->insert( 'pagelinks',
1776 array(
1777 'pl_from' => $newid,
1778 'pl_namespace' => $nt->getNamespace(),
1779 'pl_title' => $nt->getDBkey() ),
1780 $fname );
1781
1782 # Non-existent target may have had broken links to it; these must
1783 # now be touched to update link coloring.
1784 $nt->touchLinks();
1785
1786 # Purge old title from squid
1787 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1788 $titles = $nt->getLinksTo();
1789 if ( $wgUseSquid ) {
1790 $urls = $this->getSquidURLs();
1791 foreach ( $titles as $linkTitle ) {
1792 $urls[] = $linkTitle->getInternalURL();
1793 }
1794 $u = new SquidUpdate( $urls );
1795 $u->doUpdate();
1796 }
1797 }
1798
1799 /**
1800 * Checks if $this can be moved to a given Title
1801 * - Selects for update, so don't call it unless you mean business
1802 *
1803 * @param Title &$nt the new title to check
1804 * @access public
1805 */
1806 function isValidMoveTarget( $nt ) {
1807
1808 $fname = 'Title::isValidMoveTarget';
1809 $dbw =& wfGetDB( DB_MASTER );
1810
1811 # Is it a redirect?
1812 $id = $nt->getArticleID();
1813 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1814 array( 'page_is_redirect','old_text' ),
1815 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1816 $fname, 'FOR UPDATE' );
1817
1818 if ( !$obj || 0 == $obj->page_is_redirect ) {
1819 # Not a redirect
1820 return false;
1821 }
1822
1823 # Does the redirect point to the source?
1824 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1825 $redirTitle = Title::newFromText( $m[1] );
1826 if( !is_object( $redirTitle ) ||
1827 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1828 return false;
1829 }
1830 }
1831
1832 # Does the article have a history?
1833 $row = $dbw->selectRow( array( 'page', 'revision'),
1834 array( 'rev_id' ),
1835 array( 'page_namespace' => $nt->getNamespace(),
1836 'page_title' => $nt->getDBkey(),
1837 'page_id=rev_page AND page_latest != rev_id'
1838 ), $fname, 'FOR UPDATE'
1839 );
1840
1841 # Return true if there was no history
1842 return $row === false;
1843 }
1844
1845 /**
1846 * Create a redirect; fails if the title already exists; does
1847 * not notify RC
1848 *
1849 * @param Title $dest the destination of the redirect
1850 * @param string $comment the comment string describing the move
1851 * @return bool true on success
1852 * @access public
1853 */
1854 function createRedirect( $dest, $comment ) {
1855 global $wgUser;
1856 if ( $this->getArticleID() ) {
1857 return false;
1858 }
1859
1860 $fname = 'Title::createRedirect';
1861 $dbw =& wfGetDB( DB_MASTER );
1862
1863 $article = new Article( $this );
1864 $newid = $article->insertOn( $dbw );
1865 $revision = new Revision( array(
1866 'page' => $newid,
1867 'comment' => $comment,
1868 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1869 ) );
1870 $revisionId = $revision->insertOn( $dbw );
1871 $article->updateRevisionOn( $dbw, $revision, 0 );
1872
1873 # Link table
1874 $dbw->insert( 'pagelinks',
1875 array(
1876 'pl_from' => $newid,
1877 'pl_namespace' => $dest->getNamespace(),
1878 'pl_title' => $dest->getDbKey()
1879 ), $fname
1880 );
1881
1882 Article::onArticleCreate( $this );
1883 return true;
1884 }
1885
1886 /**
1887 * Get categories to which this Title belongs and return an array of
1888 * categories' names.
1889 *
1890 * @return array an array of parents in the form:
1891 * $parent => $currentarticle
1892 * @access public
1893 */
1894 function getParentCategories() {
1895 global $wgContLang,$wgUser;
1896
1897 $titlekey = $this->getArticleId();
1898 $sk =& $wgUser->getSkin();
1899 $parents = array();
1900 $dbr =& wfGetDB( DB_SLAVE );
1901 $categorylinks = $dbr->tableName( 'categorylinks' );
1902
1903 # NEW SQL
1904 $sql = "SELECT * FROM $categorylinks"
1905 ." WHERE cl_from='$titlekey'"
1906 ." AND cl_from <> '0'"
1907 ." ORDER BY cl_sortkey";
1908
1909 $res = $dbr->query ( $sql ) ;
1910
1911 if($dbr->numRows($res) > 0) {
1912 while ( $x = $dbr->fetchObject ( $res ) )
1913 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1914 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1915 $dbr->freeResult ( $res ) ;
1916 } else {
1917 $data = '';
1918 }
1919 return $data;
1920 }
1921
1922 /**
1923 * Get a tree of parent categories
1924 * @param array $children an array with the children in the keys, to check for circular refs
1925 * @return array
1926 * @access public
1927 */
1928 function getParentCategoryTree( $children = array() ) {
1929 $parents = $this->getParentCategories();
1930
1931 if($parents != '') {
1932 foreach($parents as $parent => $current)
1933 {
1934 if ( array_key_exists( $parent, $children ) ) {
1935 # Circular reference
1936 $stack[$parent] = array();
1937 } else {
1938 $nt = Title::newFromText($parent);
1939 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1940 }
1941 }
1942 return $stack;
1943 } else {
1944 return array();
1945 }
1946 }
1947
1948
1949 /**
1950 * Get an associative array for selecting this title from
1951 * the "cur" table
1952 *
1953 * @return array
1954 * @access public
1955 */
1956 function curCond() {
1957 wfDebugDieBacktrace( 'curCond called' );
1958 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1959 }
1960
1961 /**
1962 * Get an associative array for selecting this title from the
1963 * "old" table
1964 *
1965 * @return array
1966 * @access public
1967 */
1968 function oldCond() {
1969 wfDebugDieBacktrace( 'oldCond called' );
1970 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1971 }
1972
1973 /**
1974 * Get the revision ID of the previous revision
1975 *
1976 * @param integer $revision Revision ID. Get the revision that was before this one.
1977 * @return interger $oldrevision|false
1978 */
1979 function getPreviousRevisionID( $revision ) {
1980 $dbr =& wfGetDB( DB_SLAVE );
1981 return $dbr->selectField( 'revision', 'rev_id',
1982 'rev_page=' . IntVal( $this->getArticleId() ) .
1983 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1984 }
1985
1986 /**
1987 * Get the revision ID of the next revision
1988 *
1989 * @param integer $revision Revision ID. Get the revision that was after this one.
1990 * @return interger $oldrevision|false
1991 */
1992 function getNextRevisionID( $revision ) {
1993 $dbr =& wfGetDB( DB_SLAVE );
1994 return $dbr->selectField( 'revision', 'rev_id',
1995 'rev_page=' . IntVal( $this->getArticleId() ) .
1996 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1997 }
1998
1999 /**
2000 * Compare with another title.
2001 *
2002 * @param Title $title
2003 * @return bool
2004 */
2005 function equals( &$title ) {
2006 return $this->getInterwiki() == $title->getInterwiki()
2007 && $this->getNamespace() == $title->getNamespace()
2008 && $this->getDbkey() == $title->getDbkey();
2009 }
2010
2011 /**
2012 * Check if page exists
2013 * @return bool
2014 */
2015 function exists() {
2016 return $this->getArticleId() != 0;
2017 }
2018
2019 /**
2020 * Should a link should be displayed as a known link, just based on its title?
2021 *
2022 * Currently, a self-link with a fragment, special pages and image pages are in
2023 * this category. Special pages never exist in the database. Some images do not
2024 * have description pages in the database, but the description page contains
2025 * useful history information that the user may want to link to.
2026 */
2027 function isAlwaysKnown() {
2028 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2029 || NS_SPECIAL == $this->mNamespace || NS_IMAGE == $this->mNamespace;
2030 }
2031
2032 /**
2033 * Update page_touched timestamps on pages linking to this title.
2034 * In principal, this could be backgrounded and could also do squid
2035 * purging.
2036 */
2037 function touchLinks() {
2038 $fname = 'Title::touchLinks';
2039
2040 $dbw =& wfGetDB( DB_MASTER );
2041
2042 $res = $dbw->select( 'pagelinks',
2043 array( 'pl_from' ),
2044 array(
2045 'pl_namespace' => $this->getNamespace(),
2046 'pl_title' => $this->getDbKey() ),
2047 $fname );
2048 if ( 0 == $dbw->numRows( $res ) ) {
2049 return;
2050 }
2051
2052 $arr = array();
2053 $toucharr = array();
2054 while( $row = $dbw->fetchObject( $res ) ) {
2055 $toucharr[] = $row->pl_from;
2056 }
2057
2058 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2059 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2060 }
2061 }
2062 ?>