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