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