New file form Christian List.
[mediawiki.git] / includes / Article.php
blob078dc8bff2bcba8e9d451fca4f59680f1efb1e7b
1 <?
2 # Class representing a Wikipedia article and history.
3 # See design.doc for an overview.
5 class Article {
6 /* private */ var $mContent, $mContentLoaded;
7 /* private */ var $mUser, $mTimestamp, $mUserText;
8 /* private */ var $mCounter, $mComment, $mCountAdjustment;
9 /* private */ var $mMinorEdit, $mRedirectedFrom;
10 /* private */ var $mTouched, $mFileCache;
12 function Article() { $this->clear(); }
14 /* private */ function clear()
16 $this->mContentLoaded = false;
17 $this->mUser = $this->mCounter = -1; # Not loaded
18 $this->mRedirectedFrom = $this->mUserText =
19 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
20 $this->mCountAdjustment = 0;
21 $this->mTouched = "19700101000000";
24 /* static */ function newFromID( $newid )
26 global $wgOut, $wgTitle, $wgArticle;
27 $a = new Article();
28 $n = Article::nameOf( $newid );
30 $wgTitle = Title::newFromDBkey( $n );
31 $wgTitle->resetArticleID( $newid );
33 return $a;
36 /* static */ function nameOf( $id )
38 $sql = "SELECT cur_namespace,cur_title FROM cur WHERE " .
39 "cur_id={$id}";
40 $res = wfQuery( $sql, "Article::nameOf" );
41 if ( 0 == wfNumRows( $res ) ) { return NULL; }
43 $s = wfFetchObject( $res );
44 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
45 return $n;
48 # Note that getContent/loadContent may follow redirects if
49 # not told otherwise, and so may cause a change to wgTitle.
51 function getContent( $noredir = false )
53 global $action,$wgTitle; # From query string
54 wfProfileIn( "Article::getContent" );
56 if ( 0 == $this->getID() ) {
57 if ( "edit" == $action ) {
59 global $wgTitle;
60 return ""; # was "newarticletext", now moved above the box)
64 wfProfileOut();
65 return wfMsg( "noarticletext" );
66 } else {
67 $this->loadContent( $noredir );
68 wfProfileOut();
70 if(
71 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
72 ( $wgTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
73 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$wgTitle->getText()) &&
74 $action=="view"
77 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
78 else {
79 return $this->mContent;
84 function loadContent( $noredir = false )
86 global $wgOut, $wgTitle;
87 global $oldid, $redirect; # From query
89 if ( $this->mContentLoaded ) return;
90 $fname = "Article::loadContent";
92 # Pre-fill content with error message so that if something
93 # fails we'll have something telling us what we intended.
95 $t = $wgTitle->getPrefixedText();
96 if ( $oldid ) { $t .= ",oldid={$oldid}"; }
97 if ( $redirect ) { $t .= ",redirect={$redirect}"; }
98 $this->mContent = str_replace( "$1", $t, wfMsg( "missingarticle" ) );
100 if ( ! $oldid ) { # Retrieve current version
101 $id = $this->getID();
102 if ( 0 == $id ) return;
104 $sql = "SELECT " .
105 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
106 "FROM cur WHERE cur_id={$id}";
107 $res = wfQuery( $sql, $fname );
108 if ( 0 == wfNumRows( $res ) ) { return; }
110 $s = wfFetchObject( $res );
112 # If we got a redirect, follow it (unless we've been told
113 # not to by either the function parameter or the query
115 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
116 ( preg_match( "/^#redirect/i", $s->cur_text ) ) ) {
117 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
118 $s->cur_text, $m ) ) {
119 $rt = Title::newFromText( $m[1] );
121 # Gotta hand redirects to special pages differently:
122 # Fill the HTTP response "Location" header and ignore
123 # the rest of the page we're on.
125 if ( $rt->getInterwiki() != "" ) {
126 $wgOut->redirect( $rt->getFullURL() ) ;
127 return;
129 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
130 $wgOut->redirect( wfLocalUrl(
131 $rt->getPrefixedURL() ) );
132 return;
134 $rid = $rt->getArticleID();
135 if ( 0 != $rid ) {
136 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
137 "cur_counter,cur_touched FROM cur WHERE cur_id={$rid}";
138 $res = wfQuery( $sql, $fname );
140 if ( 0 != wfNumRows( $res ) ) {
141 $this->mRedirectedFrom = $wgTitle->getPrefixedText();
142 $wgTitle = $rt;
143 $s = wfFetchObject( $res );
148 $this->mContent = $s->cur_text;
149 $this->mUser = $s->cur_user;
150 $this->mCounter = $s->cur_counter;
151 $this->mTimestamp = $s->cur_timestamp;
152 $this->mTouched = $s->cur_touched;
153 $wgTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
154 $wgTitle->mRestrictionsLoaded = true;
155 wfFreeResult( $res );
156 } else { # oldid set, retrieve historical version
157 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
158 "WHERE old_id={$oldid}";
159 $res = wfQuery( $sql, $fname );
160 if ( 0 == wfNumRows( $res ) ) { return; }
162 $s = wfFetchObject( $res );
163 $this->mContent = $s->old_text;
164 $this->mUser = $s->old_user;
165 $this->mCounter = 0;
166 $this->mTimestamp = $s->old_timestamp;
167 wfFreeResult( $res );
169 $this->mContentLoaded = true;
172 function getID() { global $wgTitle; return $wgTitle->getArticleID(); }
174 function getCount()
176 if ( -1 == $this->mCounter ) {
177 $id = $this->getID();
178 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
180 return $this->mCounter;
183 # Would the given text make this article a "good" article (i.e.,
184 # suitable for including in the article count)?
186 function isCountable( $text )
188 global $wgTitle, $wgUseCommaCount;
190 if ( 0 != $wgTitle->getNamespace() ) { return 0; }
191 if ( preg_match( "/^#redirect/i", $text ) ) { return 0; }
192 $token = ($wgUseCommaCount ? "," : "[[" );
193 if ( false === strstr( $text, $token ) ) { return 0; }
194 return 1;
197 # Load the field related to the last edit time of the article.
198 # This isn't necessary for all uses, so it's only done if needed.
200 /* private */ function loadLastEdit()
202 global $wgOut;
203 if ( -1 != $this->mUser ) return;
205 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
206 "cur_comment,cur_minor_edit FROM cur WHERE " .
207 "cur_id=" . $this->getID();
208 $res = wfQuery( $sql, "Article::loadLastEdit" );
210 if ( wfNumRows( $res ) > 0 ) {
211 $s = wfFetchObject( $res );
212 $this->mUser = $s->cur_user;
213 $this->mUserText = $s->cur_user_text;
214 $this->mTimestamp = $s->cur_timestamp;
215 $this->mComment = $s->cur_comment;
216 $this->mMinorEdit = $s->cur_minor_edit;
220 function getTimestamp()
222 $this->loadLastEdit();
223 return $this->mTimestamp;
226 function getUser()
228 $this->loadLastEdit();
229 return $this->mUser;
232 function getUserText()
234 $this->loadLastEdit();
235 return $this->mUserText;
238 function getComment()
240 $this->loadLastEdit();
241 return $this->mComment;
244 function getMinorEdit()
246 $this->loadLastEdit();
247 return $this->mMinorEdit;
250 # This is the default action of the script: just view the page of
251 # the given title.
253 function view()
255 global $wgUser, $wgOut, $wgTitle, $wgLang;
256 global $oldid, $diff; # From query
257 global $wgLinkCache;
258 wfProfileIn( "Article::view" );
260 $wgOut->setArticleFlag( true );
261 $wgOut->setRobotpolicy( "index,follow" );
263 # If we got diff and oldid in the query, we want to see a
264 # diff page instead of the article.
266 if ( isset( $diff ) ) {
267 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
268 $de = new DifferenceEngine( $oldid, $diff );
269 $de->showDiffPage();
270 wfProfileOut();
271 return;
273 $text = $this->getContent(); # May change wgTitle!
274 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
275 $wgOut->setHTMLTitle( $wgTitle->getPrefixedText() .
276 " - " . wfMsg( "wikititlesuffix" ) );
278 # We're looking at an old revision
280 if ( $oldid ) {
281 $this->setOldSubtitle();
282 $wgOut->setRobotpolicy( "noindex,follow" );
284 if ( "" != $this->mRedirectedFrom ) {
285 $sk = $wgUser->getSkin();
286 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
287 "redirect=no" );
288 $s = str_replace( "$1", $redir, wfMsg( "redirectedfrom" ) );
289 $wgOut->setSubtitle( $s );
291 $wgOut->checkLastModified( $this->mTouched );
292 $this->tryFileCache();
293 $wgLinkCache->preFill( $wgTitle );
294 $wgOut->addWikiText( $text );
296 # If the article we've just shown is in the "Image" namespace,
297 # follow it with the history list and link list for the image
298 # it describes.
300 if ( Namespace::getImage() == $wgTitle->getNamespace() ) {
301 $this->imageHistory();
302 $this->imageLinks();
304 $this->viewUpdates();
305 wfProfileOut();
308 # This is the function that gets called for "action=edit".
310 function edit()
312 global $wgOut, $wgUser, $wgTitle;
313 global $wpTextbox1, $wpSummary, $wpSave, $wpPreview;
314 global $wpMinoredit, $wpEdittime, $wpTextbox2;
316 $fields = array( "wpTextbox1", "wpSummary", "wpTextbox2" );
317 wfCleanFormFields( $fields );
319 if ( ! $wgTitle->userCanEdit() ) {
320 $this->view();
321 return;
323 if ( $wgUser->isBlocked() ) {
324 $this->blockedIPpage();
325 return;
327 if ( wfReadOnly() ) {
328 if( isset( $wpSave ) or isset( $wpPreview ) ) {
329 $this->editForm( "preview" );
330 } else {
331 $wgOut->readOnlyPage();
333 return;
335 if ( $_SERVER['REQUEST_METHOD'] != "POST" ) unset( $wpSave );
336 if ( isset( $wpSave ) ) {
337 $this->editForm( "save" );
338 } else if ( isset( $wpPreview ) ) {
339 $this->editForm( "preview" );
340 } else { # First time through
341 $this->editForm( "initial" );
345 # Since there is only one text field on the edit form,
346 # pressing <enter> will cause the form to be submitted, but
347 # the submit button value won't appear in the query, so we
348 # Fake it here before going back to edit(). This is kind of
349 # ugly, but it helps some old URLs to still work.
351 function submit()
353 global $wpSave, $wpPreview;
354 if ( ! isset( $wpPreview ) ) { $wpSave = 1; }
356 $this->edit();
359 # The edit form is self-submitting, so that when things like
360 # preview and edit conflicts occur, we get the same form back
361 # with the extra stuff added. Only when the final submission
362 # is made and all is well do we actually save and redirect to
363 # the newly-edited page.
365 function editForm( $formtype )
367 global $wgOut, $wgUser, $wgTitle;
368 global $wpTextbox1, $wpSummary, $wpWatchthis;
369 global $wpSave, $wpPreview;
370 global $wpMinoredit, $wpEdittime, $wpTextbox2;
371 global $oldid, $redirect;
372 global $wgLang;
374 $sk = $wgUser->getSkin();
375 $isConflict = false;
376 $wpTextbox1 = rtrim ( $wpTextbox1 ) ; # To avoid text getting longer on each preview
378 if(!$wgTitle->getArticleID()) { # new article
380 $wgOut->addWikiText(wfmsg("newarticletext"));
384 # Attempt submission here. This will check for edit conflicts,
385 # and redundantly check for locked database, blocked IPs, etc.
386 # that edit() already checked just in case someone tries to sneak
387 # in the back door with a hand-edited submission URL.
389 if ( "save" == $formtype ) {
390 if ( $wgUser->isBlocked() ) {
391 $this->blockedIPpage();
392 return;
394 if ( wfReadOnly() ) {
395 $wgOut->readOnlyPage();
396 return;
398 # If article is new, insert it.
400 $aid = $wgTitle->getArticleID();
401 if ( 0 == $aid ) {
402 # we need to strip Windoze linebreaks because some browsers
403 # append them and the string comparison fails
404 if ( ( "" == $wpTextbox1 ) ||
405 ( wfMsg( "newarticletext" ) == rtrim( preg_replace("/\r/","",$wpTextbox1) ) ) ) {
406 $wgOut->redirect( wfLocalUrl(
407 $wgTitle->getPrefixedURL() ) );
408 return;
410 $this->mCountAdjustment = $this->isCountable( $wpTextbox1 );
411 $this->insertNewArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
412 return;
414 # Article exists. Check for edit conflict.
416 $this->clear(); # Force reload of dates, etc.
417 if ( $this->getTimestamp() != $wpEdittime ) { $isConflict = true; }
418 $u = $wgUser->getID();
420 # Supress edit conflict with self
422 if ( ( 0 != $u ) && ( $this->getUser() == $u ) ) {
423 $isConflict = false;
425 if ( ! $isConflict ) {
426 # All's well: update the article here
427 $this->updateArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
428 return;
431 # First time through: get contents, set time for conflict
432 # checking, etc.
434 if ( "initial" == $formtype ) {
435 $wpEdittime = $this->getTimestamp();
436 $wpTextbox1 = $this->getContent(true);
437 $wpSummary = "";
439 $wgOut->setRobotpolicy( "noindex,nofollow" );
440 $wgOut->setArticleFlag( false );
442 if ( $isConflict ) {
443 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
444 wfMsg( "editconflict" ) );
445 $wgOut->setPageTitle( $s );
446 $wgOut->addHTML( wfMsg( "explainconflict" ) );
448 $wpTextbox2 = $wpTextbox1;
449 $wpTextbox1 = $this->getContent(true);
450 $wpEdittime = $this->getTimestamp();
451 } else {
452 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
453 wfMsg( "editing" ) );
454 $wgOut->setPageTitle( $s );
455 if ( $oldid ) {
456 $this->setOldSubtitle();
457 $wgOut->addHTML( wfMsg( "editingold" ) );
461 if( wfReadOnly() ) {
462 $wgOut->addHTML( "<strong>" .
463 wfMsg( "readonlywarning" ) .
464 "</strong>" );
466 if( $wgTitle->isProtected() ) {
467 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
468 "</strong><br />\n" );
471 $kblength = (int)(strlen( $wpTextbox1 ) / 1024);
472 if( $kblength > 29 ) {
473 $wgOut->addHTML( "<strong>" .
474 str_replace( '$1', $kblength , wfMsg( "longpagewarning" ) )
475 . "</strong>" );
478 $rows = $wgUser->getOption( "rows" );
479 $cols = $wgUser->getOption( "cols" );
481 $ew = $wgUser->getOption( "editwidth" );
482 if ( $ew ) $ew = " style=\"width:100%\"";
483 else $ew = "" ;
485 $q = "action=submit";
486 if ( "no" == $redirect ) { $q .= "&redirect=no"; }
487 $action = wfEscapeHTML( wfLocalUrl( $wgTitle->getPrefixedURL(), $q ) );
489 $summary = wfMsg( "summary" );
490 $minor = wfMsg( "minoredit" );
491 $watchthis = wfMsg ("watchthis");
492 $save = wfMsg( "savearticle" );
493 $prev = wfMsg( "showpreview" );
495 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedURL(),
496 wfMsg( "cancel" ) );
497 $edithelp = $sk->makeKnownLink( wfMsg( "edithelppage" ),
498 wfMsg( "edithelp" ) );
499 $copywarn = str_replace( "$1", $sk->makeKnownLink(
500 wfMsg( "copyrightpage" ) ), wfMsg( "copyrightwarning" ) );
502 $wpTextbox1 = wfEscapeHTML( $wpTextbox1 );
503 $wpTextbox2 = wfEscapeHTML( $wpTextbox2 );
504 $wpSummary = wfEscapeHTML( $wpSummary );
506 // activate checkboxes if user wants them to be always active
507 if (!$wpPreview && $wgUser->getOption("watchdefault")) $wpWatchthis=1;
508 if (!$wpPreview && $wgUser->getOption("minordefault")) $wpMinoredit=1;
510 // activate checkbox also if user is already watching the page,
511 // require wpWatchthis to be unset so that second condition is not
512 // checked unnecessarily
513 if (!$wpWatchthis && !$wpPreview && $wgTitle->userIsWatching()) $wpWatchthis=1;
515 if ( 0 != $wgUser->getID() ) {
516 $checkboxhtml=
517 "<input tabindex=3 type=checkbox value=1 name='wpMinoredit'".($wpMinoredit?" checked":"").">{$minor}".
518 "<input tabindex=4 type=checkbox name='wpWatchthis'".($wpWatchthis?" checked":"").">{$watchthis}<br>";
520 } else {
521 $checkboxhtml="";
525 if ( "preview" == $formtype) {
527 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
528 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large><P>\n";
529 if ( $isConflict ) {
530 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
531 "</h2>\n";
533 $previewtext = wfUnescapeHTML( $wpTextbox1 );
535 if($wgUser->getOption("previewontop")) {
536 $wgOut->addHTML($previewhead);
537 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) ."\n\n");
539 $wgOut->addHTML( "<br clear=\"all\" />\n" );
541 $wgOut->addHTML( "
542 <form id=\"editform\" name=\"editform\" method=\"post\" action=\"$action\"
543 enctype=\"application/x-www-form-urlencoded\">
544 <textarea tabindex=1 name=\"wpTextbox1\" rows={$rows}
545 cols={$cols}{$ew} wrap=\"virtual\">" .
546 $wgLang->recodeForEdit( $wpTextbox1 ) .
548 </textarea><br>
549 {$summary}: <input tabindex=2 type=text value=\"{$wpSummary}\"
550 name=\"wpSummary\" maxlength=200 size=60><br>
551 {$checkboxhtml}
552 <input tabindex=5 type=submit value=\"{$save}\" name=\"wpSave\">
553 <input tabindex=6 type=submit value=\"{$prev}\" name=\"wpPreview\">
554 <em>{$cancel}</em> | <em>{$edithelp}</em>
555 <br><br>{$copywarn}
556 <input type=hidden value=\"{$wpEdittime}\" name=\"wpEdittime\">\n" );
558 if ( $isConflict ) {
559 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
560 DifferenceEngine::showDiff( $wpTextbox2, $wpTextbox1,
561 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
563 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
564 <textarea tabindex=6 name=\"wpTextbox2\" rows={$rows} cols={$cols} wrap=virtual>"
565 . $wgLang->recodeForEdit( $wpTextbox2 ) .
567 </textarea>" );
569 $wgOut->addHTML( "</form>\n" );
570 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
571 $wgOut->addHTML($previewhead);
572 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) );
577 # Theoretically we could defer these whole insert and update
578 # functions for after display, but that's taking a big leap
579 # of faith, and we want to be able to report database
580 # errors at some point.
582 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
584 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
585 $fname = "Article::insertNewArticle";
587 $ns = $wgTitle->getNamespace();
588 $ttl = $wgTitle->getDBkey();
589 $text = $this->preSaveTransform( $text );
590 if ( preg_match( "/^#redirect/i", $text ) ) { $redir = 1; }
591 else { $redir = 0; }
593 $now = wfTimestampNow();
594 $won = wfInvertTimestamp( $now );
595 wfSeedRandom();
596 $rand = mt_rand() / mt_getrandmax();
597 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
598 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
599 "cur_restrictions,cur_user_text,cur_is_redirect," .
600 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
601 wfStrencode( $text ) . "', '" .
602 wfStrencode( $summary ) . "', '" .
603 $wgUser->getID() . "', '{$now}', " .
604 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
605 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
606 $res = wfQuery( $sql, $fname );
608 $newid = wfInsertId();
609 $wgTitle->resetArticleID( $newid );
611 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
612 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
613 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
614 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
615 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
616 wfStrencode( $wgUser->getName() ) . "','" .
617 wfStrencode( $summary ) . "',0,0," .
618 ( $wgUser->isBot() ? 1 : 0 ) . ")";
619 wfQuery( $sql, $fname );
620 if ($watchthis) {
621 if(!$wgTitle->userIsWatching()) $this->watch();
622 } else {
623 if ( $wgTitle->userIsWatching() ) {
624 $this->unwatch();
628 $this->showArticle( $text, wfMsg( "newarticle" ) );
631 function updateArticle( $text, $summary, $minor, $watchthis )
633 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
634 global $wgDBtransactions;
635 $fname = "Article::updateArticle";
637 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
638 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
639 if ( preg_match( "/^(#redirect[^\\n]+)/i", $text, $m ) ) {
640 $redir = 1;
641 $text = $m[1] . "\n"; # Remove all content but redirect
643 else { $redir = 0; }
644 $this->loadLastEdit();
646 $text = $this->preSaveTransform( $text );
648 # Update article, but only if changed.
650 if( $wgDBtransactions ) {
651 $sql = "BEGIN";
652 wfQuery( $sql );
654 $oldtext = $this->getContent( true );
656 if ( 0 != strcmp( $text, $oldtext ) ) {
657 $this->mCountAdjustment = $this->isCountable( $text )
658 - $this->isCountable( $oldtext );
660 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
661 "old_comment,old_user,old_user_text,old_timestamp," .
662 "old_minor_edit,inverse_timestamp) VALUES (" .
663 $wgTitle->getNamespace() . ", '" .
664 wfStrencode( $wgTitle->getDBkey() ) . "', '" .
665 wfStrencode( $oldtext ) . "', '" .
666 wfStrencode( $this->getComment() ) . "', " .
667 $this->getUser() . ", '" .
668 wfStrencode( $this->getUserText() ) . "', '" .
669 $this->getTimestamp() . "', " . $me1 . ", '" .
670 wfInvertTimestamp( $this->getTimestamp() ) . "')";
671 $res = wfQuery( $sql, $fname );
672 $oldid = wfInsertID( $res );
674 $now = wfTimestampNow();
675 $won = wfInvertTimestamp( $now );
676 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
677 "',cur_comment='" . wfStrencode( $summary ) .
678 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
679 ",cur_timestamp='{$now}',cur_user_text='" .
680 wfStrencode( $wgUser->getName() ) .
681 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
682 "WHERE cur_id=" . $this->getID();
683 wfQuery( $sql, $fname );
685 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
686 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
687 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
688 "'{$now}','{$now}'," . $wgTitle->getNamespace() . ",'" .
689 wfStrencode( $wgTitle->getDBkey() ) . "',0,{$me2}," .
690 ( $wgUser->isBot() ? 1 : 0 ) . "," .
691 $this->getID() . "," . $wgUser->getID() . ",'" .
692 wfStrencode( $wgUser->getName() ) . "','" .
693 wfStrencode( $summary ) . "',0,{$oldid})";
694 wfQuery( $sql, $fname );
696 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
697 "WHERE rc_namespace=" . $wgTitle->getNamespace() . " AND " .
698 "rc_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' AND " .
699 "rc_timestamp='" . $this->getTimestamp() . "'";
700 wfQuery( $sql, $fname );
702 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
703 "WHERE rc_cur_id=" . $this->getID();
704 wfQuery( $sql, $fname );
706 if( $wgDBtransactions ) {
707 $sql = "COMMIT";
708 wfQuery( $sql );
711 if ($watchthis) {
712 if (!$wgTitle->userIsWatching()) $this->watch();
713 } else {
714 if ( $wgTitle->userIsWatching() ) {
715 $this->unwatch();
719 $this->showArticle( $text, wfMsg( "updated" ) );
722 # After we've either updated or inserted the article, update
723 # the link tables and redirect to the new page.
725 function showArticle( $text, $subtitle )
727 global $wgOut, $wgTitle, $wgUser, $wgLinkCache;
729 $wgLinkCache = new LinkCache();
730 $wgOut->addWikiText( $text ); # Just to update links
732 $this->editUpdates( $text );
733 if( preg_match( "/^#redirect/i", $text ) )
734 $r = "redirect=no";
735 else
736 $r = "";
737 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL(), $r ) );
740 # If the page we've just displayed is in the "Image" namespace,
741 # we follow it with an upload history of the image and its usage.
743 function imageHistory()
745 global $wgUser, $wgOut, $wgLang, $wgTitle;
746 $fname = "Article::imageHistory";
748 $sql = "SELECT img_size,img_description,img_user," .
749 "img_user_text,img_timestamp FROM image WHERE " .
750 "img_name='" . wfStrencode( $wgTitle->getDBkey() ) . "'";
751 $res = wfQuery( $sql, $fname );
753 if ( 0 == wfNumRows( $res ) ) { return; }
755 $sk = $wgUser->getSkin();
756 $s = $sk->beginImageHistoryList();
758 $line = wfFetchObject( $res );
759 $s .= $sk->imageHistoryLine( true, $line->img_timestamp,
760 $wgTitle->getText(), $line->img_user,
761 $line->img_user_text, $line->img_size, $line->img_description );
763 $sql = "SELECT oi_size,oi_description,oi_user," .
764 "oi_user_text,oi_timestamp,oi_archive_name FROM oldimage WHERE " .
765 "oi_name='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
766 "ORDER BY oi_timestamp DESC";
767 $res = wfQuery( $sql, $fname );
769 while ( $line = wfFetchObject( $res ) ) {
770 $s .= $sk->imageHistoryLine( false, $line->oi_timestamp,
771 $line->oi_archive_name, $line->oi_user,
772 $line->oi_user_text, $line->oi_size, $line->oi_description );
774 $s .= $sk->endImageHistoryList();
775 $wgOut->addHTML( $s );
778 function imageLinks()
780 global $wgUser, $wgOut, $wgTitle;
782 $wgOut->addHTML( "<h2>" . wfMsg( "imagelinks" ) . "</h2>\n" );
784 $sql = "SELECT il_from FROM imagelinks WHERE il_to='" .
785 wfStrencode( $wgTitle->getDBkey() ) . "'";
786 $res = wfQuery( $sql, "Article::imageLinks" );
788 if ( 0 == wfNumRows( $res ) ) {
789 $wgOut->addHtml( "<p>" . wfMsg( "nolinkstoimage" ) . "\n" );
790 return;
792 $wgOut->addHTML( "<p>" . wfMsg( "linkstoimage" ) . "\n<ul>" );
794 $sk = $wgUser->getSkin();
795 while ( $s = wfFetchObject( $res ) ) {
796 $name = $s->il_from;
797 $link = $sk->makeKnownLink( $name, "" );
798 $wgOut->addHTML( "<li>{$link}</li>\n" );
800 $wgOut->addHTML( "</ul>\n" );
803 # Add this page to my watchlist
805 function watch()
807 global $wgUser, $wgTitle, $wgOut, $wgLang;
808 global $wgDeferredUpdateList;
810 if ( 0 == $wgUser->getID() ) {
811 $wgOut->errorpage( "watchnologin", "watchnologintext" );
812 return;
814 if ( wfReadOnly() ) {
815 $wgOut->readOnlyPage();
816 return;
818 $wgUser->addWatch( $wgTitle );
820 $wgOut->setPagetitle( wfMsg( "addedwatch" ) );
821 $wgOut->setRobotpolicy( "noindex,follow" );
823 $sk = $wgUser->getSkin() ;
824 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
826 $text = str_replace( "$1", $link ,
827 wfMsg( "addedwatchtext" ) );
828 $wgOut->addHTML( $text );
830 $up = new UserUpdate();
831 array_push( $wgDeferredUpdateList, $up );
833 $wgOut->returnToMain( false );
836 function unwatch()
838 global $wgUser, $wgTitle, $wgOut, $wgLang;
839 global $wgDeferredUpdateList;
841 if ( 0 == $wgUser->getID() ) {
842 $wgOut->errorpage( "watchnologin", "watchnologintext" );
843 return;
845 if ( wfReadOnly() ) {
846 $wgOut->readOnlyPage();
847 return;
849 $wgUser->removeWatch( $wgTitle );
851 $wgOut->setPagetitle( wfMsg( "removedwatch" ) );
852 $wgOut->setRobotpolicy( "noindex,follow" );
854 $sk = $wgUser->getSkin() ;
855 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
857 $text = str_replace( "$1", $link ,
858 wfMsg( "removedwatchtext" ) );
859 $wgOut->addHTML( $text );
861 $up = new UserUpdate();
862 array_push( $wgDeferredUpdateList, $up );
864 $wgOut->returnToMain( false );
867 # This shares a lot of issues (and code) with Recent Changes
869 function history()
871 global $wgUser, $wgOut, $wgLang, $wgTitle, $offset, $limit;
873 # If page hasn't changed, client can cache this
875 $wgOut->checkLastModified( $this->getTimestamp() );
876 wfProfileIn( "Article::history" );
878 $wgOut->setPageTitle( $wgTitle->getPRefixedText() );
879 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
880 $wgOut->setArticleFlag( false );
881 $wgOut->setRobotpolicy( "noindex,nofollow" );
883 if( $wgTitle->getArticleID() == 0 ) {
884 $wgOut->addHTML( wfMsg( "nohistory" ) );
885 wfProfileOut();
886 return;
889 $offset = (int)$offset;
890 $limit = (int)$limit;
891 if( $limit == 0 ) $limit = 50;
892 $namespace = $wgTitle->getNamespace();
893 $title = $wgTitle->getText();
894 $sql = "SELECT old_id,old_user," .
895 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
896 "FROM old USE INDEX (name_title_timestamp) " .
897 "WHERE old_namespace={$namespace} AND " .
898 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
899 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
900 $res = wfQuery( $sql, "Article::history" );
902 $revs = wfNumRows( $res );
903 if( $wgTitle->getArticleID() == 0 ) {
904 $wgOut->addHTML( wfMsg( "nohistory" ) );
905 wfProfileOut();
906 return;
909 $sk = $wgUser->getSkin();
910 $numbar = wfViewPrevNext(
911 $offset, $limit,
912 $wgTitle->getPrefixedText(),
913 "action=history" );
914 $s = $numbar;
915 $s .= $sk->beginHistoryList();
917 if($offset == 0 )
918 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
919 $this->getUserText(), $namespace,
920 $title, 0, $this->getComment(),
921 ( $this->getMinorEdit() > 0 ) );
923 $revs = wfNumRows( $res );
924 while ( $line = wfFetchObject( $res ) ) {
925 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
926 $line->old_user_text, $namespace,
927 $title, $line->old_id,
928 $line->old_comment, ( $line->old_minor_edit > 0 ) );
930 $s .= $sk->endHistoryList();
931 $s .= $numbar;
932 $wgOut->addHTML( $s );
933 wfProfileOut();
936 function protect()
938 global $wgUser, $wgOut, $wgTitle;
940 if ( ! $wgUser->isSysop() ) {
941 $wgOut->sysopRequired();
942 return;
944 if ( wfReadOnly() ) {
945 $wgOut->readOnlyPage();
946 return;
948 $id = $wgTitle->getArticleID();
949 if ( 0 == $id ) {
950 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
951 return;
953 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
954 "cur_restrictions='sysop' WHERE cur_id={$id}";
955 wfQuery( $sql, "Article::protect" );
957 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
960 function unprotect()
962 global $wgUser, $wgOut, $wgTitle;
964 if ( ! $wgUser->isSysop() ) {
965 $wgOut->sysopRequired();
966 return;
968 if ( wfReadOnly() ) {
969 $wgOut->readOnlyPage();
970 return;
972 $id = $wgTitle->getArticleID();
973 if ( 0 == $id ) {
974 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
975 return;
977 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
978 "cur_restrictions='' WHERE cur_id={$id}";
979 wfQuery( $sql, "Article::unprotect" );
981 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
984 function delete()
986 global $wgUser, $wgOut, $wgTitle;
987 global $wpConfirm, $wpReason, $image, $oldimage;
989 # Anybody can delete old revisions of images; only sysops
990 # can delete articles and current images
992 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
993 $wgOut->sysopRequired();
994 return;
996 if ( wfReadOnly() ) {
997 $wgOut->readOnlyPage();
998 return;
1001 # Better double-check that it hasn't been deleted yet!
1002 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
1003 if ( $image ) {
1004 if ( "" == trim( $image ) ) {
1005 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1006 return;
1008 $sub = str_replace( "$1", $image, wfMsg( "deletesub" ) );
1009 } else {
1011 if ( ( "" == trim( $wgTitle->getText() ) )
1012 or ( $wgTitle->getArticleId() == 0 ) ) {
1013 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1014 return;
1016 $sub = str_replace( "$1", $wgTitle->getPrefixedText(),
1017 wfMsg( "deletesub" ) );
1019 # determine whether this page has earlier revisions
1020 # and insert a warning if it does
1021 # we select the text because it might be useful below
1022 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
1023 $res=wfQuery($sql,$fname);
1024 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
1025 $skin=$wgUser->getSkin();
1026 $wgOut->addHTML("<B>".wfMsg("historywarning"));
1027 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
1030 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."'";
1031 $res=wfQuery($sql,$fname);
1032 if( ($s=wfFetchObject($res))) {
1034 # if this is a mini-text, we can paste part of it into the deletion reason
1036 #if this is empty, an earlier revision may contain "useful" text
1037 if($s->cur_text!="") {
1038 $text=$s->cur_text;
1039 } else {
1040 if($old) {
1041 $text=$old->old_text;
1042 $blanked=1;
1047 $length=strlen($text);
1049 # this should not happen, since it is not possible to store an empty, new
1050 # page. Let's insert a standard text in case it does, though
1051 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
1054 if($length < 500 && !$wpReason) {
1056 # comment field=255, let's grep the first 150 to have some user
1057 # space left
1058 $text=substr($text,0,150);
1059 # let's strip out newlines and HTML tags
1060 $text=preg_replace("/\"/","'",$text);
1061 $text=preg_replace("/\</","&lt;",$text);
1062 $text=preg_replace("/\>/","&gt;",$text);
1063 $text=preg_replace("/[\n\r]/","",$text);
1064 if(!$blanked) {
1065 $wpReason=wfMsg("excontent"). " '".$text;
1066 } else {
1067 $wpReason=wfMsg("exbeforeblank") . " '".$text;
1069 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
1070 $wpReason.="'";
1076 # Likewise, deleting old images doesn't require confirmation
1077 if ( $oldimage || 1 == $wpConfirm ) {
1078 $this->doDelete();
1079 return;
1082 $wgOut->setSubtitle( $sub );
1083 $wgOut->setRobotpolicy( "noindex,nofollow" );
1084 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1086 $t = $wgTitle->getPrefixedURL();
1087 $q = "action=delete";
1089 if ( $image ) {
1090 $q .= "&image={$image}";
1091 } else if ( $oldimage ) {
1092 $q .= "&oldimage={$oldimage}";
1093 } else {
1094 $q .= "&title={$t}";
1096 $formaction = wfEscapeHTML( wfLocalUrl( "", $q ) );
1097 $confirm = wfMsg( "confirm" );
1098 $check = wfMsg( "confirmcheck" );
1099 $delcom = wfMsg( "deletecomment" );
1101 $wgOut->addHTML( "
1102 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1103 <table border=0><tr><td align=right>
1104 {$delcom}:</td><td align=left>
1105 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
1106 </td></tr><tr><td>&nbsp;</td></tr>
1107 <tr><td align=right>
1108 <input type=checkbox name=\"wpConfirm\" value='1'>
1109 </td><td>{$check}</td>
1110 </tr><tr><td>&nbsp;</td><td>
1111 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1112 </td></tr></table></form>\n" );
1114 $wgOut->returnToMain( false );
1117 function doDelete()
1119 global $wgOut, $wgTitle, $wgUser, $wgLang;
1120 global $image, $oldimage, $wpReason;
1121 $fname = "Article::doDelete";
1123 if ( $image ) {
1124 $dest = wfImageDir( $image );
1125 $archive = wfImageDir( $image );
1126 if ( ! unlink( "{$dest}/{$image}" ) ) {
1127 $wgOut->fileDeleteError( "{$dest}/{$image}" );
1128 return;
1130 $sql = "DELETE FROM image WHERE img_name='" .
1131 wfStrencode( $image ) . "'";
1132 wfQuery( $sql, $fname );
1134 $sql = "SELECT oi_archive_name FROM oldimage WHERE oi_name='" .
1135 wfStrencode( $image ) . "'";
1136 $res = wfQuery( $sql, $fname );
1138 while ( $s = wfFetchObject( $res ) ) {
1139 $this->doDeleteOldImage( $s->oi_archive_name );
1141 $sql = "DELETE FROM oldimage WHERE oi_name='" .
1142 wfStrencode( $image ) . "'";
1143 wfQuery( $sql, $fname );
1145 # Image itself is now gone, and database is cleaned.
1146 # Now we remove the image description page.
1148 $nt = Title::newFromText( $wgLang->getNsText( Namespace::getImage() ) . ":" . $image );
1149 $this->doDeleteArticle( $nt );
1151 $deleted = $image;
1152 } else if ( $oldimage ) {
1153 $this->doDeleteOldImage( $oldimage );
1154 $sql = "DELETE FROM oldimage WHERE oi_archive_name='" .
1155 wfStrencode( $oldimage ) . "'";
1156 wfQuery( $sql, $fname );
1158 $deleted = $oldimage;
1159 } else {
1160 $this->doDeleteArticle( $wgTitle );
1161 $deleted = $wgTitle->getPrefixedText();
1163 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1164 $wgOut->setRobotpolicy( "noindex,nofollow" );
1166 $sk = $wgUser->getSkin();
1167 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1168 Namespace::getWikipedia() ) .
1169 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1171 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1172 $text = str_replace( "$2", $loglink, $text );
1174 $wgOut->addHTML( "<p>" . $text );
1175 $wgOut->returnToMain( false );
1178 function doDeleteOldImage( $oldimage )
1180 global $wgOut;
1182 $name = substr( $oldimage, 15 );
1183 $archive = wfImageArchiveDir( $name );
1184 if ( ! unlink( "{$archive}/{$oldimage}" ) ) {
1185 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
1189 function doDeleteArticle( $title )
1191 global $wgUser, $wgOut, $wgLang, $wpReason, $wgTitle, $wgDeferredUpdateList;
1193 $fname = "Article::doDeleteArticle";
1194 $ns = $title->getNamespace();
1195 $t = wfStrencode( $title->getDBkey() );
1196 $id = $title->getArticleID();
1198 if ( "" == $t ) {
1199 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1200 return;
1203 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1204 array_push( $wgDeferredUpdateList, $u );
1206 # Move article and history to the "archive" table
1207 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1208 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1209 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1210 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1211 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1212 wfQuery( $sql, $fname );
1214 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1215 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1216 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1217 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1218 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1219 wfQuery( $sql, $fname );
1221 # Now that it's safely backed up, delete it
1223 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1224 "cur_title='{$t}'";
1225 wfQuery( $sql, $fname );
1227 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1228 "old_title='{$t}'";
1229 wfQuery( $sql, $fname );
1231 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1232 "rc_title='{$t}'";
1233 wfQuery( $sql, $fname );
1235 # Finally, clean up the link tables
1237 if ( 0 != $id ) {
1238 $t = wfStrencode( $title->getPrefixedDBkey() );
1239 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1240 $res = wfQuery( $sql, $fname );
1242 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1243 $now = wfTimestampNow();
1244 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1245 $first = true;
1247 while ( $s = wfFetchObject( $res ) ) {
1248 $nt = Title::newFromDBkey( $s->l_from );
1249 $lid = $nt->getArticleID();
1251 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1252 $first = false;
1253 $sql .= "({$lid},'{$t}')";
1254 $sql2 .= "{$lid}";
1256 $sql2 .= ")";
1257 if ( ! $first ) {
1258 wfQuery( $sql, $fname );
1259 wfQuery( $sql2, $fname );
1261 wfFreeResult( $res );
1263 $sql = "DELETE FROM links WHERE l_to={$id}";
1264 wfQuery( $sql, $fname );
1266 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1267 wfQuery( $sql, $fname );
1269 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1270 wfQuery( $sql, $fname );
1272 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1273 wfQuery( $sql, $fname );
1276 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1277 $art = $title->getPrefixedText();
1278 $wpReason = wfCleanQueryVar( $wpReason );
1279 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1281 # Clear the cached article id so the interface doesn't act like we exist
1282 $wgTitle->resetArticleID( 0 );
1283 $wgTitle->mArticleID = 0;
1286 function revert()
1288 global $wgOut;
1289 global $oldimage;
1291 if ( strlen( $oldimage ) < 16 ) {
1292 $wgOut->unexpectedValueError( "oldimage", $oldimage );
1293 return;
1295 if ( wfReadOnly() ) {
1296 $wgOut->readOnlyPage();
1297 return;
1299 $name = substr( $oldimage, 15 );
1301 $dest = wfImageDir( $name );
1302 $archive = wfImageArchiveDir( $name );
1303 $curfile = "{$dest}/{$name}";
1305 if ( ! is_file( $curfile ) ) {
1306 $wgOut->fileNotFoundError( $curfile );
1307 return;
1309 $oldver = wfTimestampNow() . "!{$name}";
1310 $size = wfGetSQL( "oldimage", "oi_size", "oi_archive_name='" .
1311 wfStrencode( $oldimage ) . "'" );
1313 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
1314 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
1315 return;
1317 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
1318 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
1320 wfRecordUpload( $name, $oldver, $size, wfMsg( "reverted" ) );
1322 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1323 $wgOut->setRobotpolicy( "noindex,nofollow" );
1324 $wgOut->addHTML( wfMsg( "imagereverted" ) );
1325 $wgOut->returnToMain( false );
1328 function rollback()
1330 global $wgUser, $wgTitle, $wgLang, $wgOut, $from;
1332 if ( ! $wgUser->isSysop() ) {
1333 $wgOut->sysopRequired();
1334 return;
1337 # Replace all this user's current edits with the next one down
1338 $tt = wfStrencode( $wgTitle->getDBKey() );
1339 $n = $wgTitle->getNamespace();
1341 # Get the last editor
1342 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1343 $res = wfQuery( $sql );
1344 if( ($x = wfNumRows( $res )) != 1 ) {
1345 # Something wrong
1346 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1347 return;
1349 $s = wfFetchObject( $res );
1350 $ut = wfStrencode( $s->cur_user_text );
1351 $uid = $s->cur_user;
1352 $pid = $s->cur_id;
1354 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
1355 if( $from != $s->cur_user_text ) {
1356 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
1357 $wgOut->addWikiText( wfMsg( "alreadyrolled",
1358 htmlspecialchars( $wgTitle->getPrefixedText()),
1359 htmlspecialchars( $from ),
1360 htmlspecialchars( $s->cur_user_text ) ) );
1361 if($s->cur_comment != "") {
1362 $wgOut->addHTML(
1363 wfMsg("editcomment",
1364 htmlspecialchars( $s->cur_comment ) ) );
1366 return;
1369 # Get the last edit not by this guy
1370 $sql = "SELECT old_text,old_user,old_user_text
1371 FROM old USE INDEX (name_title_timestamp)
1372 WHERE old_namespace={$n} AND old_title='{$tt}'
1373 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1374 ORDER BY inverse_timestamp LIMIT 1";
1375 $res = wfQuery( $sql );
1376 if( wfNumRows( $res ) != 1 ) {
1377 # Something wrong
1378 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1379 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1380 return;
1382 $s = wfFetchObject( $res );
1384 # Save it!
1385 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1386 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1387 $wgOut->setRobotpolicy( "noindex,nofollow" );
1388 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1389 $this->updateArticle( $s->old_text, $newcomment, 1, $wgTitle->userIsWatching() );
1391 $wgOut->returnToMain( false );
1395 # Do standard deferred updates after page view
1397 /* private */ function viewUpdates()
1399 global $wgDeferredUpdateList, $wgTitle;
1401 if ( 0 != $this->getID() ) {
1402 $u = new ViewCountUpdate( $this->getID() );
1403 array_push( $wgDeferredUpdateList, $u );
1404 $u = new SiteStatsUpdate( 1, 0, 0 );
1405 array_push( $wgDeferredUpdateList, $u );
1407 $u = new UserTalkUpdate( 0, $wgTitle->getNamespace(),
1408 $wgTitle->getDBkey() );
1409 array_push( $wgDeferredUpdateList, $u );
1413 # Do standard deferred updates after page edit.
1414 # Every 1000th edit, prune the recent changes table.
1416 /* private */ function editUpdates( $text )
1418 global $wgDeferredUpdateList, $wgTitle;
1420 wfSeedRandom();
1421 if ( 0 == mt_rand( 0, 999 ) ) {
1422 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1423 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1424 wfQuery( $sql );
1426 $id = $this->getID();
1427 $title = $wgTitle->getPrefixedDBkey();
1428 $adj = $this->mCountAdjustment;
1430 if ( 0 != $id ) {
1431 $u = new LinksUpdate( $id, $title );
1432 array_push( $wgDeferredUpdateList, $u );
1433 $u = new SiteStatsUpdate( 0, 1, $adj );
1434 array_push( $wgDeferredUpdateList, $u );
1435 $u = new SearchUpdate( $id, $title, $text );
1436 array_push( $wgDeferredUpdateList, $u );
1438 $u = new UserTalkUpdate( 1, $wgTitle->getNamespace(),
1439 $wgTitle->getDBkey() );
1440 array_push( $wgDeferredUpdateList, $u );
1444 /* private */ function setOldSubtitle()
1446 global $wgLang, $wgOut;
1448 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1449 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1450 $wgOut->setSubtitle( "({$r})" );
1453 function blockedIPpage()
1455 global $wgOut, $wgUser, $wgLang;
1457 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1458 $wgOut->setRobotpolicy( "noindex,nofollow" );
1459 $wgOut->setArticleFlag( false );
1461 $id = $wgUser->blockedBy();
1462 $reason = $wgUser->blockedFor();
1464 $name = User::whoIs( $id );
1465 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1466 ":{$name}|{$name}]]";
1468 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1469 $text = str_replace( "$2", $reason, $text );
1470 $wgOut->addWikiText( $text );
1471 $wgOut->returnToMain( false );
1474 # This function is called right before saving the wikitext,
1475 # so we can do things like signatures and links-in-context.
1477 function preSaveTransform( $text )
1479 $s = "";
1480 while ( "" != $text ) {
1481 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1482 $s .= $this->pstPass2( $p[0] );
1484 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1485 else {
1486 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1487 $s .= "<nowiki>{$q[0]}</nowiki>";
1488 $text = $q[1];
1491 return rtrim( $s );
1494 /* private */ function pstPass2( $text )
1496 global $wgUser, $wgLang, $wgTitle, $wgLocaltimezone;
1498 # Signatures
1500 $n = $wgUser->getName();
1501 $k = $wgUser->getOption( "nickname" );
1502 if ( "" == $k ) { $k = $n; }
1503 if(isset($wgLocaltimezone)) {
1504 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1506 $d = $wgLang->timeanddate( wfTimestampNow(), false ) .
1507 " (" . date( "T" ) . ")";
1508 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1510 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1511 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1512 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1513 Namespace::getUser() ) . ":$n|$k]]", $text );
1515 # Context links: [[|name]] and [[name (context)|]]
1517 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1518 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1519 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1521 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1522 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1523 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1524 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1525 # [[ns:page (cont)|]]
1526 $context = "";
1527 $t = $wgTitle->getText();
1528 if ( preg_match( $conpat, $t, $m ) ) {
1529 $context = $m[2];
1531 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1532 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1533 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1535 if ( "" == $context ) {
1536 $text = preg_replace( $p2, "[[\\1]]", $text );
1537 } else {
1538 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1540 # Replace local image links with new [[image:]] style
1542 $text = preg_replace(
1543 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/upload\/" .
1544 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1545 "\\1[[image:\\3.\\4]]", $text );
1546 $text = preg_replace(
1547 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/images\/uploads\/" .
1548 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1549 "\\1[[image:\\3.\\4]]", $text );
1551 return $text;
1555 /* Caching functions */
1557 function tryFileCache() {
1558 if($this->isFileCacheable()) {
1559 if($this->isFileCacheGood()) {
1560 wfDebug( " tryFileCache() - about to load\n" );
1561 $this->loadFromFileCache();
1562 exit;
1563 } else {
1564 wfDebug( " tryFileCache() - starting buffer\n" );
1565 ob_start( array(&$this, 'saveToFileCache' ) );
1567 } else {
1568 wfDebug( " tryFileCache() - not cacheable\n" );
1572 function isFileCacheable() {
1573 global $wgUser, $wgTitle, $wgUseFileCache, $wgShowIPinHeader;
1574 global $action, $oldid, $diff, $redirect, $printable;
1575 return $wgUseFileCache
1576 and (!$wgShowIPinHeader)
1577 and ($wgUser->getId() == 0)
1578 and (!$wgUser->getNewtalk())
1579 and ($wgTitle->getNamespace != Namespace::getSpecial())
1580 and ($action == "view")
1581 and (!isset($oldid))
1582 and (!isset($diff))
1583 and (!isset($redirect))
1584 and (!isset($printable))
1585 and (!$this->mRedirectedFrom);
1589 function fileCacheName() {
1590 global $wgTitle, $wgFileCacheDirectory, $wgLang;
1591 if( !$this->mFileCache ) {
1592 $hash = md5( $key = $wgTitle->getDbkey() );
1593 if( $wgTitle->getNamespace() )
1594 $key = $wgLang->getNsText( $wgTitle->getNamespace() ) . ":" . $key;
1595 $key = str_replace( ".", "%2E", urlencode( $key ) );
1596 $hash1 = substr( $hash, 0, 1 );
1597 $hash2 = substr( $hash, 0, 2 );
1598 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$key}.html";
1599 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
1601 return $this->mFileCache;
1604 function isFileCacheGood() {
1605 global $wgUser, $wgCacheEpoch;
1606 if(!file_exists( $fn = $this->fileCacheName() ) ) return false;
1607 $cachetime = wfUnix2Timestamp( filemtime( $fn ) );
1608 $good = ( $this->mTouched <= $cachetime ) &&
1609 ($wgCacheEpoch <= $cachetime );
1610 wfDebug(" isFileCacheGood() - cachetime $cachetime, touched {$this->mTouched} epoch {$wgCacheEpoch}, good $good\n");
1611 return $good;
1614 function loadFromFileCache() {
1615 global $wgUseGzip;
1616 wfDebug(" loadFromFileCache()\n");
1617 $filename=$this->fileCacheName();
1618 $filenamegz = "{$filename}.gz";
1619 if( $wgUseGzip
1620 && wfClientAcceptsGzip()
1621 && file_exists( $filenamegz)
1622 && ( filemtime( $filenamegz ) >= filemtime( $filename ) ) ) {
1623 wfDebug(" sending gzip\n");
1624 header( "Content-Encoding: gzip" );
1625 header( "Vary: Accept-Encoding" );
1626 $filename = $filenamegz;
1628 readfile( $filename );
1631 function saveToFileCache( $text ) {
1632 global $wgUseGzip, $wgCompressByDefault;
1634 wfDebug(" saveToFileCache()\n");
1635 $filename=$this->fileCacheName();
1636 $mydir2=substr($filename,0,strrpos($filename,"/")); # subdirectory level 2
1637 $mydir1=substr($mydir2,0,strrpos($mydir2,"/")); # subdirectory level 1
1638 if(!file_exists($mydir1)) { mkdir($mydir1,0777); } # create if necessary
1639 if(!file_exists($mydir2)) { mkdir($mydir2,0777); }
1640 $f = fopen( $filename, "w" );
1641 if($f) {
1642 $now = wfTimestampNow();
1643 fwrite( $f, str_replace( "</html>",
1644 "<!-- Cached $now -->\n</html>",
1645 $text ) );
1646 fclose( $f );
1647 if( $wgUseGzip and $wgCompressByDefault ) {
1648 $start = microtime();
1649 wfDebug(" saving gzip\n");
1650 $gzout = gzencode( str_replace( "</html>",
1651 "<!-- Cached/compressed $now -->\n</html>",
1652 $text ) );
1653 if( $gzout === false ) {
1654 wfDebug(" failed to gzip compress, sending plaintext\n");
1655 return $text;
1657 if( $f = fopen( "{$filename}.gz", "w" ) ) {
1658 fwrite( $f, $gzout );
1659 fclose( $f );
1660 $end = microtime();
1662 list($usec1, $sec1) = explode(" ",$start);
1663 list($usec2, $sec2) = explode(" ",$end);
1664 $interval = ((float)$usec2 + (float)$sec2) -
1665 ((float)$usec1 + (float)$sec1);
1666 wfDebug(" saved gzip in $interval\n");
1667 } else {
1668 wfDebug(" failed to write gzip, still sending\n" );
1670 header( "Content-Encoding: gzip" );
1671 header( "Vary: Accept-Encoding" );
1672 return $gzout;
1675 return $text;