203027f8a84b0e958b4f821c936820ac7cc7362c
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 # $Id$
3 #
4 # Class representing a Wikipedia article and history.
5 # See design.doc for an overview.
6
7 # Note: edit user interface and cache support functions have been
8 # moved to separate EditPage and CacheManager classes.
9
10 require_once( 'CacheManager.php' );
11
12 class Article {
13 /* private */ var $mContent, $mContentLoaded;
14 /* private */ var $mUser, $mTimestamp, $mUserText;
15 /* private */ var $mCounter, $mComment, $mCountAdjustment;
16 /* private */ var $mMinorEdit, $mRedirectedFrom;
17 /* private */ var $mTouched, $mFileCache, $mTitle;
18 /* private */ var $mId, $mTable;
19
20 function Article( &$title ) {
21 $this->mTitle =& $title;
22 $this->clear();
23 }
24
25 /* private */ function clear()
26 {
27 $this->mContentLoaded = false;
28 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
29 $this->mRedirectedFrom = $this->mUserText =
30 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
31 $this->mCountAdjustment = 0;
32 $this->mTouched = '19700101000000';
33 }
34
35 # Get revision text associated with an old or archive row
36 # $row is usually an object from wfFetchRow(), both the flags and the text field must be included
37 /* static */ function getRevisionText( $row, $prefix = 'old_' ) {
38 # Get data
39 $textField = $prefix . 'text';
40 $flagsField = $prefix . 'flags';
41
42 if ( isset( $row->$flagsField ) ) {
43 $flags = explode( ",", $row->$flagsField );
44 } else {
45 $flags = array();
46 }
47
48 if ( isset( $row->$textField ) ) {
49 $text = $row->$textField;
50 } else {
51 return false;
52 }
53
54 if ( in_array( 'link', $flags ) ) {
55 # Handle link type
56 $text = Article::followLink( $text );
57 } elseif ( in_array( 'gzip', $flags ) ) {
58 # Deal with optional compression of archived pages.
59 # This can be done periodically via maintenance/compressOld.php, and
60 # as pages are saved if $wgCompressRevisions is set.
61 return gzinflate( $text );
62 }
63 return $text;
64 }
65
66 /* static */ function compressRevisionText( &$text ) {
67 global $wgCompressRevisions;
68 if( !$wgCompressRevisions ) {
69 return '';
70 }
71 if( !function_exists( 'gzdeflate' ) ) {
72 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
73 return '';
74 }
75 $text = gzdeflate( $text );
76 return 'gzip';
77 }
78
79 # Returns the text associated with a "link" type old table row
80 /* static */ function followLink( $link ) {
81 # Split the link into fields and values
82 $lines = explode( '\n', $link );
83 $hash = '';
84 $locations = array();
85 foreach ( $lines as $line ) {
86 # Comments
87 if ( $line{0} == '#' ) {
88 continue;
89 }
90 # Field/value pairs
91 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
92 $field = strtolower($matches[1]);
93 $value = $matches[2];
94 if ( $field == 'hash' ) {
95 $hash = $value;
96 } elseif ( $field == 'location' ) {
97 $locations[] = $value;
98 }
99 }
100 }
101
102 if ( $hash === '' ) {
103 return false;
104 }
105
106 # Look in each specified location for the text
107 $text = false;
108 foreach ( $locations as $location ) {
109 $text = Article::fetchFromLocation( $location, $hash );
110 if ( $text !== false ) {
111 break;
112 }
113 }
114
115 return $text;
116 }
117
118 /* static */ function fetchFromLocation( $location, $hash ) {
119 global $wgDatabase, $wgKnownDBServers;
120 $fname = 'fetchFromLocation';
121 wfProfileIn( $fname );
122
123 $p = strpos( $location, ':' );
124 if ( $p === false ) {
125 wfProfileOut( $fname );
126 return false;
127 }
128
129 $type = substr( $location, 0, $p );
130 $text = false;
131 switch ( $type ) {
132 case 'mysql':
133 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
134 # Machine ID 0 is the current connection
135 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
136 $location, $matches ) ) {
137 $machineID = $matches[1];
138 $dbName = $matches[2];
139 $tblName = $matches[3];
140 $index = $matches[4];
141 if ( $machineID == 0 ) {
142 # Current connection
143 $db =& wfGetDB();
144 } else {
145 # Alternate connection
146 $db =& $wgLoadBalancer->getConnection( $machineID );
147
148 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
149 # Try to open, return false on failure
150 $params = $wgKnownDBServers[$machineId];
151 $db = Database::newFromParams( $params['server'], $params['user'], $params['password'],
152 $dbName, 1, false, true, true );
153 }
154 }
155 if ( $db->isOpen() ) {
156 $index = wfStrencode( $index );
157 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName WHERE blob_index='$index'", $fname );
158 $row = $db->fetchObject( $res );
159 $text = $row->text_data;
160 }
161 }
162 break;
163 case 'file':
164 # File locations are of the form file://<filename>, relative to the current directory
165 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
166 $filename = strstr( $location, 'file://' );
167 $text = @file_get_contents( $matches[1] );
168 }
169 if ( $text !== false ) {
170 # Got text, now we need to interpret it
171 # The first line contains information about how to do this
172 $p = strpos( $text, '\n' );
173 $type = substr( $text, 0, $p );
174 $text = substr( $text, $p + 1 );
175 switch ( $type ) {
176 case 'plain':
177 break;
178 case 'gzip':
179 $text = gzinflate( $text );
180 break;
181 case 'object':
182 $object = unserialize( $text );
183 $text = $object->getItem( $hash );
184 break;
185 default:
186 $text = false;
187 }
188 }
189 wfProfileOut( $fname );
190 return $text;
191 }
192
193 # Note that getContent/loadContent may follow redirects if
194 # not told otherwise, and so may cause a change to mTitle.
195
196 # Return the text of this revision
197 function getContent( $noredir )
198 {
199 global $wgRequest;
200
201 # Get variables from query string :P
202 $action = $wgRequest->getText( 'action', 'view' );
203 $section = $wgRequest->getText( 'section' );
204
205 $fname = 'Article::getContent';
206 wfProfileIn( $fname );
207
208 if ( 0 == $this->getID() ) {
209 if ( 'edit' == $action ) {
210 wfProfileOut( $fname );
211 return ''; # was "newarticletext", now moved above the box)
212 }
213 wfProfileOut( $fname );
214 return wfMsg( 'noarticletext' );
215 } else {
216 $this->loadContent( $noredir );
217
218 if(
219 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
220 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
221 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle->getText()) &&
222 $action=='view'
223 )
224 {
225 wfProfileOut( $fname );
226 return $this->mContent . "\n" .wfMsg('anontalkpagetext'); }
227 else {
228 if($action=='edit') {
229 if($section!='') {
230 if($section=='new') {
231 wfProfileOut( $fname );
232 return '';
233 }
234
235 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
236 # comments to be stripped as well)
237 $rv=$this->getSection($this->mContent,$section);
238 wfProfileOut( $fname );
239 return $rv;
240 }
241 }
242 wfProfileOut( $fname );
243 return $this->mContent;
244 }
245 }
246 }
247
248 # This function returns the text of a section, specified by a number ($section).
249 # A section is text under a heading like == Heading == or <h1>Heading</h1>, or
250 # the first section before any such heading (section 0).
251 #
252 # If a section contains subsections, these are also returned.
253 #
254 function getSection($text,$section) {
255
256 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
257 # comments to be stripped as well)
258 $striparray=array();
259 $parser=new Parser();
260 $parser->mOutputType=OT_WIKI;
261 $striptext=$parser->strip($text, $striparray, true);
262
263 # now that we can be sure that no pseudo-sections are in the source,
264 # split it up by section
265 $secs =
266 preg_split(
267 '/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
268 $striptext, -1,
269 PREG_SPLIT_DELIM_CAPTURE);
270 if($section==0) {
271 $rv=$secs[0];
272 } else {
273 $headline=$secs[$section*2-1];
274 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
275 $hlevel=$matches[1];
276
277 # translate wiki heading into level
278 if(strpos($hlevel,'=')!==false) {
279 $hlevel=strlen($hlevel);
280 }
281
282 $rv=$headline. $secs[$section*2];
283 $count=$section+1;
284
285 $break=false;
286 while(!empty($secs[$count*2-1]) && !$break) {
287
288 $subheadline=$secs[$count*2-1];
289 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
290 $subhlevel=$matches[1];
291 if(strpos($subhlevel,'=')!==false) {
292 $subhlevel=strlen($subhlevel);
293 }
294 if($subhlevel > $hlevel) {
295 $rv.=$subheadline.$secs[$count*2];
296 }
297 if($subhlevel <= $hlevel) {
298 $break=true;
299 }
300 $count++;
301
302 }
303 }
304 # reinsert stripped tags
305 $rv=$parser->unstrip($rv,$striparray);
306 $rv=$parser->unstripNoWiki($rv,$striparray);
307 $rv=trim($rv);
308 return $rv;
309
310 }
311
312
313 # Load the revision (including cur_text) into this object
314 function loadContent( $noredir = false )
315 {
316 global $wgOut, $wgMwRedir, $wgRequest, $wgIsPg;
317
318 # Query variables :P
319 $oldid = $wgRequest->getVal( 'oldid' );
320 $redirect = $wgRequest->getVal( 'redirect' );
321
322 if ( $this->mContentLoaded ) return;
323 $fname = 'Article::loadContent';
324
325 # Pre-fill content with error message so that if something
326 # fails we'll have something telling us what we intended.
327
328 $t = $this->mTitle->getPrefixedText();
329 if ( isset( $oldid ) ) {
330 $oldid = IntVal( $oldid );
331 $t .= ",oldid={$oldid}";
332 }
333 if ( isset( $redirect ) ) {
334 $redirect = ($redirect == 'no') ? 'no' : 'yes';
335 $t .= ",redirect={$redirect}";
336 }
337 $this->mContent = wfMsg( 'missingarticle', $t );
338
339 if ( ! $oldid ) { # Retrieve current version
340 $id = $this->getID();
341 if ( 0 == $id ) return;
342
343 $sql = 'SELECT ' .
344 'cur_text,cur_timestamp,cur_user,cur_user_text,cur_comment,cur_counter,cur_restrictions,cur_touched ' .
345 "FROM cur WHERE cur_id={$id}";
346 wfDebug( "$sql\n" );
347 $res = wfQuery( $sql, DB_READ, $fname );
348 if ( 0 == wfNumRows( $res ) ) {
349 return;
350 }
351
352 $s = wfFetchObject( $res );
353 # If we got a redirect, follow it (unless we've been told
354 # not to by either the function parameter or the query
355 if ( ( 'no' != $redirect ) && ( false == $noredir ) &&
356 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
357 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
358 $s->cur_text, $m ) ) {
359 $rt = Title::newFromText( $m[1] );
360 if( $rt ) {
361 # Gotta hand redirects to special pages differently:
362 # Fill the HTTP response "Location" header and ignore
363 # the rest of the page we're on.
364
365 if ( $rt->getInterwiki() != '' ) {
366 $wgOut->redirect( $rt->getFullURL() ) ;
367 return;
368 }
369 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
370 $wgOut->redirect( $rt->getFullURL() );
371 return;
372 }
373 $rid = $rt->getArticleID();
374 if ( 0 != $rid ) {
375 $sql = 'SELECT cur_text,cur_timestamp,cur_user,cur_user_text,cur_comment,' .
376 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
377 $res = wfQuery( $sql, DB_READ, $fname );
378
379 if ( 0 != wfNumRows( $res ) ) {
380 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
381 $this->mTitle = $rt;
382 $s = wfFetchObject( $res );
383 }
384 }
385 }
386 }
387 }
388
389 $this->mContent = $s->cur_text;
390 $this->mUser = $s->cur_user;
391 $this->mUserText = $s->cur_user_text;
392 $this->mComment = $s->cur_comment;
393 $this->mCounter = $s->cur_counter;
394 $this->mTimestamp = $s->cur_timestamp;
395 $this->mTouched = $s->cur_touched;
396 $this->mTitle->mRestrictions = explode( ',', trim( $s->cur_restrictions ) );
397 $this->mTitle->mRestrictionsLoaded = true;
398 wfFreeResult( $res );
399 } else { # oldid set, retrieve historical version
400 $oldtable=$wgIsPg?'"old"':'old';
401 $sql = "SELECT old_namespace,old_title,old_text,old_timestamp,".
402 "old_user,old_user_text,old_comment,old_flags FROM old ".
403 "WHERE old_id={$oldid}";
404 $res = wfQuery( $sql, DB_READ, $fname );
405 if ( 0 == wfNumRows( $res ) ) {
406 return;
407 }
408
409 $s = wfFetchObject( $res );
410 if( $this->mTitle->getNamespace() != $s->old_namespace ||
411 $this->mTitle->getDBkey() != $s->old_title ) {
412 $oldTitle = Title::makeTitle( $s->old_namesapce, $s->old_title );
413 $this->mTitle = $oldTitle;
414 $wgTitle = $oldTitle;
415 }
416 $this->mContent = Article::getRevisionText( $s );
417 $this->mUser = $s->old_user;
418 $this->mUserText = $s->old_user_text;
419 $this->mComment = $s->old_comment;
420 $this->mCounter = 0;
421 $this->mTimestamp = $s->old_timestamp;
422 wfFreeResult( $res );
423 }
424 $this->mContentLoaded = true;
425 return $this->mContent;
426 }
427
428 # Gets the article text without using so many damn globals
429 # Returns false on error
430 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
431 global $wgMwRedir, $wgIsPg;
432
433 if ( $this->mContentLoaded ) {
434 return $this->mContent;
435 }
436 $this->mContent = false;
437
438 $fname = 'Article::loadContent';
439
440 if ( ! $oldid ) { # Retrieve current version
441 $id = $this->getID();
442 if ( 0 == $id ) {
443 return false;
444 }
445
446 $sql = 'SELECT ' .
447 'cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched ' .
448 "FROM cur WHERE cur_id={$id}";
449 $res = wfQuery( $sql, DB_READ, $fname );
450 if ( 0 == wfNumRows( $res ) ) {
451 return false;
452 }
453
454 $s = wfFetchObject( $res );
455 # If we got a redirect, follow it (unless we've been told
456 # not to by either the function parameter or the query
457 if ( !$noredir && $wgMwRedir->matchStart( $s->cur_text ) ) {
458 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
459 $s->cur_text, $m ) ) {
460 $rt = Title::newFromText( $m[1] );
461 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != Namespace::getSpecial() ) {
462 $rid = $rt->getArticleID();
463 if ( 0 != $rid ) {
464 $sql = 'SELECT cur_text,cur_timestamp,cur_user,' .
465 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
466 $res = wfQuery( $sql, DB_READ, $fname );
467
468 if ( 0 != wfNumRows( $res ) ) {
469 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
470 $this->mTitle = $rt;
471 $s = wfFetchObject( $res );
472 }
473 }
474 }
475 }
476 }
477
478 $this->mContent = $s->cur_text;
479 $this->mUser = $s->cur_user;
480 $this->mCounter = $s->cur_counter;
481 $this->mTimestamp = $s->cur_timestamp;
482 $this->mTouched = $s->cur_touched;
483 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
484 $this->mTitle->mRestrictionsLoaded = true;
485 wfFreeResult( $res );
486 } else { # oldid set, retrieve historical version
487 $oldtable=$wgIsPg?'"old"':'old';
488 $sql = "SELECT old_text,old_timestamp,old_user,old_flags FROM $oldtable " .
489 "WHERE old_id={$oldid}";
490 $res = wfQuery( $sql, DB_READ, $fname );
491 if ( 0 == wfNumRows( $res ) ) {
492 return false;
493 }
494
495 $s = wfFetchObject( $res );
496 $this->mContent = Article::getRevisionText( $s );
497 $this->mUser = $s->old_user;
498 $this->mCounter = 0;
499 $this->mTimestamp = $s->old_timestamp;
500 wfFreeResult( $res );
501 }
502 $this->mContentLoaded = true;
503 return $this->mContent;
504 }
505
506 function getID() {
507 if( $this->mTitle ) {
508 return $this->mTitle->getArticleID();
509 } else {
510 return 0;
511 }
512 }
513
514 function getCount()
515 {
516 if ( -1 == $this->mCounter ) {
517 $id = $this->getID();
518 $this->mCounter = wfGetSQL( 'cur', 'cur_counter', "cur_id={$id}" );
519 }
520 return $this->mCounter;
521 }
522
523 # Would the given text make this article a "good" article (i.e.,
524 # suitable for including in the article count)?
525
526 function isCountable( $text )
527 {
528 global $wgUseCommaCount, $wgMwRedir;
529
530 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
531 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
532 $token = ($wgUseCommaCount ? ',' : '[[' );
533 if ( false === strstr( $text, $token ) ) { return 0; }
534 return 1;
535 }
536
537 # Loads everything from cur except cur_text
538 # This isn't necessary for all uses, so it's only done if needed.
539
540 /* private */ function loadLastEdit()
541 {
542 global $wgOut;
543 if ( -1 != $this->mUser ) return;
544
545 $sql = 'SELECT cur_user,cur_user_text,cur_timestamp,' .
546 'cur_comment,cur_minor_edit FROM cur WHERE ' .
547 'cur_id=' . $this->getID();
548 $res = wfQuery( $sql, DB_READ, 'Article::loadLastEdit' );
549
550 if ( wfNumRows( $res ) > 0 ) {
551 $s = wfFetchObject( $res );
552 $this->mUser = $s->cur_user;
553 $this->mUserText = $s->cur_user_text;
554 $this->mTimestamp = $s->cur_timestamp;
555 $this->mComment = $s->cur_comment;
556 $this->mMinorEdit = $s->cur_minor_edit;
557 }
558 }
559
560 function getTimestamp()
561 {
562 $this->loadLastEdit();
563 return $this->mTimestamp;
564 }
565
566 function getUser()
567 {
568 $this->loadLastEdit();
569 return $this->mUser;
570 }
571
572 function getUserText()
573 {
574 $this->loadLastEdit();
575 return $this->mUserText;
576 }
577
578 function getComment()
579 {
580 $this->loadLastEdit();
581 return $this->mComment;
582 }
583
584 function getMinorEdit()
585 {
586 $this->loadLastEdit();
587 return $this->mMinorEdit;
588 }
589
590 function getContributors($limit = 0, $offset = 0)
591 {
592 $fname = 'Article::getContributors';
593
594 # XXX: this is expensive; cache this info somewhere.
595
596 $title = $this->mTitle;
597
598 $contribs = array();
599
600 $sql = 'SELECT old.old_user, old.old_user_text, ' .
601 ' user.user_real_name, MAX(old.old_timestamp) as timestamp' .
602 ' FROM old, user ' .
603 ' WHERE old.old_user = user.user_id ' .
604 ' AND old.old_namespace = ' . $title->getNamespace() .
605 ' AND old.old_title = "' . $title->getDBkey() . '"' .
606 ' AND old.old_user != 0 ' .
607 ' AND old.old_user != ' . $this->getUser() .
608 ' GROUP BY old.old_user ' .
609 ' ORDER BY timestamp DESC ';
610
611 if ($limit > 0) {
612 $sql .= ' LIMIT '.$limit;
613 }
614
615 $res = wfQuery($sql, DB_READ, $fname);
616
617 while ( $line = wfFetchObject( $res ) ) {
618 $contribs[$line->old_user] =
619 array($line->old_user_text, $line->user_real_name);
620 }
621
622 # Count anonymous users
623
624 $res = wfQuery('SELECT COUNT(*) AS cnt ' .
625 ' FROM old ' .
626 ' WHERE old_namespace = ' . $title->getNamespace() .
627 " AND old_title = '" . $title->getDBkey() . "'" .
628 ' AND old_user = 0 ', DB_READ, $fname);
629
630 while ( $line = wfFetchObject( $res ) ) {
631 $contribs[0] = array($line->cnt, 'Anonymous');
632 }
633
634 return $contribs;
635 }
636
637 # This is the default action of the script: just view the page of
638 # the given title.
639
640 function view()
641 {
642 global $wgUser, $wgOut, $wgLang, $wgRequest;
643 global $wgLinkCache, $IP, $wgEnableParserCache;
644
645 $fname = 'Article::view';
646 wfProfileIn( $fname );
647
648 # Get variables from query string :P
649 $oldid = $wgRequest->getVal( 'oldid' );
650 $diff = $wgRequest->getVal( 'diff' );
651
652 $wgOut->setArticleFlag( true );
653 $wgOut->setRobotpolicy( 'index,follow' );
654
655 # If we got diff and oldid in the query, we want to see a
656 # diff page instead of the article.
657
658 if ( !is_null( $diff ) ) {
659 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
660 $de = new DifferenceEngine( intval($oldid), intval($diff) );
661 $de->showDiffPage();
662 wfProfileOut( $fname );
663 return;
664 }
665
666 if ( !is_null( $oldid ) and $this->checkTouched() ) {
667 if( $wgOut->checkLastModified( $this->mTouched ) ){
668 return;
669 } else if ( $this->tryFileCache() ) {
670 # tell wgOut that output is taken care of
671 $wgOut->disable();
672 $this->viewUpdates();
673 return;
674 }
675 }
676
677 # Should the parser cache be used?
678 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
679 $pcache = true;
680 } else {
681 $pcache = false;
682 }
683
684 $outputDone = false;
685 if ( $pcache ) {
686 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
687 $outputDone = true;
688 }
689 }
690
691 if ( !$outputDone ) {
692 $text = $this->getContent( false ); # May change mTitle by following a redirect
693
694 # Another whitelist check in case oldid or redirects are altering the title
695 if ( !$this->mTitle->userCanRead() ) {
696 $wgOut->loginToUse();
697 $wgOut->output();
698 exit;
699 }
700
701
702 # We're looking at an old revision
703
704 if ( !empty( $oldid ) ) {
705 $this->setOldSubtitle();
706 $wgOut->setRobotpolicy( 'noindex,follow' );
707 }
708 if ( '' != $this->mRedirectedFrom ) {
709 $sk = $wgUser->getSkin();
710 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
711 'redirect=no' );
712 $s = wfMsg( 'redirectedfrom', $redir );
713 $wgOut->setSubtitle( $s );
714
715 # Can't cache redirects
716 $pcache = false;
717 }
718
719 $wgLinkCache->preFill( $this->mTitle );
720
721 # wrap user css and user js in pre and don't parse
722 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
723 if (
724 $this->mTitle->getNamespace() == Namespace::getUser() &&
725 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
726 ) {
727 $wgOut->addWikiText( wfMsg('clearyourcache'));
728 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
729 } else if ( $pcache ) {
730 $wgOut->addWikiText( $text, true, $this );
731 } else {
732 $wgOut->addWikiText( $text );
733 }
734 }
735 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
736
737 # Add link titles as META keywords
738 $wgOut->addMetaTags() ;
739
740 $this->viewUpdates();
741 wfProfileOut( $fname );
742 }
743
744 # Theoretically we could defer these whole insert and update
745 # functions for after display, but that's taking a big leap
746 # of faith, and we want to be able to report database
747 # errors at some point.
748
749 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
750 {
751 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
752 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgIsPg, $wgIsMySQL;
753
754 $fname = 'Article::insertNewArticle';
755
756 $this->mCountAdjustment = $this->isCountable( $text );
757
758 $ns = $this->mTitle->getNamespace();
759 $ttl = $this->mTitle->getDBkey();
760 $text = $this->preSaveTransform( $text );
761 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
762 else { $redir = 0; }
763
764 $now = wfTimestampNow();
765 $won = wfInvertTimestamp( $now );
766 wfSeedRandom();
767 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
768
769 if ($wgIsPg) {
770 $cur_id_column="cur_id,";
771 $cur_id=wfGetSQL(""," nextval('cur_cur_id_seq')");
772 $cur_id_value="{$cur_id},";
773 } else {
774 $cur_id_column="";
775 $cur_id="";
776 $cur_id_value="";
777 }
778
779 $isminor = ( $isminor && $wgUser->getID() ) ? 1 : 0;
780 $sql = "INSERT INTO cur ({$cur_id_column}cur_namespace,cur_title,cur_text," .
781 'cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter,' .
782 'cur_restrictions,cur_user_text,cur_is_redirect,' .
783 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$cur_id_value}{$ns},'" . wfStrencode( $ttl ) . "', '" .
784 wfStrencode( $text ) . "', '" .
785 wfStrencode( $summary ) . "', '" .
786 $wgUser->getID() . "', '{$now}', " .
787 $isminor . ", 0, '', '" .
788 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
789 $res = wfQuery( $sql, DB_WRITE, $fname );
790
791 $newid = $wgIsPg?$cur_id:wfInsertId();
792 $this->mTitle->resetArticleID( $newid );
793
794 Article::onArticleCreate( $this->mTitle );
795 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
796
797 if ($watchthis) {
798 if(!$this->mTitle->userIsWatching()) $this->watch();
799 } else {
800 if ( $this->mTitle->userIsWatching() ) {
801 $this->unwatch();
802 }
803 }
804
805 # The talk page isn't in the regular link tables, so we need to update manually:
806 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
807 $sql = "UPDATE cur set cur_touched='$now' WHERE cur_namespace=$talkns AND cur_title='" . wfStrencode( $ttl ) . "'";
808 wfQuery( $sql, DB_WRITE );
809
810 # standard deferred updates
811 $this->editUpdates( $text );
812
813 $this->showArticle( $text, wfMsg( 'newarticle' ) );
814 }
815
816
817 /* Side effects: loads last edit */
818 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ''){
819 $this->loadLastEdit();
820 $oldtext = $this->getContent( true );
821 if ($section != '') {
822 if($section=='new') {
823 if($summary) $subject="== {$summary} ==\n\n";
824 $text=$oldtext."\n\n".$subject.$text;
825 } else {
826
827 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
828 # comments to be stripped as well)
829 $striparray=array();
830 $parser=new Parser();
831 $parser->mOutputType=OT_WIKI;
832 $oldtext=$parser->strip($oldtext, $striparray, true);
833
834 # now that we can be sure that no pseudo-sections are in the source,
835 # split it up
836 # Unfortunately we can't simply do a preg_replace because that might
837 # replace the wrong section, so we have to use the section counter instead
838 $secs=preg_split('/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
839 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
840 $secs[$section*2]=$text."\n\n"; // replace with edited
841
842 # section 0 is top (intro) section
843 if($section!=0) {
844
845 # headline of old section - we need to go through this section
846 # to determine if there are any subsections that now need to
847 # be erased, as the mother section has been replaced with
848 # the text of all subsections.
849 $headline=$secs[$section*2-1];
850 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
851 $hlevel=$matches[1];
852
853 # determine headline level for wikimarkup headings
854 if(strpos($hlevel,'=')!==false) {
855 $hlevel=strlen($hlevel);
856 }
857
858 $secs[$section*2-1]=''; // erase old headline
859 $count=$section+1;
860 $break=false;
861 while(!empty($secs[$count*2-1]) && !$break) {
862
863 $subheadline=$secs[$count*2-1];
864 preg_match(
865 '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
866 $subhlevel=$matches[1];
867 if(strpos($subhlevel,'=')!==false) {
868 $subhlevel=strlen($subhlevel);
869 }
870 if($subhlevel > $hlevel) {
871 // erase old subsections
872 $secs[$count*2-1]='';
873 $secs[$count*2]='';
874 }
875 if($subhlevel <= $hlevel) {
876 $break=true;
877 }
878 $count++;
879
880 }
881
882 }
883 $text=join('',$secs);
884 # reinsert the stuff that we stripped out earlier
885 $text=$parser->unstrip($text,$striparray);
886 $text=$parser->unstripNoWiki($text,$striparray);
887 }
888
889 }
890 return $text;
891 }
892
893 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' )
894 {
895 global $wgOut, $wgUser, $wgLinkCache;
896 global $wgDBtransactions, $wgMwRedir;
897 global $wgUseSquid, $wgInternalServer;
898 global $wgIsPg;
899 $fname = 'Article::updateArticle';
900
901 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
902 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
903 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
904 $redir = 1;
905 $text = $m[1] . "\n"; # Remove all content but redirect
906 }
907 else { $redir = 0; }
908
909 $text = $this->preSaveTransform( $text );
910
911 # Update article, but only if changed.
912
913 if( $wgDBtransactions ) {
914 $sql = 'BEGIN';
915 wfQuery( $sql, DB_WRITE );
916 }
917 $oldtext = $this->getContent( true );
918
919 if ( 0 != strcmp( $text, $oldtext ) ) {
920 $this->mCountAdjustment = $this->isCountable( $text )
921 - $this->isCountable( $oldtext );
922
923 $now = wfTimestampNow();
924 $won = wfInvertTimestamp( $now );
925 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
926 "',cur_comment='" . wfStrencode( $summary ) .
927 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
928 ",cur_timestamp='{$now}',cur_user_text='" .
929 wfStrencode( $wgUser->getName() ) .
930 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
931 "WHERE cur_id=" . $this->getID() .
932 " AND cur_timestamp='" . $this->getTimestamp() . "'";
933 $res = wfQuery( $sql, DB_WRITE, $fname );
934
935 if( wfAffectedRows() == 0 ) {
936 /* Belated edit conflict! Run away!! */
937 return false;
938 }
939
940 # This overwrites $oldtext if revision compression is on
941 $flags = Article::compressRevisionText( $oldtext );
942
943 $oldtable=$wgIsPg?'"old"':'old';
944 if ($wgIsPg) {
945 $oldtable='"old"';
946 $old_id_column='old_id,';
947 $old_id=wfGetSQL(""," nextval('old_old_id_seq')");
948 $old_id_value=$old_id.',';
949 } else {
950 $oldtable='old';
951 $old_id_column='';
952 $old_id_value='';
953 }
954
955 $sql = "INSERT INTO $oldtable ({$old_id_column}old_namespace,old_title,old_text," .
956 'old_comment,old_user,old_user_text,old_timestamp,' .
957 'old_minor_edit,inverse_timestamp,old_flags) VALUES (' .
958 $old_id_value.
959 $this->mTitle->getNamespace() . ", '" .
960 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
961 wfStrencode( $oldtext ) . "', '" .
962 wfStrencode( $this->getComment() ) . "', " .
963 $this->getUser() . ", '" .
964 wfStrencode( $this->getUserText() ) . "', '" .
965 $this->getTimestamp() . "', " . $me1 . ", '" .
966 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
967 $res = wfQuery( $sql, DB_WRITE, $fname );
968
969 $oldid = $wgIsPg?$old_id:wfInsertId( $res );
970
971 $bot = (int)($wgUser->isBot() || $forceBot);
972 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
973 $oldid, $this->getTimestamp(), $bot );
974 Article::onArticleEdit( $this->mTitle );
975 }
976
977 if( $wgDBtransactions ) {
978 $sql = 'COMMIT';
979 wfQuery( $sql, DB_WRITE );
980 }
981
982 if ($watchthis) {
983 if (!$this->mTitle->userIsWatching()) $this->watch();
984 } else {
985 if ( $this->mTitle->userIsWatching() ) {
986 $this->unwatch();
987 }
988 }
989 # standard deferred updates
990 $this->editUpdates( $text );
991
992
993 $urls = array();
994 # Template namespace
995 # Purge all articles linking here
996 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
997 $titles = $this->mTitle->getLinksTo();
998 Title::touchArray( $titles );
999 if ( $wgUseSquid ) {
1000 foreach ( $titles as $title ) {
1001 $urls[] = $title->getInternalURL();
1002 }
1003 }
1004 }
1005
1006 # Squid updates
1007 if ( $wgUseSquid ) {
1008 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1009 $u = new SquidUpdate( $urls );
1010 $u->doUpdate();
1011 }
1012
1013 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1014 return true;
1015 }
1016
1017 # After we've either updated or inserted the article, update
1018 # the link tables and redirect to the new page.
1019
1020 function showArticle( $text, $subtitle , $sectionanchor = '' )
1021 {
1022 global $wgOut, $wgUser, $wgLinkCache;
1023 global $wgMwRedir;
1024
1025 $wgLinkCache = new LinkCache();
1026
1027 # Get old version of link table to allow incremental link updates
1028 $wgLinkCache->preFill( $this->mTitle );
1029 $wgLinkCache->clear();
1030
1031 # Now update the link cache by parsing the text
1032 $wgOut = new OutputPage();
1033 $wgOut->addWikiText( $text );
1034
1035 if( $wgMwRedir->matchStart( $text ) )
1036 $r = 'redirect=no';
1037 else
1038 $r = '';
1039 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1040 }
1041
1042 # Add this page to my watchlist
1043
1044 function watch( $add = true )
1045 {
1046 global $wgUser, $wgOut, $wgLang;
1047 global $wgDeferredUpdateList;
1048
1049 if ( 0 == $wgUser->getID() ) {
1050 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1051 return;
1052 }
1053 if ( wfReadOnly() ) {
1054 $wgOut->readOnlyPage();
1055 return;
1056 }
1057 if( $add )
1058 $wgUser->addWatch( $this->mTitle );
1059 else
1060 $wgUser->removeWatch( $this->mTitle );
1061
1062 $wgOut->setPagetitle( wfMsg( $add ? 'addedwatch' : 'removedwatch' ) );
1063 $wgOut->setRobotpolicy( 'noindex,follow' );
1064
1065 $sk = $wgUser->getSkin() ;
1066 $link = $this->mTitle->getPrefixedText();
1067
1068 if($add)
1069 $text = wfMsg( 'addedwatchtext', $link );
1070 else
1071 $text = wfMsg( 'removedwatchtext', $link );
1072 $wgOut->addWikiText( $text );
1073
1074 $up = new UserUpdate();
1075 array_push( $wgDeferredUpdateList, $up );
1076
1077 $wgOut->returnToMain( false );
1078 }
1079
1080 function unwatch()
1081 {
1082 $this->watch( false );
1083 }
1084
1085 function protect( $limit = 'sysop' )
1086 {
1087 global $wgUser, $wgOut, $wgRequest;
1088
1089 if ( ! $wgUser->isSysop() ) {
1090 $wgOut->sysopRequired();
1091 return;
1092 }
1093 if ( wfReadOnly() ) {
1094 $wgOut->readOnlyPage();
1095 return;
1096 }
1097 $id = $this->mTitle->getArticleID();
1098 if ( 0 == $id ) {
1099 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1100 return;
1101 }
1102
1103 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1104 $reason = $wgRequest->getText( 'wpReasonProtect' );
1105
1106 if ( $confirm ) {
1107
1108 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1109 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
1110 wfQuery( $sql, DB_WRITE, 'Article::protect' );
1111
1112 $log = new LogPage( wfMsg( 'protectlogpage' ), wfMsg( 'protectlogtext' ) );
1113 if ( $limit === "" ) {
1114 $log->addEntry( wfMsg( 'unprotectedarticle', $this->mTitle->getPrefixedText() ), $reason );
1115 } else {
1116 $log->addEntry( wfMsg( 'protectedarticle', $this->mTitle->getPrefixedText() ), $reason );
1117 }
1118 $wgOut->redirect( $this->mTitle->getFullURL() );
1119 return;
1120 } else {
1121 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1122 return $this->confirmProtect( '', $reason, $limit );
1123 }
1124 }
1125
1126 # Output protection confirmation dialog
1127 function confirmProtect( $par, $reason, $limit = 'sysop' )
1128 {
1129 global $wgOut;
1130
1131 wfDebug( "Article::confirmProtect\n" );
1132
1133 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1134 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1135
1136 $check = '';
1137 $protcom = '';
1138
1139 if ( $limit === '' ) {
1140 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1141 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1142 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1143 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1144 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1145 } else {
1146 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1147 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1148 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1149 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1150 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1151 }
1152
1153 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1154
1155 $wgOut->addHTML( "
1156 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1157 <table border='0'>
1158 <tr>
1159 <td align='right'>
1160 <label for='wpReasonProtect'>{$protcom}:</label>
1161 </td>
1162 <td align='left'>
1163 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1164 </td>
1165 </tr>
1166 <tr>
1167 <td>&nbsp;</td>
1168 </tr>
1169 <tr>
1170 <td align='right'>
1171 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1172 </td>
1173 <td>
1174 <label for='wpConfirmProtect'>{$check}</label>
1175 </td>
1176 </tr>
1177 <tr>
1178 <td>&nbsp;</td>
1179 <td>
1180 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1181 </td>
1182 </tr>
1183 </table>
1184 </form>\n" );
1185
1186 $wgOut->returnToMain( false );
1187 }
1188
1189 function unprotect()
1190 {
1191 return $this->protect( '' );
1192 }
1193
1194 # UI entry point for page deletion
1195 function delete()
1196 {
1197 global $wgUser, $wgOut, $wgMessageCache, $wgRequest, $wgIsPg;
1198 $fname = 'Article::delete';
1199 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1200 $reason = $wgRequest->getText( 'wpReason' );
1201
1202 # This code desperately needs to be totally rewritten
1203
1204 # Check permissions
1205 if ( ( ! $wgUser->isSysop() ) ) {
1206 $wgOut->sysopRequired();
1207 return;
1208 }
1209 if ( wfReadOnly() ) {
1210 $wgOut->readOnlyPage();
1211 return;
1212 }
1213
1214 # Better double-check that it hasn't been deleted yet!
1215 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1216 if ( ( '' == trim( $this->mTitle->getText() ) )
1217 or ( $this->mTitle->getArticleId() == 0 ) ) {
1218 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1219 return;
1220 }
1221
1222 if ( $confirm ) {
1223 $this->doDelete( $reason );
1224 return;
1225 }
1226
1227 # determine whether this page has earlier revisions
1228 # and insert a warning if it does
1229 # we select the text because it might be useful below
1230 $ns = $this->mTitle->getNamespace();
1231 $title = $this->mTitle->getDBkey();
1232 $etitle = wfStrencode( $title );
1233 $oldtable=$wgIsPg?'"old"':'old';
1234 $sql = "SELECT old_text,old_flags FROM $oldtable WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
1235 $res = wfQuery( $sql, DB_READ, $fname );
1236 if( ($old=wfFetchObject($res)) && !$confirm ) {
1237 $skin=$wgUser->getSkin();
1238 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1239 $wgOut->addHTML( $skin->historyLink() .'</b>');
1240 }
1241
1242 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
1243 $res=wfQuery($sql, DB_READ, $fname);
1244 if( ($s=wfFetchObject($res))) {
1245
1246 # if this is a mini-text, we can paste part of it into the deletion reason
1247
1248 #if this is empty, an earlier revision may contain "useful" text
1249 $blanked = false;
1250 if($s->cur_text!="") {
1251 $text=$s->cur_text;
1252 } else {
1253 if($old) {
1254 $text = Article::getRevisionText( $old );
1255 $blanked = true;
1256 }
1257
1258 }
1259
1260 $length=strlen($text);
1261
1262 # this should not happen, since it is not possible to store an empty, new
1263 # page. Let's insert a standard text in case it does, though
1264 if($length == 0 && $reason === '') {
1265 $reason = wfMsg('exblank');
1266 }
1267
1268 if($length < 500 && $reason === '') {
1269
1270 # comment field=255, let's grep the first 150 to have some user
1271 # space left
1272 $text=substr($text,0,150);
1273 # let's strip out newlines and HTML tags
1274 $text=preg_replace('/\"/',"'",$text);
1275 $text=preg_replace('/\</','&lt;',$text);
1276 $text=preg_replace('/\>/','&gt;',$text);
1277 $text=preg_replace("/[\n\r]/",'',$text);
1278 if(!$blanked) {
1279 $reason=wfMsg('excontent'). " '".$text;
1280 } else {
1281 $reason=wfMsg('exbeforeblank') . " '".$text;
1282 }
1283 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1284 $reason.="'";
1285 }
1286 }
1287
1288 return $this->confirmDelete( '', $reason );
1289 }
1290
1291 # Output deletion confirmation dialog
1292 function confirmDelete( $par, $reason )
1293 {
1294 global $wgOut;
1295
1296 wfDebug( "Article::confirmDelete\n" );
1297
1298 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1299 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1300 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1301 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1302
1303 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1304
1305 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1306 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1307 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1308
1309 $wgOut->addHTML( "
1310 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1311 <table border='0'>
1312 <tr>
1313 <td align='right'>
1314 <label for='wpReason'>{$delcom}:</label>
1315 </td>
1316 <td align='left'>
1317 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1318 </td>
1319 </tr>
1320 <tr>
1321 <td>&nbsp;</td>
1322 </tr>
1323 <tr>
1324 <td align='right'>
1325 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1326 </td>
1327 <td>
1328 <label for='wpConfirm'>{$check}</label>
1329 </td>
1330 </tr>
1331 <tr>
1332 <td>&nbsp;</td>
1333 <td>
1334 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1335 </td>
1336 </tr>
1337 </table>
1338 </form>\n" );
1339
1340 $wgOut->returnToMain( false );
1341 }
1342
1343 # Perform a deletion and output success or failure messages
1344 function doDelete( $reason )
1345 {
1346 global $wgOut, $wgUser, $wgLang;
1347 $fname = 'Article::doDelete';
1348 wfDebug( "$fname\n" );
1349
1350 if ( $this->doDeleteArticle( $reason ) ) {
1351 $deleted = $this->mTitle->getPrefixedText();
1352
1353 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1354 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1355
1356 $sk = $wgUser->getSkin();
1357 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1358 Namespace::getWikipedia() ) .
1359 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1360
1361 $text = wfMsg( "deletedtext", $deleted, $loglink );
1362
1363 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1364 $wgOut->returnToMain( false );
1365 } else {
1366 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1367 }
1368 }
1369
1370 # Back-end article deletion
1371 # Deletes the article with database consistency, writes logs, purges caches
1372 # Returns success
1373 function doDeleteArticle( $reason )
1374 {
1375 global $wgUser, $wgLang;
1376 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1377
1378 $fname = 'Article::doDeleteArticle';
1379 wfDebug( $fname."\n" );
1380
1381 $ns = $this->mTitle->getNamespace();
1382 $t = wfStrencode( $this->mTitle->getDBkey() );
1383 $id = $this->mTitle->getArticleID();
1384
1385 if ( '' == $t || $id == 0 ) {
1386 return false;
1387 }
1388
1389 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1390 array_push( $wgDeferredUpdateList, $u );
1391
1392 $linksTo = $this->mTitle->getLinksTo();
1393
1394 # Squid purging
1395 if ( $wgUseSquid ) {
1396 $urls = array(
1397 $this->mTitle->getInternalURL(),
1398 $this->mTitle->getInternalURL( 'history' )
1399 );
1400 foreach ( $linksTo as $linkTo ) {
1401 $urls[] = $linkTo->getInternalURL();
1402 }
1403
1404 $u = new SquidUpdate( $urls );
1405 array_push( $wgDeferredUpdateList, $u );
1406
1407 }
1408
1409 # Client and file cache invalidation
1410 Title::touchArray( $linksTo );
1411
1412 # Move article and history to the "archive" table
1413 $sql = 'INSERT INTO archive (ar_namespace,ar_title,ar_text,' .
1414 'ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit,' .
1415 'ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment,' .
1416 'cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur ' .
1417 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1418 wfQuery( $sql, DB_WRITE, $fname );
1419
1420 $sql = 'INSERT INTO archive (ar_namespace,ar_title,ar_text,' .
1421 'ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit,' .
1422 'ar_flags) SELECT old_namespace,old_title,old_text,old_comment,' .
1423 'old_user,old_user_text,old_timestamp,old_minor_edit,old_flags ' .
1424 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1425 wfQuery( $sql, DB_WRITE, $fname );
1426
1427 # Now that it's safely backed up, delete it
1428
1429 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1430 "cur_title='{$t}'";
1431 wfQuery( $sql, DB_WRITE, $fname );
1432
1433 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1434 "old_title='{$t}'";
1435 wfQuery( $sql, DB_WRITE, $fname );
1436
1437 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1438 "rc_title='{$t}'";
1439 wfQuery( $sql, DB_WRITE, $fname );
1440
1441 # Finally, clean up the link tables
1442 $t = wfStrencode( $this->mTitle->getPrefixedDBkey() );
1443
1444 Article::onArticleDelete( $this->mTitle );
1445
1446 $sql = 'INSERT INTO brokenlinks (bl_from,bl_to) VALUES ';
1447 $first = true;
1448
1449 foreach ( $linksTo as $titleObj ) {
1450 if ( ! $first ) { $sql .= ','; }
1451 $first = false;
1452 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1453 $linkID = $titleObj->getArticleID();
1454 $sql .= "({$linkID},'{$t}')";
1455 }
1456 if ( ! $first ) {
1457 wfQuery( $sql, DB_WRITE, $fname );
1458 }
1459
1460 $sql = "DELETE FROM links WHERE l_to={$id}";
1461 wfQuery( $sql, DB_WRITE, $fname );
1462
1463 $sql = "DELETE FROM links WHERE l_from={$id}";
1464 wfQuery( $sql, DB_WRITE, $fname );
1465
1466 $sql = "DELETE FROM imagelinks WHERE il_from={$id}";
1467 wfQuery( $sql, DB_WRITE, $fname );
1468
1469 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1470 wfQuery( $sql, DB_WRITE, $fname );
1471
1472 $sql = "DELETE FROM categorylinks WHERE cl_from={$id}";
1473 wfQuery( $sql, DB_WRITE, $fname );
1474
1475 $log = new LogPage( wfMsg( 'dellogpage' ), wfMsg( 'dellogpagetext' ) );
1476 $art = $this->mTitle->getPrefixedText();
1477 $log->addEntry( wfMsg( 'deletedarticle', $art ), $reason );
1478
1479 # Clear the cached article id so the interface doesn't act like we exist
1480 $this->mTitle->resetArticleID( 0 );
1481 $this->mTitle->mArticleID = 0;
1482 return true;
1483 }
1484
1485 function rollback()
1486 {
1487 global $wgUser, $wgLang, $wgOut, $wgRequest, $wgIsMySQL, $wgIsPg;
1488
1489 if ( ! $wgUser->isSysop() ) {
1490 $wgOut->sysopRequired();
1491 return;
1492 }
1493 if ( wfReadOnly() ) {
1494 $wgOut->readOnlyPage( $this->getContent( true ) );
1495 return;
1496 }
1497
1498 # Enhanced rollback, marks edits rc_bot=1
1499 $bot = $wgRequest->getBool( 'bot' );
1500
1501 # Replace all this user's current edits with the next one down
1502 $tt = wfStrencode( $this->mTitle->getDBKey() );
1503 $n = $this->mTitle->getNamespace();
1504
1505 # Get the last editor
1506 $sql = 'SELECT cur_id,cur_user,cur_user_text,cur_comment ' .
1507 "FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1508 $res = wfQuery( $sql, DB_READ );
1509 if( ($x = wfNumRows( $res )) != 1 ) {
1510 # Something wrong
1511 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1512 return;
1513 }
1514 $s = wfFetchObject( $res );
1515 $ut = wfStrencode( $s->cur_user_text );
1516 $uid = $s->cur_user;
1517 $pid = $s->cur_id;
1518
1519 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1520 if( $from != $s->cur_user_text ) {
1521 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1522 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1523 htmlspecialchars( $this->mTitle->getPrefixedText()),
1524 htmlspecialchars( $from ),
1525 htmlspecialchars( $s->cur_user_text ) ) );
1526 if($s->cur_comment != '') {
1527 $wgOut->addHTML(
1528 wfMsg('editcomment',
1529 htmlspecialchars( $s->cur_comment ) ) );
1530 }
1531 return;
1532 }
1533
1534 # Get the last edit not by this guy
1535
1536 $use_index=$wgIsMySQL?"USE INDEX (name_title_timestamp)":"";
1537 $oldtable=$wgIsPg?'"old"':'old';
1538 $sql = 'SELECT old_text,old_user,old_user_text,old_timestamp,old_flags ' .
1539 "FROM $oldtable {$use_index} " .
1540 "WHERE old_namespace={$n} AND old_title='{$tt}' " .
1541 "AND (old_user <> {$uid} OR old_user_text <> '{$ut}') " .
1542 'ORDER BY inverse_timestamp LIMIT 1';
1543 $res = wfQuery( $sql, DB_READ );
1544 if( wfNumRows( $res ) != 1 ) {
1545 # Something wrong
1546 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1547 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1548 return;
1549 }
1550 $s = wfFetchObject( $res );
1551
1552 if ( $bot ) {
1553 # Mark all reverted edits as bot
1554 $sql = 'UPDATE recentchanges SET rc_bot=1 WHERE ' .
1555 "rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
1556 wfQuery( $sql, DB_WRITE, $fname );
1557 }
1558
1559 # Save it!
1560 $newcomment = wfMsg( 'revertpage', $s->old_user_text, $from );
1561 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1562 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1563 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1564 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1565 Article::onArticleEdit( $this->mTitle );
1566 $wgOut->returnToMain( false );
1567 }
1568
1569
1570 # Do standard deferred updates after page view
1571
1572 /* private */ function viewUpdates()
1573 {
1574 global $wgDeferredUpdateList;
1575 if ( 0 != $this->getID() ) {
1576 global $wgDisableCounters;
1577 if( !$wgDisableCounters ) {
1578 Article::incViewCount( $this->getID() );
1579 $u = new SiteStatsUpdate( 1, 0, 0 );
1580 array_push( $wgDeferredUpdateList, $u );
1581 }
1582 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1583 $this->mTitle->getDBkey() );
1584 array_push( $wgDeferredUpdateList, $u );
1585 }
1586 }
1587
1588 # Do standard deferred updates after page edit.
1589 # Every 1000th edit, prune the recent changes table.
1590
1591 /* private */ function editUpdates( $text )
1592 {
1593 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1594 global $wgMessageCache;
1595
1596 wfSeedRandom();
1597 if ( 0 == mt_rand( 0, 999 ) ) {
1598 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1599 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1600 wfQuery( $sql, DB_WRITE );
1601 }
1602 $id = $this->getID();
1603 $title = $this->mTitle->getPrefixedDBkey();
1604 $shortTitle = $this->mTitle->getDBkey();
1605
1606 $adj = $this->mCountAdjustment;
1607
1608 if ( 0 != $id ) {
1609 $u = new LinksUpdate( $id, $title );
1610 array_push( $wgDeferredUpdateList, $u );
1611 $u = new SiteStatsUpdate( 0, 1, $adj );
1612 array_push( $wgDeferredUpdateList, $u );
1613 $u = new SearchUpdate( $id, $title, $text );
1614 array_push( $wgDeferredUpdateList, $u );
1615
1616 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1617 array_push( $wgDeferredUpdateList, $u );
1618
1619 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1620 $wgMessageCache->replace( $shortTitle, $text );
1621 }
1622 }
1623 }
1624
1625 /* private */ function setOldSubtitle()
1626 {
1627 global $wgLang, $wgOut;
1628
1629 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1630 $r = wfMsg( 'revisionasof', $td );
1631 $wgOut->setSubtitle( "({$r})" );
1632 }
1633
1634 # This function is called right before saving the wikitext,
1635 # so we can do things like signatures and links-in-context.
1636
1637 function preSaveTransform( $text )
1638 {
1639 global $wgParser, $wgUser;
1640 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1641 }
1642
1643 /* Caching functions */
1644
1645 # checkLastModified returns true if it has taken care of all
1646 # output to the client that is necessary for this request.
1647 # (that is, it has sent a cached version of the page)
1648 function tryFileCache() {
1649 static $called = false;
1650 if( $called ) {
1651 wfDebug( " tryFileCache() -- called twice!?\n" );
1652 return;
1653 }
1654 $called = true;
1655 if($this->isFileCacheable()) {
1656 $touched = $this->mTouched;
1657 if( $this->mTitle->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1658 # Expire the main page quicker
1659 $expire = wfUnix2Timestamp( time() - 3600 );
1660 $touched = max( $expire, $touched );
1661 }
1662 $cache = new CacheManager( $this->mTitle );
1663 if($cache->isFileCacheGood( $touched )) {
1664 global $wgOut;
1665 wfDebug( " tryFileCache() - about to load\n" );
1666 $cache->loadFromFileCache();
1667 return true;
1668 } else {
1669 wfDebug( " tryFileCache() - starting buffer\n" );
1670 ob_start( array(&$cache, 'saveToFileCache' ) );
1671 }
1672 } else {
1673 wfDebug( " tryFileCache() - not cacheable\n" );
1674 }
1675 }
1676
1677 function isFileCacheable() {
1678 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1679 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1680
1681 return $wgUseFileCache
1682 and (!$wgShowIPinHeader)
1683 and ($this->getID() != 0)
1684 and ($wgUser->getId() == 0)
1685 and (!$wgUser->getNewtalk())
1686 and ($this->mTitle->getNamespace() != Namespace::getSpecial())
1687 and ($action == 'view')
1688 and (!isset($oldid))
1689 and (!isset($diff))
1690 and (!isset($redirect))
1691 and (!isset($printable))
1692 and (!$this->mRedirectedFrom);
1693 }
1694
1695 # Loads cur_touched and returns a value indicating if it should be used
1696 function checkTouched() {
1697 $id = $this->getID();
1698 $sql = 'SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id='.$id;
1699 $res = wfQuery( $sql, DB_READ, 'Article::checkTouched' );
1700 if( $s = wfFetchObject( $res ) ) {
1701 $this->mTouched = $s->cur_touched;
1702 return !$s->cur_is_redirect;
1703 } else {
1704 return false;
1705 }
1706 }
1707
1708 # Edit an article without doing all that other stuff
1709 function quickEdit( $text, $comment = '', $minor = 0 ) {
1710 global $wgUser, $wgMwRedir, $wgIsPg;
1711 $fname = 'Article::quickEdit';
1712 wfProfileIn( $fname );
1713
1714 $ns = $this->mTitle->getNamespace();
1715 $dbkey = $this->mTitle->getDBkey();
1716 $encDbKey = wfStrencode( $dbkey );
1717 $timestamp = wfTimestampNow();
1718
1719 # Save to history
1720 $oldtable=$wgIsPg?'"old"':'old';
1721 $sql = "INSERT INTO $oldtable (old_namespace,old_title,old_text,old_comment,old_user,old_user_text,old_timestamp,inverse_timestamp)
1722 SELECT cur_namespace,cur_title,cur_text,cur_comment,cur_user,cur_user_text,cur_timestamp,99999999999999-cur_timestamp
1723 FROM cur WHERE cur_namespace=$ns AND cur_title='$encDbKey'";
1724 wfQuery( $sql, DB_WRITE );
1725
1726 # Use the affected row count to determine if the article is new
1727 $numRows = wfAffectedRows();
1728
1729 # Make an array of fields to be inserted
1730 $fields = array(
1731 'cur_text' => $text,
1732 'cur_timestamp' => $timestamp,
1733 'cur_user' => $wgUser->getID(),
1734 'cur_user_text' => $wgUser->getName(),
1735 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1736 'cur_comment' => $comment,
1737 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ? 1 : 0,
1738 'cur_minor_edit' => intval($minor),
1739 'cur_touched' => $timestamp,
1740 );
1741
1742 if ( $numRows ) {
1743 # Update article
1744 $fields['cur_is_new'] = 0;
1745 wfUpdateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1746 } else {
1747 # Insert new article
1748 $fields['cur_is_new'] = 1;
1749 $fields['cur_namespace'] = $ns;
1750 $fields['cur_title'] = $dbkey;
1751 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1752 wfInsertArray( 'cur', $fields, $fname );
1753 }
1754 wfProfileOut( $fname );
1755 }
1756
1757 /* static */ function incViewCount( $id )
1758 {
1759 $id = intval( $id );
1760 global $wgHitcounterUpdateFreq;
1761
1762 if( $wgHitcounterUpdateFreq <= 1 ){ //
1763 wfQuery('UPDATE cur SET cur_counter = cur_counter + 1 ' .
1764 'WHERE cur_id = '.$id, DB_WRITE);
1765 return;
1766 }
1767
1768 # Not important enough to warrant an error page in case of failure
1769 $oldignore = wfIgnoreSQLErrors( true );
1770
1771 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE);
1772
1773 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1774 if( (rand() % $checkfreq != 0) or (wfLastErrno() != 0) ){
1775 # Most of the time (or on SQL errors), skip row count check
1776 wfIgnoreSQLErrors( $oldignore );
1777 return;
1778 }
1779
1780 $res = wfQuery('SELECT COUNT(*) as n FROM hitcounter', DB_WRITE);
1781 $row = wfFetchObject( $res );
1782 $rown = intval( $row->n );
1783 if( $rown >= $wgHitcounterUpdateFreq ){
1784 wfProfileIn( 'Article::incViewCount-collect' );
1785 $old_user_abort = ignore_user_abort( true );
1786
1787 wfQuery('LOCK TABLES hitcounter WRITE', DB_WRITE);
1788 wfQuery('CREATE TEMPORARY TABLE acchits TYPE=HEAP '.
1789 'SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter '.
1790 'GROUP BY hc_id', DB_WRITE);
1791 wfQuery('DELETE FROM hitcounter', DB_WRITE);
1792 wfQuery('UNLOCK TABLES', DB_WRITE);
1793 wfQuery('UPDATE cur,acchits SET cur_counter=cur_counter + hc_n '.
1794 'WHERE cur_id = hc_id', DB_WRITE);
1795 wfQuery('DROP TABLE acchits', DB_WRITE);
1796
1797 ignore_user_abort( $old_user_abort );
1798 wfProfileOut( 'Article::incViewCount-collect' );
1799 }
1800 wfIgnoreSQLErrors( $oldignore );
1801 }
1802
1803 # The onArticle*() functions are supposed to be a kind of hooks
1804 # which should be called whenever any of the specified actions
1805 # are done.
1806 #
1807 # This is a good place to put code to clear caches, for instance.
1808
1809 # This is called on page move and undelete, as well as edit
1810 /* static */ function onArticleCreate($title_obj){
1811 global $wgUseSquid, $wgDeferredUpdateList;
1812
1813 $titles = $title_obj->getBrokenLinksTo();
1814
1815 # Purge squid
1816 if ( $wgUseSquid ) {
1817 $urls = $title_obj->getSquidURLs();
1818 foreach ( $titles as $linkTitle ) {
1819 $urls[] = $linkTitle->getInternalURL();
1820 }
1821 $u = new SquidUpdate( $urls );
1822 array_push( $wgDeferredUpdateList, $u );
1823 }
1824
1825 # Clear persistent link cache
1826 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1827 }
1828
1829 /* static */ function onArticleDelete($title_obj){
1830 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
1831 }
1832
1833 /* static */ function onArticleEdit($title_obj){
1834 LinkCache::linksccClearPage( $title_obj->getArticleID() );
1835 }
1836 }
1837
1838 ?>