Support for [[Wikipedia:Book sources]] (or localized text), content of
[mediawiki.git] / includes / Article.php
blob3453d7e720c5d8cc421c29d5eb3cbe8a1422bbb0
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();
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();
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");
540 $wgOut->addHTML( "
541 <form id=\"editform\" method=\"post\" action=\"$action\"
542 enctype=\"application/x-www-form-urlencoded\">
543 <textarea tabindex=1 name=\"wpTextbox1\" rows={$rows}
544 cols={$cols}{$ew} wrap=\"virtual\">" .
545 $wgLang->recodeForEdit( $wpTextbox1 ) .
547 </textarea><br>
548 {$summary}: <input tabindex=2 type=text value=\"{$wpSummary}\"
549 name=\"wpSummary\" maxlength=200 size=60><br>
550 {$checkboxhtml}
551 <input tabindex=5 type=submit value=\"{$save}\" name=\"wpSave\">
552 <input tabindex=6 type=submit value=\"{$prev}\" name=\"wpPreview\">
553 <em>{$cancel}</em> | <em>{$edithelp}</em>
554 <br><br>{$copywarn}
555 <input type=hidden value=\"{$wpEdittime}\" name=\"wpEdittime\">\n" );
557 if ( $isConflict ) {
558 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
559 DifferenceEngine::showDiff( $wpTextbox2, $wpTextbox1,
560 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
562 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
563 <textarea tabindex=6 name=\"wpTextbox2\" rows={$rows} cols={$cols} wrap=virtual>"
564 . $wgLang->recodeForEdit( $wpTextbox2 ) .
566 </textarea>" );
568 $wgOut->addHTML( "</form>\n" );
569 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
570 $wgOut->addHTML($previewhead);
571 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) );
576 # Theoretically we could defer these whole insert and update
577 # functions for after display, but that's taking a big leap
578 # of faith, and we want to be able to report database
579 # errors at some point.
581 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
583 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
584 $fname = "Article::insertNewArticle";
586 $ns = $wgTitle->getNamespace();
587 $ttl = $wgTitle->getDBkey();
588 $text = $this->preSaveTransform( $text );
589 if ( preg_match( "/^#redirect/i", $text ) ) { $redir = 1; }
590 else { $redir = 0; }
592 $now = wfTimestampNow();
593 $won = wfInvertTimestamp( $now );
594 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
595 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
596 "cur_restrictions,cur_user_text,cur_is_redirect," .
597 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
598 wfStrencode( $text ) . "', '" .
599 wfStrencode( $summary ) . "', '" .
600 $wgUser->getID() . "', '{$now}', " .
601 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
602 wfStrencode( $wgUser->getName() ) . "', $redir, 1, RAND(), '{$now}', '{$won}')";
603 $res = wfQuery( $sql, $fname );
605 $newid = wfInsertId();
606 $wgTitle->resetArticleID( $newid );
608 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
609 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
610 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
611 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
612 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
613 wfStrencode( $wgUser->getName() ) . "','" .
614 wfStrencode( $summary ) . "',0,0," .
615 ( $wgUser->isBot() ? 1 : 0 ) . ")";
616 wfQuery( $sql, $fname );
617 if ($watchthis) {
618 if(!$wgTitle->userIsWatching()) $this->watch();
619 } else {
620 if ( $wgTitle->userIsWatching() ) {
621 $this->unwatch();
625 $this->showArticle( $text, wfMsg( "newarticle" ) );
628 function updateArticle( $text, $summary, $minor, $watchthis )
630 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
631 global $wgDBtransactions;
632 $fname = "Article::updateArticle";
634 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
635 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
636 if ( preg_match( "/^(#redirect[^\\n]+)/i", $text, $m ) ) {
637 $redir = 1;
638 $text = $m[1] . "\n"; # Remove all content but redirect
640 else { $redir = 0; }
641 $this->loadLastEdit();
643 $text = $this->preSaveTransform( $text );
645 # Update article, but only if changed.
647 if( $wgDBtransactions ) {
648 $sql = "BEGIN";
649 wfQuery( $sql );
651 $oldtext = $this->getContent( true );
653 if ( 0 != strcmp( $text, $oldtext ) ) {
654 $this->mCountAdjustment = $this->isCountable( $text )
655 - $this->isCountable( $oldtext );
657 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
658 "old_comment,old_user,old_user_text,old_timestamp," .
659 "old_minor_edit,inverse_timestamp) VALUES (" .
660 $wgTitle->getNamespace() . ", '" .
661 wfStrencode( $wgTitle->getDBkey() ) . "', '" .
662 wfStrencode( $oldtext ) . "', '" .
663 wfStrencode( $this->getComment() ) . "', " .
664 $this->getUser() . ", '" .
665 wfStrencode( $this->getUserText() ) . "', '" .
666 $this->getTimestamp() . "', " . $me1 . ", '" .
667 wfInvertTimestamp( $this->getTimestamp() ) . "')";
668 $res = wfQuery( $sql, $fname );
669 $oldid = wfInsertID( $res );
671 $now = wfTimestampNow();
672 $won = wfInvertTimestamp( $now );
673 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
674 "',cur_comment='" . wfStrencode( $summary ) .
675 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
676 ",cur_timestamp='{$now}',cur_user_text='" .
677 wfStrencode( $wgUser->getName() ) .
678 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
679 "WHERE cur_id=" . $this->getID();
680 wfQuery( $sql, $fname );
682 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
683 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
684 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
685 "'{$now}','{$now}'," . $wgTitle->getNamespace() . ",'" .
686 wfStrencode( $wgTitle->getDBkey() ) . "',0,{$me2}," .
687 ( $wgUser->isBot() ? 1 : 0 ) . "," .
688 $this->getID() . "," . $wgUser->getID() . ",'" .
689 wfStrencode( $wgUser->getName() ) . "','" .
690 wfStrencode( $summary ) . "',0,{$oldid})";
691 wfQuery( $sql, $fname );
693 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
694 "WHERE rc_namespace=" . $wgTitle->getNamespace() . " AND " .
695 "rc_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' AND " .
696 "rc_timestamp='" . $this->getTimestamp() . "'";
697 wfQuery( $sql, $fname );
699 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
700 "WHERE rc_cur_id=" . $this->getID();
701 wfQuery( $sql, $fname );
703 if( $wgDBtransactions ) {
704 $sql = "COMMIT";
705 wfQuery( $sql );
708 if ($watchthis) {
709 if (!$wgTitle->userIsWatching()) $this->watch();
710 } else {
711 if ( $wgTitle->userIsWatching() ) {
712 $this->unwatch();
716 $this->showArticle( $text, wfMsg( "updated" ) );
719 # After we've either updated or inserted the article, update
720 # the link tables and redirect to the new page.
722 function showArticle( $text, $subtitle )
724 global $wgOut, $wgTitle, $wgUser, $wgLinkCache;
726 $wgLinkCache = new LinkCache();
727 $wgOut->addWikiText( $text ); # Just to update links
729 $this->editUpdates( $text );
730 if( preg_match( "/^#redirect/i", $text ) )
731 $r = "redirect=no";
732 else
733 $r = "";
734 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL(), $r ) );
737 # If the page we've just displayed is in the "Image" namespace,
738 # we follow it with an upload history of the image and its usage.
740 function imageHistory()
742 global $wgUser, $wgOut, $wgLang, $wgTitle;
743 $fname = "Article::imageHistory";
745 $sql = "SELECT img_size,img_description,img_user," .
746 "img_user_text,img_timestamp FROM image WHERE " .
747 "img_name='" . wfStrencode( $wgTitle->getDBkey() ) . "'";
748 $res = wfQuery( $sql, $fname );
750 if ( 0 == wfNumRows( $res ) ) { return; }
752 $sk = $wgUser->getSkin();
753 $s = $sk->beginImageHistoryList();
755 $line = wfFetchObject( $res );
756 $s .= $sk->imageHistoryLine( true, $line->img_timestamp,
757 $wgTitle->getText(), $line->img_user,
758 $line->img_user_text, $line->img_size, $line->img_description );
760 $sql = "SELECT oi_size,oi_description,oi_user," .
761 "oi_user_text,oi_timestamp,oi_archive_name FROM oldimage WHERE " .
762 "oi_name='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
763 "ORDER BY oi_timestamp DESC";
764 $res = wfQuery( $sql, $fname );
766 while ( $line = wfFetchObject( $res ) ) {
767 $s .= $sk->imageHistoryLine( false, $line->oi_timestamp,
768 $line->oi_archive_name, $line->oi_user,
769 $line->oi_user_text, $line->oi_size, $line->oi_description );
771 $s .= $sk->endImageHistoryList();
772 $wgOut->addHTML( $s );
775 function imageLinks()
777 global $wgUser, $wgOut, $wgTitle;
779 $wgOut->addHTML( "<h2>" . wfMsg( "imagelinks" ) . "</h2>\n" );
781 $sql = "SELECT il_from FROM imagelinks WHERE il_to='" .
782 wfStrencode( $wgTitle->getDBkey() ) . "'";
783 $res = wfQuery( $sql, "Article::imageLinks" );
785 if ( 0 == wfNumRows( $res ) ) {
786 $wgOut->addHtml( "<p>" . wfMsg( "nolinkstoimage" ) . "\n" );
787 return;
789 $wgOut->addHTML( "<p>" . wfMsg( "linkstoimage" ) . "\n<ul>" );
791 $sk = $wgUser->getSkin();
792 while ( $s = wfFetchObject( $res ) ) {
793 $name = $s->il_from;
794 $link = $sk->makeKnownLink( $name, "" );
795 $wgOut->addHTML( "<li>{$link}</li>\n" );
797 $wgOut->addHTML( "</ul>\n" );
800 # Add this page to my watchlist
802 function watch()
804 global $wgUser, $wgTitle, $wgOut, $wgLang;
805 global $wgDeferredUpdateList;
807 if ( 0 == $wgUser->getID() ) {
808 $wgOut->errorpage( "watchnologin", "watchnologintext" );
809 return;
811 if ( wfReadOnly() ) {
812 $wgOut->readOnlyPage();
813 return;
815 $wgUser->addWatch( $wgTitle );
817 $wgOut->setPagetitle( wfMsg( "addedwatch" ) );
818 $wgOut->setRobotpolicy( "noindex,follow" );
820 $sk = $wgUser->getSkin() ;
821 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
823 $text = str_replace( "$1", $link ,
824 wfMsg( "addedwatchtext" ) );
825 $wgOut->addHTML( $text );
827 $up = new UserUpdate();
828 array_push( $wgDeferredUpdateList, $up );
830 $wgOut->returnToMain( false );
833 function unwatch()
835 global $wgUser, $wgTitle, $wgOut, $wgLang;
836 global $wgDeferredUpdateList;
838 if ( 0 == $wgUser->getID() ) {
839 $wgOut->errorpage( "watchnologin", "watchnologintext" );
840 return;
842 if ( wfReadOnly() ) {
843 $wgOut->readOnlyPage();
844 return;
846 $wgUser->removeWatch( $wgTitle );
848 $wgOut->setPagetitle( wfMsg( "removedwatch" ) );
849 $wgOut->setRobotpolicy( "noindex,follow" );
851 $sk = $wgUser->getSkin() ;
852 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
854 $text = str_replace( "$1", $link ,
855 wfMsg( "removedwatchtext" ) );
856 $wgOut->addHTML( $text );
858 $up = new UserUpdate();
859 array_push( $wgDeferredUpdateList, $up );
861 $wgOut->returnToMain( false );
864 # This shares a lot of issues (and code) with Recent Changes
866 function history()
868 global $wgUser, $wgOut, $wgLang, $wgTitle, $offset, $limit;
870 # If page hasn't changed, client can cache this
872 $wgOut->checkLastModified( $this->getTimestamp() );
873 wfProfileIn( "Article::history" );
875 $wgOut->setPageTitle( $wgTitle->getPRefixedText() );
876 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
877 $wgOut->setArticleFlag( false );
878 $wgOut->setRobotpolicy( "noindex,nofollow" );
880 if( $wgTitle->getArticleID() == 0 ) {
881 $wgOut->addHTML( wfMsg( "nohistory" ) );
882 wfProfileOut();
883 return;
886 $offset = (int)$offset;
887 $limit = (int)$limit;
888 if( $limit == 0 ) $limit = 50;
889 $namespace = $wgTitle->getNamespace();
890 $title = $wgTitle->getText();
891 $sql = "SELECT old_id,old_user," .
892 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
893 "FROM old USE INDEX (name_title_timestamp) " .
894 "WHERE old_namespace={$namespace} AND " .
895 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
896 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
897 $res = wfQuery( $sql, "Article::history" );
899 $revs = wfNumRows( $res );
900 if( $wgTitle->getArticleID() == 0 ) {
901 $wgOut->addHTML( wfMsg( "nohistory" ) );
902 wfProfileOut();
903 return;
906 $sk = $wgUser->getSkin();
907 $numbar = wfViewPrevNext(
908 $offset, $limit,
909 $wgTitle->getPrefixedText(),
910 "action=history" );
911 $s = $numbar;
912 $s .= $sk->beginHistoryList();
914 if($offset == 0 )
915 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
916 $this->getUserText(), $namespace,
917 $title, 0, $this->getComment(),
918 ( $this->getMinorEdit() > 0 ) );
920 $revs = wfNumRows( $res );
921 while ( $line = wfFetchObject( $res ) ) {
922 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
923 $line->old_user_text, $namespace,
924 $title, $line->old_id,
925 $line->old_comment, ( $line->old_minor_edit > 0 ) );
927 $s .= $sk->endHistoryList();
928 $s .= $numbar;
929 $wgOut->addHTML( $s );
930 wfProfileOut();
933 function protect()
935 global $wgUser, $wgOut, $wgTitle;
937 if ( ! $wgUser->isSysop() ) {
938 $wgOut->sysopRequired();
939 return;
941 if ( wfReadOnly() ) {
942 $wgOut->readOnlyPage();
943 return;
945 $id = $wgTitle->getArticleID();
946 if ( 0 == $id ) {
947 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
948 return;
950 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
951 "cur_restrictions='sysop' WHERE cur_id={$id}";
952 wfQuery( $sql, "Article::protect" );
954 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
957 function unprotect()
959 global $wgUser, $wgOut, $wgTitle;
961 if ( ! $wgUser->isSysop() ) {
962 $wgOut->sysopRequired();
963 return;
965 if ( wfReadOnly() ) {
966 $wgOut->readOnlyPage();
967 return;
969 $id = $wgTitle->getArticleID();
970 if ( 0 == $id ) {
971 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
972 return;
974 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
975 "cur_restrictions='' WHERE cur_id={$id}";
976 wfQuery( $sql, "Article::unprotect" );
978 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
981 function delete()
983 global $wgUser, $wgOut, $wgTitle;
984 global $wpConfirm, $wpReason, $image, $oldimage;
986 # Anybody can delete old revisions of images; only sysops
987 # can delete articles and current images
989 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
990 $wgOut->sysopRequired();
991 return;
993 if ( wfReadOnly() ) {
994 $wgOut->readOnlyPage();
995 return;
998 # Better double-check that it hasn't been deleted yet!
999 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
1000 if ( $image ) {
1001 if ( "" == trim( $image ) ) {
1002 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1003 return;
1005 $sub = str_replace( "$1", $image, wfMsg( "deletesub" ) );
1006 } else {
1007 if ( ( "" == trim( $wgTitle->getText() ) )
1008 or ( $wgTitle->getArticleId() == 0 ) ) {
1009 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1010 return;
1012 $sub = str_replace( "$1", $wgTitle->getPrefixedText(),
1013 wfMsg( "deletesub" ) );
1016 # Likewise, deleting old images doesn't require confirmation
1017 if ( $oldimage || 1 == $wpConfirm ) {
1018 $this->doDelete();
1019 return;
1022 $wgOut->setSubtitle( $sub );
1023 $wgOut->setRobotpolicy( "noindex,nofollow" );
1024 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1026 $t = $wgTitle->getPrefixedURL();
1027 $q = "action=delete";
1029 if ( $image ) {
1030 $q .= "&image={$image}";
1031 } else if ( $oldimage ) {
1032 $q .= "&oldimage={$oldimage}";
1033 } else {
1034 $q .= "&title={$t}";
1036 $formaction = wfEscapeHTML( wfLocalUrl( "", $q ) );
1037 $confirm = wfMsg( "confirm" );
1038 $check = wfMsg( "confirmcheck" );
1039 $delcom = wfMsg( "deletecomment" );
1041 $wgOut->addHTML( "
1042 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1043 <table border=0><tr><td align=right>
1044 {$delcom}:</td><td align=left>
1045 <input type=text size=20 name=\"wpReason\" value=\"{$wpReason}\">
1046 </td></tr><tr><td>&nbsp;</td></tr>
1047 <tr><td align=right>
1048 <input type=checkbox name=\"wpConfirm\" value='1'>
1049 </td><td>{$check}</td>
1050 </tr><tr><td>&nbsp;</td><td>
1051 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1052 </td></tr></table></form>\n" );
1054 $wgOut->returnToMain( false );
1057 function doDelete()
1059 global $wgOut, $wgTitle, $wgUser, $wgLang;
1060 global $image, $oldimage, $wpReason;
1061 $fname = "Article::doDelete";
1063 if ( $image ) {
1064 $dest = wfImageDir( $image );
1065 $archive = wfImageDir( $image );
1066 if ( ! unlink( "{$dest}/{$image}" ) ) {
1067 $wgOut->fileDeleteError( "{$dest}/{$image}" );
1068 return;
1070 $sql = "DELETE FROM image WHERE img_name='" .
1071 wfStrencode( $image ) . "'";
1072 wfQuery( $sql, $fname );
1074 $sql = "SELECT oi_archive_name FROM oldimage WHERE oi_name='" .
1075 wfStrencode( $image ) . "'";
1076 $res = wfQuery( $sql, $fname );
1078 while ( $s = wfFetchObject( $res ) ) {
1079 $this->doDeleteOldImage( $s->oi_archive_name );
1081 $sql = "DELETE FROM oldimage WHERE oi_name='" .
1082 wfStrencode( $image ) . "'";
1083 wfQuery( $sql, $fname );
1085 # Image itself is now gone, and database is cleaned.
1086 # Now we remove the image description page.
1088 $nt = Title::newFromText( $wgLang->getNsText( Namespace::getImage() ) . ":" . $image );
1089 $this->doDeleteArticle( $nt );
1091 $deleted = $image;
1092 } else if ( $oldimage ) {
1093 $this->doDeleteOldImage( $oldimage );
1094 $sql = "DELETE FROM oldimage WHERE oi_archive_name='" .
1095 wfStrencode( $oldimage ) . "'";
1096 wfQuery( $sql, $fname );
1098 $deleted = $oldimage;
1099 } else {
1100 $this->doDeleteArticle( $wgTitle );
1101 $deleted = $wgTitle->getPrefixedText();
1103 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1104 $wgOut->setRobotpolicy( "noindex,nofollow" );
1106 $sk = $wgUser->getSkin();
1107 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1108 Namespace::getWikipedia() ) .
1109 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1111 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1112 $text = str_replace( "$2", $loglink, $text );
1114 $wgOut->addHTML( "<p>" . $text );
1115 $wgOut->returnToMain( false );
1118 function doDeleteOldImage( $oldimage )
1120 global $wgOut;
1122 $name = substr( $oldimage, 15 );
1123 $archive = wfImageArchiveDir( $name );
1124 if ( ! unlink( "{$archive}/{$oldimage}" ) ) {
1125 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
1129 function doDeleteArticle( $title )
1131 global $wgUser, $wgOut, $wgLang, $wpReason, $wgTitle, $wgDeferredUpdateList;
1133 $fname = "Article::doDeleteArticle";
1134 $ns = $title->getNamespace();
1135 $t = wfStrencode( $title->getDBkey() );
1136 $id = $title->getArticleID();
1138 if ( "" == $t ) {
1139 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1140 return;
1143 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1144 array_push( $wgDeferredUpdateList, $u );
1146 # Move article and history to the "archive" table
1147 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1148 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1149 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1150 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1151 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1152 wfQuery( $sql, $fname );
1154 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1155 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1156 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1157 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1158 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1159 wfQuery( $sql, $fname );
1161 # Now that it's safely backed up, delete it
1163 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1164 "cur_title='{$t}'";
1165 wfQuery( $sql, $fname );
1167 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1168 "old_title='{$t}'";
1169 wfQuery( $sql, $fname );
1171 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1172 "rc_title='{$t}'";
1173 wfQuery( $sql, $fname );
1175 # Finally, clean up the link tables
1177 if ( 0 != $id ) {
1178 $t = wfStrencode( $title->getPrefixedDBkey() );
1179 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1180 $res = wfQuery( $sql, $fname );
1182 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1183 $now = wfTimestampNow();
1184 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1185 $first = true;
1187 while ( $s = wfFetchObject( $res ) ) {
1188 $nt = Title::newFromDBkey( $s->l_from );
1189 $lid = $nt->getArticleID();
1191 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1192 $first = false;
1193 $sql .= "({$lid},'{$t}')";
1194 $sql2 .= "{$lid}";
1196 $sql2 .= ")";
1197 if ( ! $first ) {
1198 wfQuery( $sql, $fname );
1199 wfQuery( $sql2, $fname );
1201 wfFreeResult( $res );
1203 $sql = "DELETE FROM links WHERE l_to={$id}";
1204 wfQuery( $sql, $fname );
1206 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1207 wfQuery( $sql, $fname );
1209 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1210 wfQuery( $sql, $fname );
1212 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1213 wfQuery( $sql, $fname );
1216 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1217 $art = $title->getPrefixedText();
1218 $wpReason = wfCleanQueryVar( $wpReason );
1219 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1221 # Clear the cached article id so the interface doesn't act like we exist
1222 $wgTitle->resetArticleID( 0 );
1223 $wgTitle->mArticleID = 0;
1226 function revert()
1228 global $wgOut;
1229 global $oldimage;
1231 if ( strlen( $oldimage ) < 16 ) {
1232 $wgOut->unexpectedValueError( "oldimage", $oldimage );
1233 return;
1235 if ( wfReadOnly() ) {
1236 $wgOut->readOnlyPage();
1237 return;
1239 $name = substr( $oldimage, 15 );
1241 $dest = wfImageDir( $name );
1242 $archive = wfImageArchiveDir( $name );
1243 $curfile = "{$dest}/{$name}";
1245 if ( ! is_file( $curfile ) ) {
1246 $wgOut->fileNotFoundError( $curfile );
1247 return;
1249 $oldver = wfTimestampNow() . "!{$name}";
1250 $size = wfGetSQL( "oldimage", "oi_size", "oi_archive_name='" .
1251 wfStrencode( $oldimage ) . "'" );
1253 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
1254 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
1255 return;
1257 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
1258 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
1260 wfRecordUpload( $name, $oldver, $size, wfMsg( "reverted" ) );
1262 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1263 $wgOut->setRobotpolicy( "noindex,nofollow" );
1264 $wgOut->addHTML( wfMsg( "imagereverted" ) );
1265 $wgOut->returnToMain( false );
1268 function rollback()
1270 global $wgUser, $wgTitle, $wgLang, $wgOut;
1272 if ( ! $wgUser->isSysop() ) {
1273 $wgOut->sysopRequired();
1274 return;
1277 # Replace all this user's current edits with the next one down
1278 $tt = wfStrencode( $wgTitle->getDBKey() );
1279 $n = $wgTitle->getNamespace();
1281 # Get the last editor
1282 $sql = "SELECT cur_id,cur_user,cur_user_text FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1283 $res = wfQuery( $sql );
1284 if( ($x = wfNumRows( $res )) != 1 ) {
1285 # Something wrong
1286 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1287 return;
1289 $s = wfFetchObject( $res );
1290 $ut = wfStrencode( $s->cur_user_text );
1291 $uid = $s->cur_user;
1292 $pid = $s->cur_id;
1294 # Get the last edit not by this guy
1295 $sql = "SELECT old_text,old_user,old_user_text
1296 FROM old USE INDEX (name_title_timestamp)
1297 WHERE old_namespace={$n} AND old_title='{$tt}'
1298 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1299 ORDER BY inverse_timestamp LIMIT 1";
1300 $res = wfQuery( $sql );
1301 if( wfNumRows( $res ) != 1 ) {
1302 # Something wrong
1303 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1304 return;
1306 $s = wfFetchObject( $res );
1308 # Save it!
1309 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1310 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1311 $wgOut->setRobotpolicy( "noindex,nofollow" );
1312 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1313 $this->updateArticle( $s->old_text, $newcomment, 1, $wgTitle->userIsWatching() );
1315 $wgOut->returnToMain( false );
1319 # Do standard deferred updates after page view
1321 /* private */ function viewUpdates()
1323 global $wgDeferredUpdateList, $wgTitle;
1325 if ( 0 != $this->getID() ) {
1326 $u = new ViewCountUpdate( $this->getID() );
1327 array_push( $wgDeferredUpdateList, $u );
1328 $u = new SiteStatsUpdate( 1, 0, 0 );
1329 array_push( $wgDeferredUpdateList, $u );
1331 $u = new UserTalkUpdate( 0, $wgTitle->getNamespace(),
1332 $wgTitle->getDBkey() );
1333 array_push( $wgDeferredUpdateList, $u );
1337 # Do standard deferred updates after page edit.
1338 # Every 1000th edit, prune the recent changes table.
1340 /* private */ function editUpdates( $text )
1342 global $wgDeferredUpdateList, $wgTitle;
1344 wfSeedRandom();
1345 if ( 0 == mt_rand( 0, 999 ) ) {
1346 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1347 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1348 wfQuery( $sql );
1350 $id = $this->getID();
1351 $title = $wgTitle->getPrefixedDBkey();
1352 $adj = $this->mCountAdjustment;
1354 if ( 0 != $id ) {
1355 $u = new LinksUpdate( $id, $title );
1356 array_push( $wgDeferredUpdateList, $u );
1357 $u = new SiteStatsUpdate( 0, 1, $adj );
1358 array_push( $wgDeferredUpdateList, $u );
1359 $u = new SearchUpdate( $id, $title, $text );
1360 array_push( $wgDeferredUpdateList, $u );
1362 $u = new UserTalkUpdate( 1, $wgTitle->getNamespace(),
1363 $wgTitle->getDBkey() );
1364 array_push( $wgDeferredUpdateList, $u );
1368 /* private */ function setOldSubtitle()
1370 global $wgLang, $wgOut;
1372 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1373 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1374 $wgOut->setSubtitle( "({$r})" );
1377 function blockedIPpage()
1379 global $wgOut, $wgUser, $wgLang;
1381 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1382 $wgOut->setRobotpolicy( "noindex,nofollow" );
1383 $wgOut->setArticleFlag( false );
1385 $id = $wgUser->blockedBy();
1386 $reason = $wgUser->blockedFor();
1388 $name = User::whoIs( $id );
1389 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1390 ":{$name}|{$name}]]";
1392 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1393 $text = str_replace( "$2", $reason, $text );
1394 $wgOut->addWikiText( $text );
1395 $wgOut->returnToMain( false );
1398 # This function is called right before saving the wikitext,
1399 # so we can do things like signatures and links-in-context.
1401 function preSaveTransform( $text )
1403 $s = "";
1404 while ( "" != $text ) {
1405 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1406 $s .= $this->pstPass2( $p[0] );
1408 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1409 else {
1410 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1411 $s .= "<nowiki>{$q[0]}</nowiki>";
1412 $text = $q[1];
1415 return rtrim( $s );
1418 /* private */ function pstPass2( $text )
1420 global $wgUser, $wgLang, $wgTitle, $wgLocaltimezone;
1422 # Signatures
1424 $n = $wgUser->getName();
1425 $k = $wgUser->getOption( "nickname" );
1426 if ( "" == $k ) { $k = $n; }
1427 if(isset($wgLocaltimezone)) {
1428 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1430 $d = $wgLang->timeanddate( wfTimestampNow(), false ) .
1431 " (" . date( "T" ) . ")";
1432 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1434 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1435 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1436 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1437 Namespace::getUser() ) . ":$n|$k]]", $text );
1439 # Context links: [[|name]] and [[name (context)|]]
1441 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1442 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1443 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1445 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1446 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1447 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1448 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1449 # [[ns:page (cont)|]]
1450 $context = "";
1451 $t = $wgTitle->getText();
1452 if ( preg_match( $conpat, $t, $m ) ) {
1453 $context = $m[2];
1455 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1456 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1457 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1459 if ( "" == $context ) {
1460 $text = preg_replace( $p2, "[[\\1]]", $text );
1461 } else {
1462 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1464 # Replace local image links with new [[image:]] style
1466 $text = preg_replace(
1467 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/upload\/" .
1468 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1469 "\\1[[image:\\3.\\4]]", $text );
1470 $text = preg_replace(
1471 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/images\/uploads\/" .
1472 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1473 "\\1[[image:\\3.\\4]]", $text );
1475 return $text;
1479 /* Caching functions */
1481 function tryFileCache() {
1482 if($this->isFileCacheable()) {
1483 if($this->isFileCacheGood()) {
1484 wfDebug( " tryFileCache() - about to load\n" );
1485 $this->loadFromFileCache();
1486 exit;
1487 } else {
1488 wfDebug( " tryFileCache() - starting buffer\n" );
1489 ob_start( array(&$this, 'saveToFileCache' ) );
1491 } else {
1492 wfDebug( " tryFileCache() - not cacheable\n" );
1496 function isFileCacheable() {
1497 global $wgUser, $wgTitle, $wgUseFileCache, $wgShowIPinHeader;
1498 global $action, $oldid, $diff, $redirect, $printable;
1499 return $wgUseFileCache
1500 and (!$wgShowIPinHeader)
1501 and ($wgUser->getId() == 0)
1502 and (!$wgUser->getNewtalk())
1503 and ($wgTitle->getNamespace != Namespace::getSpecial())
1504 and ($action == "view")
1505 and (!isset($oldid))
1506 and (!isset($diff))
1507 and (!isset($redirect))
1508 and (!isset($printable))
1509 and (!$this->mRedirectedFrom);
1513 function fileCacheName() {
1514 global $wgTitle, $wgFileCacheDirectory, $wgLang;
1515 if( !$this->mFileCache ) {
1516 $hash = md5( $key = $wgTitle->getDbkey() );
1517 if( $wgTitle->getNamespace() )
1518 $key = $wgLang->getNsText( $wgTitle->getNamespace() ) . ":" . $key;
1519 $key = str_replace( ".", "%2E", urlencode( $key ) );
1520 $hash1 = substr( $hash, 0, 1 );
1521 $hash2 = substr( $hash, 0, 2 );
1522 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$key}.html";
1523 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
1525 return $this->mFileCache;
1528 function isFileCacheGood() {
1529 global $wgUser, $wgCacheEpoch;
1530 if(!file_exists( $fn = $this->fileCacheName() ) ) return false;
1531 $cachetime = wfUnix2Timestamp( filemtime( $fn ) );
1532 $good = ( $this->mTouched <= $cachetime ) &&
1533 ($wgCacheEpoch <= $cachetime );
1534 wfDebug(" isFileCacheGood() - cachetime $cachetime, touched {$this->mTouched} epoch {$wgCacheEpoch}, good $good\n");
1535 return $good;
1538 function loadFromFileCache() {
1539 wfDebug(" loadFromFileCache()\n");
1540 readfile($this->fileCacheName());
1543 function saveToFileCache( $text ) {
1545 wfDebug(" saveToFileCache()\n");
1546 $filename=$this->fileCacheName();
1547 $mydir2=substr($filename,0,strrpos($filename,"/")); # subdirectory level 2
1548 $mydir1=substr($mydir2,0,strrpos($mydir2,"/")); # subdirectory level 1
1549 if(!file_exists($mydir1)) { mkdir($mydir1,0777); } # create if necessary
1550 if(!file_exists($mydir2)) { mkdir($mydir2,0777); }
1551 $f = fopen( $filename, "w" );
1552 if($f) {
1553 fwrite( $f, str_replace( "</html>",
1554 "<!-- Cached " . wfTimestampNow() . " -->\n</html>",
1555 $text ) );
1556 fclose( $f );
1558 return $text;