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