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