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