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