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