Move page not just for sysops in bottomLinks()
[mediawiki.git] / includes / Article.php
blobe7819ef409449247142497a4bbca419dd2c78acc
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,$section,$count,$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 if($action=="edit") {
80 if($section!="") {
81 if($section=="new") { return ""; }
83 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
84 $this->mContent, -1,
85 PREG_SPLIT_DELIM_CAPTURE);
86 if($section==0) {
87 return trim($secs[0]);
88 } else {
89 return trim($secs[$section*2-1] . $secs[$section*2]);
93 return $this->mContent;
98 function loadContent( $noredir = false )
100 global $wgOut, $wgTitle;
101 global $oldid, $redirect; # From query
103 if ( $this->mContentLoaded ) return;
104 $fname = "Article::loadContent";
106 # Pre-fill content with error message so that if something
107 # fails we'll have something telling us what we intended.
109 $t = $wgTitle->getPrefixedText();
110 if ( $oldid ) { $t .= ",oldid={$oldid}"; }
111 if ( $redirect ) { $t .= ",redirect={$redirect}"; }
112 $this->mContent = str_replace( "$1", $t, wfMsg( "missingarticle" ) );
114 if ( ! $oldid ) { # Retrieve current version
115 $id = $this->getID();
116 if ( 0 == $id ) return;
118 $sql = "SELECT " .
119 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
120 "FROM cur WHERE cur_id={$id}";
121 $res = wfQuery( $sql, $fname );
122 if ( 0 == wfNumRows( $res ) ) { return; }
124 $s = wfFetchObject( $res );
126 # If we got a redirect, follow it (unless we've been told
127 # not to by either the function parameter or the query
129 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
130 ( preg_match( "/^#redirect/i", $s->cur_text ) ) ) {
131 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
132 $s->cur_text, $m ) ) {
133 $rt = Title::newFromText( $m[1] );
135 # Gotta hand redirects to special pages differently:
136 # Fill the HTTP response "Location" header and ignore
137 # the rest of the page we're on.
139 if ( $rt->getInterwiki() != "" ) {
140 $wgOut->redirect( $rt->getFullURL() ) ;
141 return;
143 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
144 $wgOut->redirect( wfLocalUrl(
145 $rt->getPrefixedURL() ) );
146 return;
148 $rid = $rt->getArticleID();
149 if ( 0 != $rid ) {
150 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
151 "cur_counter,cur_touched FROM cur WHERE cur_id={$rid}";
152 $res = wfQuery( $sql, $fname );
154 if ( 0 != wfNumRows( $res ) ) {
155 $this->mRedirectedFrom = $wgTitle->getPrefixedText();
156 $wgTitle = $rt;
157 $s = wfFetchObject( $res );
162 $this->mContent = $s->cur_text;
163 $this->mUser = $s->cur_user;
164 $this->mCounter = $s->cur_counter;
165 $this->mTimestamp = $s->cur_timestamp;
166 $this->mTouched = $s->cur_touched;
167 $wgTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
168 $wgTitle->mRestrictionsLoaded = true;
169 wfFreeResult( $res );
170 } else { # oldid set, retrieve historical version
171 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
172 "WHERE old_id={$oldid}";
173 $res = wfQuery( $sql, $fname );
174 if ( 0 == wfNumRows( $res ) ) { return; }
176 $s = wfFetchObject( $res );
177 $this->mContent = $s->old_text;
178 $this->mUser = $s->old_user;
179 $this->mCounter = 0;
180 $this->mTimestamp = $s->old_timestamp;
181 wfFreeResult( $res );
183 $this->mContentLoaded = true;
186 function getID() { global $wgTitle; return $wgTitle->getArticleID(); }
188 function getCount()
190 if ( -1 == $this->mCounter ) {
191 $id = $this->getID();
192 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
194 return $this->mCounter;
197 # Would the given text make this article a "good" article (i.e.,
198 # suitable for including in the article count)?
200 function isCountable( $text )
202 global $wgTitle, $wgUseCommaCount;
204 if ( 0 != $wgTitle->getNamespace() ) { return 0; }
205 if ( preg_match( "/^#redirect/i", $text ) ) { return 0; }
206 $token = ($wgUseCommaCount ? "," : "[[" );
207 if ( false === strstr( $text, $token ) ) { return 0; }
208 return 1;
211 # Load the field related to the last edit time of the article.
212 # This isn't necessary for all uses, so it's only done if needed.
214 /* private */ function loadLastEdit()
216 global $wgOut;
217 if ( -1 != $this->mUser ) return;
219 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
220 "cur_comment,cur_minor_edit FROM cur WHERE " .
221 "cur_id=" . $this->getID();
222 $res = wfQuery( $sql, "Article::loadLastEdit" );
224 if ( wfNumRows( $res ) > 0 ) {
225 $s = wfFetchObject( $res );
226 $this->mUser = $s->cur_user;
227 $this->mUserText = $s->cur_user_text;
228 $this->mTimestamp = $s->cur_timestamp;
229 $this->mComment = $s->cur_comment;
230 $this->mMinorEdit = $s->cur_minor_edit;
234 function getTimestamp()
236 $this->loadLastEdit();
237 return $this->mTimestamp;
240 function getUser()
242 $this->loadLastEdit();
243 return $this->mUser;
246 function getUserText()
248 $this->loadLastEdit();
249 return $this->mUserText;
252 function getComment()
254 $this->loadLastEdit();
255 return $this->mComment;
258 function getMinorEdit()
260 $this->loadLastEdit();
261 return $this->mMinorEdit;
264 # This is the default action of the script: just view the page of
265 # the given title.
267 function view()
269 global $wgUser, $wgOut, $wgTitle, $wgLang;
270 global $oldid, $diff; # From query
271 global $wgLinkCache;
272 wfProfileIn( "Article::view" );
274 $wgOut->setArticleFlag( true );
275 $wgOut->setRobotpolicy( "index,follow" );
277 # If we got diff and oldid in the query, we want to see a
278 # diff page instead of the article.
280 if ( isset( $diff ) ) {
281 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
282 $de = new DifferenceEngine( $oldid, $diff );
283 $de->showDiffPage();
284 wfProfileOut();
285 return;
287 $text = $this->getContent(); # May change wgTitle!
288 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
289 $wgOut->setHTMLTitle( $wgTitle->getPrefixedText() .
290 " - " . wfMsg( "wikititlesuffix" ) );
292 # We're looking at an old revision
294 if ( $oldid ) {
295 $this->setOldSubtitle();
296 $wgOut->setRobotpolicy( "noindex,follow" );
298 if ( "" != $this->mRedirectedFrom ) {
299 $sk = $wgUser->getSkin();
300 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
301 "redirect=no" );
302 $s = str_replace( "$1", $redir, wfMsg( "redirectedfrom" ) );
303 $wgOut->setSubtitle( $s );
305 $wgOut->checkLastModified( $this->mTouched );
306 $this->tryFileCache();
307 $wgLinkCache->preFill( $wgTitle );
308 $wgOut->addWikiText( $text );
310 # If the article we've just shown is in the "Image" namespace,
311 # follow it with the history list and link list for the image
312 # it describes.
314 if ( Namespace::getImage() == $wgTitle->getNamespace() ) {
315 $this->imageHistory();
316 $this->imageLinks();
318 $this->viewUpdates();
319 wfProfileOut();
322 # This is the function that gets called for "action=edit".
324 function edit()
326 global $wgOut, $wgUser, $wgTitle;
327 global $wpTextbox1, $wpSummary, $wpSave, $wpPreview;
328 global $wpMinoredit, $wpEdittime, $wpTextbox2;
330 $fields = array( "wpTextbox1", "wpSummary", "wpTextbox2" );
331 wfCleanFormFields( $fields );
333 if ( ! $wgTitle->userCanEdit() ) {
334 $this->view();
335 return;
337 if ( $wgUser->isBlocked() ) {
338 $this->blockedIPpage();
339 return;
341 if ( wfReadOnly() ) {
342 if( isset( $wpSave ) or isset( $wpPreview ) ) {
343 $this->editForm( "preview" );
344 } else {
345 $wgOut->readOnlyPage();
347 return;
349 if ( $_SERVER['REQUEST_METHOD'] != "POST" ) unset( $wpSave );
350 if ( isset( $wpSave ) ) {
351 $this->editForm( "save" );
352 } else if ( isset( $wpPreview ) ) {
353 $this->editForm( "preview" );
354 } else { # First time through
355 $this->editForm( "initial" );
359 # Since there is only one text field on the edit form,
360 # pressing <enter> will cause the form to be submitted, but
361 # the submit button value won't appear in the query, so we
362 # Fake it here before going back to edit(). This is kind of
363 # ugly, but it helps some old URLs to still work.
365 function submit()
367 global $wpSave, $wpPreview;
368 if ( ! isset( $wpPreview ) ) { $wpSave = 1; }
370 $this->edit();
373 # The edit form is self-submitting, so that when things like
374 # preview and edit conflicts occur, we get the same form back
375 # with the extra stuff added. Only when the final submission
376 # is made and all is well do we actually save and redirect to
377 # the newly-edited page.
379 function editForm( $formtype )
381 global $wgOut, $wgUser, $wgTitle;
382 global $wpTextbox1, $wpSummary, $wpWatchthis;
383 global $wpSave, $wpPreview;
384 global $wpMinoredit, $wpEdittime, $wpTextbox2, $wpSection;
385 global $oldid, $redirect, $section;
386 global $wgLang;
388 if(isset($wpSection)) { $section=$wpSection; }
390 $sk = $wgUser->getSkin();
391 $isConflict = false;
392 $wpTextbox1 = rtrim ( $wpTextbox1 ) ; # To avoid text getting longer on each preview
394 if(!$wgTitle->getArticleID()) { # new article
396 $wgOut->addWikiText(wfmsg("newarticletext"));
400 # Attempt submission here. This will check for edit conflicts,
401 # and redundantly check for locked database, blocked IPs, etc.
402 # that edit() already checked just in case someone tries to sneak
403 # in the back door with a hand-edited submission URL.
405 if ( "save" == $formtype ) {
406 if ( $wgUser->isBlocked() ) {
407 $this->blockedIPpage();
408 return;
410 if ( wfReadOnly() ) {
411 $wgOut->readOnlyPage();
412 return;
414 # If article is new, insert it.
416 $aid = $wgTitle->getArticleID();
417 if ( 0 == $aid ) {
418 # we need to strip Windoze linebreaks because some browsers
419 # append them and the string comparison fails
420 if ( ( "" == $wpTextbox1 ) ||
421 ( wfMsg( "newarticletext" ) == rtrim( preg_replace("/\r/","",$wpTextbox1) ) ) ) {
422 $wgOut->redirect( wfLocalUrl(
423 $wgTitle->getPrefixedURL() ) );
424 return;
426 $this->mCountAdjustment = $this->isCountable( $wpTextbox1 );
427 $this->insertNewArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
428 return;
430 # Article exists. Check for edit conflict.
432 $this->clear(); # Force reload of dates, etc.
433 if ( $this->getTimestamp() != $wpEdittime ) { $isConflict = true; }
434 $u = $wgUser->getID();
436 # Supress edit conflict with self
438 if ( ( 0 != $u ) && ( $this->getUser() == $u ) ) {
439 $isConflict = false;
441 if ( ! $isConflict ) {
442 # All's well: update the article here
443 $this->updateArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis, $wpSection );
444 return;
447 # First time through: get contents, set time for conflict
448 # checking, etc.
450 if ( "initial" == $formtype ) {
451 $wpEdittime = $this->getTimestamp();
452 $wpTextbox1 = $this->getContent(true);
453 $wpSummary = "";
455 $wgOut->setRobotpolicy( "noindex,nofollow" );
456 $wgOut->setArticleFlag( false );
458 if ( $isConflict ) {
459 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
460 wfMsg( "editconflict" ) );
461 $wgOut->setPageTitle( $s );
462 $wgOut->addHTML( wfMsg( "explainconflict" ) );
464 $wpTextbox2 = $wpTextbox1;
465 $wpTextbox1 = $this->getContent(true);
466 $wpEdittime = $this->getTimestamp();
467 } else {
468 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
469 wfMsg( "editing" ) );
471 if($section!="") {
472 if($section=="new") {
473 $s.=wfMsg("commentedit");
474 } else {
475 $s.=wfMsg("sectionedit");
478 $wgOut->setPageTitle( $s );
479 if ( $oldid ) {
480 $this->setOldSubtitle();
481 $wgOut->addHTML( wfMsg( "editingold" ) );
485 if( wfReadOnly() ) {
486 $wgOut->addHTML( "<strong>" .
487 wfMsg( "readonlywarning" ) .
488 "</strong>" );
490 if( $wgTitle->isProtected() ) {
491 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
492 "</strong><br />\n" );
495 $kblength = (int)(strlen( $wpTextbox1 ) / 1024);
496 if( $kblength > 29 ) {
497 $wgOut->addHTML( "<strong>" .
498 str_replace( '$1', $kblength , wfMsg( "longpagewarning" ) )
499 . "</strong>" );
502 $rows = $wgUser->getOption( "rows" );
503 $cols = $wgUser->getOption( "cols" );
505 $ew = $wgUser->getOption( "editwidth" );
506 if ( $ew ) $ew = " style=\"width:100%\"";
507 else $ew = "" ;
509 $q = "action=submit";
510 if ( "no" == $redirect ) { $q .= "&redirect=no"; }
511 $action = wfEscapeHTML( wfLocalUrl( $wgTitle->getPrefixedURL(), $q ) );
513 $summary = wfMsg( "summary" );
514 $subject = wfMsg("subject");
515 $minor = wfMsg( "minoredit" );
516 $watchthis = wfMsg ("watchthis");
517 $save = wfMsg( "savearticle" );
518 $prev = wfMsg( "showpreview" );
520 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedURL(),
521 wfMsg( "cancel" ) );
522 $edithelp = $sk->makeKnownLink( wfMsg( "edithelppage" ),
523 wfMsg( "edithelp" ) );
524 $copywarn = str_replace( "$1", $sk->makeKnownLink(
525 wfMsg( "copyrightpage" ) ), wfMsg( "copyrightwarning" ) );
527 $wpTextbox1 = wfEscapeHTML( $wpTextbox1 );
528 $wpTextbox2 = wfEscapeHTML( $wpTextbox2 );
529 $wpSummary = wfEscapeHTML( $wpSummary );
531 // activate checkboxes if user wants them to be always active
532 if (!$wpPreview && $wgUser->getOption("watchdefault")) $wpWatchthis=1;
533 if (!$wpPreview && $wgUser->getOption("minordefault")) $wpMinoredit=1;
535 // activate checkbox also if user is already watching the page,
536 // require wpWatchthis to be unset so that second condition is not
537 // checked unnecessarily
538 if (!$wpWatchthis && !$wpPreview && $wgTitle->userIsWatching()) $wpWatchthis=1;
540 if ( 0 != $wgUser->getID() ) {
541 $checkboxhtml=
542 "<input tabindex=3 type=checkbox value=1 name='wpMinoredit'".($wpMinoredit?" checked":"").">{$minor}".
543 "<input tabindex=4 type=checkbox name='wpWatchthis'".($wpWatchthis?" checked":"").">{$watchthis}<br>";
545 } else {
546 $checkboxhtml="";
550 if ( "preview" == $formtype) {
552 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
553 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large><P>\n";
554 if ( $isConflict ) {
555 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
556 "</h2>\n";
558 $previewtext = wfUnescapeHTML( $wpTextbox1 );
560 if($wgUser->getOption("previewontop")) {
561 $wgOut->addHTML($previewhead);
562 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) ."\n\n");
564 $wgOut->addHTML( "<br clear=\"all\" />\n" );
567 # if this is a comment, show a subject line at the top, which is also the edit summary.
568 # Otherwise, show a summary field at the bottom
569 if($section=="new") {
571 $commentsubject="{$subject}: <input tabindex=1 type=text value=\"{$wpSummary}\" name=\"wpSummary\" maxlength=200 size=60><br>";
572 } else {
574 $editsummary="{$summary}: <input tabindex=3 type=text value=\"{$wpSummary}\" name=\"wpSummary\" maxlength=200 size=60><br>";
577 $wgOut->addHTML( "
578 <form id=\"editform\" name=\"editform\" method=\"post\" action=\"$action\"
579 enctype=\"application/x-www-form-urlencoded\">
580 {$commentsubject}
581 <textarea tabindex=2 name=\"wpTextbox1\" rows={$rows}
582 cols={$cols}{$ew} wrap=\"virtual\">" .
583 $wgLang->recodeForEdit( $wpTextbox1 ) .
585 </textarea>
586 <br>{$editsummary}
587 {$checkboxhtml}
588 <input tabindex=5 type=submit value=\"{$save}\" name=\"wpSave\">
589 <input tabindex=6 type=submit value=\"{$prev}\" name=\"wpPreview\">
590 <em>{$cancel}</em> | <em>{$edithelp}</em>
591 <br><br>{$copywarn}
592 <input type=hidden value=\"{$section}\" name=\"wpSection\">
593 <input type=hidden value=\"{$wpEdittime}\" name=\"wpEdittime\">\n" );
595 if ( $isConflict ) {
596 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
597 DifferenceEngine::showDiff( $wpTextbox2, $wpTextbox1,
598 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
600 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
601 <textarea tabindex=6 name=\"wpTextbox2\" rows={$rows} cols={$cols} wrap=virtual>"
602 . $wgLang->recodeForEdit( $wpTextbox2 ) .
604 </textarea>" );
606 $wgOut->addHTML( "</form>\n" );
607 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
608 $wgOut->addHTML($previewhead);
609 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) );
614 # Theoretically we could defer these whole insert and update
615 # functions for after display, but that's taking a big leap
616 # of faith, and we want to be able to report database
617 # errors at some point.
619 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
621 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
622 $fname = "Article::insertNewArticle";
624 $ns = $wgTitle->getNamespace();
625 $ttl = $wgTitle->getDBkey();
626 $text = $this->preSaveTransform( $text );
627 if ( preg_match( "/^#redirect/i", $text ) ) { $redir = 1; }
628 else { $redir = 0; }
630 $now = wfTimestampNow();
631 $won = wfInvertTimestamp( $now );
632 wfSeedRandom();
633 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
634 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
635 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
636 "cur_restrictions,cur_user_text,cur_is_redirect," .
637 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
638 wfStrencode( $text ) . "', '" .
639 wfStrencode( $summary ) . "', '" .
640 $wgUser->getID() . "', '{$now}', " .
641 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
642 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
643 $res = wfQuery( $sql, $fname );
645 $newid = wfInsertId();
646 $wgTitle->resetArticleID( $newid );
648 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
649 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
650 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
651 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
652 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
653 wfStrencode( $wgUser->getName() ) . "','" .
654 wfStrencode( $summary ) . "',0,0," .
655 ( $wgUser->isBot() ? 1 : 0 ) . ")";
656 wfQuery( $sql, $fname );
657 if ($watchthis) {
658 if(!$wgTitle->userIsWatching()) $this->watch();
659 } else {
660 if ( $wgTitle->userIsWatching() ) {
661 $this->unwatch();
665 $this->showArticle( $text, wfMsg( "newarticle" ) );
668 function updateArticle( $text, $summary, $minor, $watchthis, $section )
670 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
671 global $wgDBtransactions;
672 $fname = "Article::updateArticle";
674 // insert updated section into old text if we have only edited part
675 // of the article
676 if ($section != "") {
677 $oldtext=$this->getContent();
678 if($section=="new") {
679 if($summary) $summary="== {$summary} ==\n\n";
680 $text=$oldtext."\n\n".$summary.$text;
681 } else {
682 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
683 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
684 $secs[$section*2]=$text."\n\n"; // replace with edited
685 if($section) { $secs[$section*2-1]=""; } // erase old headline
686 $text=join("",$secs);
689 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
690 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
691 if ( preg_match( "/^(#redirect[^\\n]+)/i", $text, $m ) ) {
692 $redir = 1;
693 $text = $m[1] . "\n"; # Remove all content but redirect
695 else { $redir = 0; }
696 $this->loadLastEdit();
698 $text = $this->preSaveTransform( $text );
700 # Update article, but only if changed.
702 if( $wgDBtransactions ) {
703 $sql = "BEGIN";
704 wfQuery( $sql );
706 $oldtext = $this->getContent( true );
708 if ( 0 != strcmp( $text, $oldtext ) ) {
709 $this->mCountAdjustment = $this->isCountable( $text )
710 - $this->isCountable( $oldtext );
712 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
713 "old_comment,old_user,old_user_text,old_timestamp," .
714 "old_minor_edit,inverse_timestamp) VALUES (" .
715 $wgTitle->getNamespace() . ", '" .
716 wfStrencode( $wgTitle->getDBkey() ) . "', '" .
717 wfStrencode( $oldtext ) . "', '" .
718 wfStrencode( $this->getComment() ) . "', " .
719 $this->getUser() . ", '" .
720 wfStrencode( $this->getUserText() ) . "', '" .
721 $this->getTimestamp() . "', " . $me1 . ", '" .
722 wfInvertTimestamp( $this->getTimestamp() ) . "')";
723 $res = wfQuery( $sql, $fname );
724 $oldid = wfInsertID( $res );
726 $now = wfTimestampNow();
727 $won = wfInvertTimestamp( $now );
728 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
729 "',cur_comment='" . wfStrencode( $summary ) .
730 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
731 ",cur_timestamp='{$now}',cur_user_text='" .
732 wfStrencode( $wgUser->getName() ) .
733 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
734 "WHERE cur_id=" . $this->getID();
735 wfQuery( $sql, $fname );
737 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
738 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
739 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
740 "'{$now}','{$now}'," . $wgTitle->getNamespace() . ",'" .
741 wfStrencode( $wgTitle->getDBkey() ) . "',0,{$me2}," .
742 ( $wgUser->isBot() ? 1 : 0 ) . "," .
743 $this->getID() . "," . $wgUser->getID() . ",'" .
744 wfStrencode( $wgUser->getName() ) . "','" .
745 wfStrencode( $summary ) . "',0,{$oldid})";
746 wfQuery( $sql, $fname );
748 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
749 "WHERE rc_namespace=" . $wgTitle->getNamespace() . " AND " .
750 "rc_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' AND " .
751 "rc_timestamp='" . $this->getTimestamp() . "'";
752 wfQuery( $sql, $fname );
754 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
755 "WHERE rc_cur_id=" . $this->getID();
756 wfQuery( $sql, $fname );
758 if( $wgDBtransactions ) {
759 $sql = "COMMIT";
760 wfQuery( $sql );
763 if ($watchthis) {
764 if (!$wgTitle->userIsWatching()) $this->watch();
765 } else {
766 if ( $wgTitle->userIsWatching() ) {
767 $this->unwatch();
771 $this->showArticle( $text, wfMsg( "updated" ) );
774 # After we've either updated or inserted the article, update
775 # the link tables and redirect to the new page.
777 function showArticle( $text, $subtitle )
779 global $wgOut, $wgTitle, $wgUser, $wgLinkCache, $wgUseBetterLinksUpdate;
781 $wgLinkCache = new LinkCache();
783 # Get old version of link table to allow incremental link updates
784 if ( $wgUseBetterLinksUpdate ) {
785 $wgLinkCache->preFill( $wgTitle );
786 $wgLinkCache->clear();
789 # Now update the link cache by parsing the text
790 $wgOut->addWikiText( $text );
792 $this->editUpdates( $text );
793 if( preg_match( "/^#redirect/i", $text ) )
794 $r = "redirect=no";
795 else
796 $r = "";
797 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL(), $r ) );
800 # If the page we've just displayed is in the "Image" namespace,
801 # we follow it with an upload history of the image and its usage.
803 function imageHistory()
805 global $wgUser, $wgOut, $wgLang, $wgTitle;
806 $fname = "Article::imageHistory";
808 $sql = "SELECT img_size,img_description,img_user," .
809 "img_user_text,img_timestamp FROM image WHERE " .
810 "img_name='" . wfStrencode( $wgTitle->getDBkey() ) . "'";
811 $res = wfQuery( $sql, $fname );
813 if ( 0 == wfNumRows( $res ) ) { return; }
815 $sk = $wgUser->getSkin();
816 $s = $sk->beginImageHistoryList();
818 $line = wfFetchObject( $res );
819 $s .= $sk->imageHistoryLine( true, $line->img_timestamp,
820 $wgTitle->getText(), $line->img_user,
821 $line->img_user_text, $line->img_size, $line->img_description );
823 $sql = "SELECT oi_size,oi_description,oi_user," .
824 "oi_user_text,oi_timestamp,oi_archive_name FROM oldimage WHERE " .
825 "oi_name='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
826 "ORDER BY oi_timestamp DESC";
827 $res = wfQuery( $sql, $fname );
829 while ( $line = wfFetchObject( $res ) ) {
830 $s .= $sk->imageHistoryLine( false, $line->oi_timestamp,
831 $line->oi_archive_name, $line->oi_user,
832 $line->oi_user_text, $line->oi_size, $line->oi_description );
834 $s .= $sk->endImageHistoryList();
835 $wgOut->addHTML( $s );
838 function imageLinks()
840 global $wgUser, $wgOut, $wgTitle;
842 $wgOut->addHTML( "<h2>" . wfMsg( "imagelinks" ) . "</h2>\n" );
844 $sql = "SELECT il_from FROM imagelinks WHERE il_to='" .
845 wfStrencode( $wgTitle->getDBkey() ) . "'";
846 $res = wfQuery( $sql, "Article::imageLinks" );
848 if ( 0 == wfNumRows( $res ) ) {
849 $wgOut->addHtml( "<p>" . wfMsg( "nolinkstoimage" ) . "\n" );
850 return;
852 $wgOut->addHTML( "<p>" . wfMsg( "linkstoimage" ) . "\n<ul>" );
854 $sk = $wgUser->getSkin();
855 while ( $s = wfFetchObject( $res ) ) {
856 $name = $s->il_from;
857 $link = $sk->makeKnownLink( $name, "" );
858 $wgOut->addHTML( "<li>{$link}</li>\n" );
860 $wgOut->addHTML( "</ul>\n" );
863 # Add this page to my watchlist
865 function watch()
867 global $wgUser, $wgTitle, $wgOut, $wgLang;
868 global $wgDeferredUpdateList;
870 if ( 0 == $wgUser->getID() ) {
871 $wgOut->errorpage( "watchnologin", "watchnologintext" );
872 return;
874 if ( wfReadOnly() ) {
875 $wgOut->readOnlyPage();
876 return;
878 $wgUser->addWatch( $wgTitle );
880 $wgOut->setPagetitle( wfMsg( "addedwatch" ) );
881 $wgOut->setRobotpolicy( "noindex,follow" );
883 $sk = $wgUser->getSkin() ;
884 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
886 $text = str_replace( "$1", $link ,
887 wfMsg( "addedwatchtext" ) );
888 $wgOut->addHTML( $text );
890 $up = new UserUpdate();
891 array_push( $wgDeferredUpdateList, $up );
893 $wgOut->returnToMain( false );
896 function unwatch()
898 global $wgUser, $wgTitle, $wgOut, $wgLang;
899 global $wgDeferredUpdateList;
901 if ( 0 == $wgUser->getID() ) {
902 $wgOut->errorpage( "watchnologin", "watchnologintext" );
903 return;
905 if ( wfReadOnly() ) {
906 $wgOut->readOnlyPage();
907 return;
909 $wgUser->removeWatch( $wgTitle );
911 $wgOut->setPagetitle( wfMsg( "removedwatch" ) );
912 $wgOut->setRobotpolicy( "noindex,follow" );
914 $sk = $wgUser->getSkin() ;
915 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
917 $text = str_replace( "$1", $link ,
918 wfMsg( "removedwatchtext" ) );
919 $wgOut->addHTML( $text );
921 $up = new UserUpdate();
922 array_push( $wgDeferredUpdateList, $up );
924 $wgOut->returnToMain( false );
927 # This shares a lot of issues (and code) with Recent Changes
929 function history()
931 global $wgUser, $wgOut, $wgLang, $wgTitle, $offset, $limit;
933 # If page hasn't changed, client can cache this
935 $wgOut->checkLastModified( $this->getTimestamp() );
936 wfProfileIn( "Article::history" );
938 $wgOut->setPageTitle( $wgTitle->getPRefixedText() );
939 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
940 $wgOut->setArticleFlag( false );
941 $wgOut->setRobotpolicy( "noindex,nofollow" );
943 if( $wgTitle->getArticleID() == 0 ) {
944 $wgOut->addHTML( wfMsg( "nohistory" ) );
945 wfProfileOut();
946 return;
949 $offset = (int)$offset;
950 $limit = (int)$limit;
951 if( $limit == 0 ) $limit = 50;
952 $namespace = $wgTitle->getNamespace();
953 $title = $wgTitle->getText();
954 $sql = "SELECT old_id,old_user," .
955 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
956 "FROM old USE INDEX (name_title_timestamp) " .
957 "WHERE old_namespace={$namespace} AND " .
958 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
959 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
960 $res = wfQuery( $sql, "Article::history" );
962 $revs = wfNumRows( $res );
963 if( $wgTitle->getArticleID() == 0 ) {
964 $wgOut->addHTML( wfMsg( "nohistory" ) );
965 wfProfileOut();
966 return;
969 $sk = $wgUser->getSkin();
970 $numbar = wfViewPrevNext(
971 $offset, $limit,
972 $wgTitle->getPrefixedText(),
973 "action=history" );
974 $s = $numbar;
975 $s .= $sk->beginHistoryList();
977 if($offset == 0 )
978 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
979 $this->getUserText(), $namespace,
980 $title, 0, $this->getComment(),
981 ( $this->getMinorEdit() > 0 ) );
983 $revs = wfNumRows( $res );
984 while ( $line = wfFetchObject( $res ) ) {
985 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
986 $line->old_user_text, $namespace,
987 $title, $line->old_id,
988 $line->old_comment, ( $line->old_minor_edit > 0 ) );
990 $s .= $sk->endHistoryList();
991 $s .= $numbar;
992 $wgOut->addHTML( $s );
993 wfProfileOut();
996 function protect()
998 global $wgUser, $wgOut, $wgTitle;
1000 if ( ! $wgUser->isSysop() ) {
1001 $wgOut->sysopRequired();
1002 return;
1004 if ( wfReadOnly() ) {
1005 $wgOut->readOnlyPage();
1006 return;
1008 $id = $wgTitle->getArticleID();
1009 if ( 0 == $id ) {
1010 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
1011 return;
1013 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1014 "cur_restrictions='sysop' WHERE cur_id={$id}";
1015 wfQuery( $sql, "Article::protect" );
1017 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
1020 function unprotect()
1022 global $wgUser, $wgOut, $wgTitle;
1024 if ( ! $wgUser->isSysop() ) {
1025 $wgOut->sysopRequired();
1026 return;
1028 if ( wfReadOnly() ) {
1029 $wgOut->readOnlyPage();
1030 return;
1032 $id = $wgTitle->getArticleID();
1033 if ( 0 == $id ) {
1034 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
1035 return;
1037 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1038 "cur_restrictions='' WHERE cur_id={$id}";
1039 wfQuery( $sql, "Article::unprotect" );
1041 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
1044 function delete()
1046 global $wgUser, $wgOut, $wgTitle;
1047 global $wpConfirm, $wpReason, $image, $oldimage;
1049 # Anybody can delete old revisions of images; only sysops
1050 # can delete articles and current images
1052 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
1053 $wgOut->sysopRequired();
1054 return;
1056 if ( wfReadOnly() ) {
1057 $wgOut->readOnlyPage();
1058 return;
1061 # Better double-check that it hasn't been deleted yet!
1062 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
1063 if ( $image ) {
1064 if ( "" == trim( $image ) ) {
1065 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1066 return;
1068 $sub = str_replace( "$1", $image, wfMsg( "deletesub" ) );
1069 } else {
1071 if ( ( "" == trim( $wgTitle->getText() ) )
1072 or ( $wgTitle->getArticleId() == 0 ) ) {
1073 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1074 return;
1076 $sub = str_replace( "$1", $wgTitle->getPrefixedText(),
1077 wfMsg( "deletesub" ) );
1079 # determine whether this page has earlier revisions
1080 # and insert a warning if it does
1081 # we select the text because it might be useful below
1082 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
1083 $res=wfQuery($sql,$fname);
1084 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
1085 $skin=$wgUser->getSkin();
1086 $wgOut->addHTML("<B>".wfMsg("historywarning"));
1087 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
1090 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."'";
1091 $res=wfQuery($sql,$fname);
1092 if( ($s=wfFetchObject($res))) {
1094 # if this is a mini-text, we can paste part of it into the deletion reason
1096 #if this is empty, an earlier revision may contain "useful" text
1097 if($s->cur_text!="") {
1098 $text=$s->cur_text;
1099 } else {
1100 if($old) {
1101 $text=$old->old_text;
1102 $blanked=1;
1107 $length=strlen($text);
1109 # this should not happen, since it is not possible to store an empty, new
1110 # page. Let's insert a standard text in case it does, though
1111 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
1114 if($length < 500 && !$wpReason) {
1116 # comment field=255, let's grep the first 150 to have some user
1117 # space left
1118 $text=substr($text,0,150);
1119 # let's strip out newlines and HTML tags
1120 $text=preg_replace("/\"/","'",$text);
1121 $text=preg_replace("/\</","&lt;",$text);
1122 $text=preg_replace("/\>/","&gt;",$text);
1123 $text=preg_replace("/[\n\r]/","",$text);
1124 if(!$blanked) {
1125 $wpReason=wfMsg("excontent"). " '".$text;
1126 } else {
1127 $wpReason=wfMsg("exbeforeblank") . " '".$text;
1129 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
1130 $wpReason.="'";
1136 # Likewise, deleting old images doesn't require confirmation
1137 if ( $oldimage || 1 == $wpConfirm ) {
1138 $this->doDelete();
1139 return;
1142 $wgOut->setSubtitle( $sub );
1143 $wgOut->setRobotpolicy( "noindex,nofollow" );
1144 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1146 $t = $wgTitle->getPrefixedURL();
1147 $q = "action=delete";
1149 if ( $image ) {
1150 $q .= "&image={$image}";
1151 } else if ( $oldimage ) {
1152 $q .= "&oldimage={$oldimage}";
1153 } else {
1154 $q .= "&title={$t}";
1156 $formaction = wfEscapeHTML( wfLocalUrl( "", $q ) );
1157 $confirm = wfMsg( "confirm" );
1158 $check = wfMsg( "confirmcheck" );
1159 $delcom = wfMsg( "deletecomment" );
1161 $wgOut->addHTML( "
1162 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1163 <table border=0><tr><td align=right>
1164 {$delcom}:</td><td align=left>
1165 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
1166 </td></tr><tr><td>&nbsp;</td></tr>
1167 <tr><td align=right>
1168 <input type=checkbox name=\"wpConfirm\" value='1'>
1169 </td><td>{$check}</td>
1170 </tr><tr><td>&nbsp;</td><td>
1171 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1172 </td></tr></table></form>\n" );
1174 $wgOut->returnToMain( false );
1177 function doDelete()
1179 global $wgOut, $wgTitle, $wgUser, $wgLang;
1180 global $image, $oldimage, $wpReason;
1181 $fname = "Article::doDelete";
1183 if ( $image ) {
1184 $dest = wfImageDir( $image );
1185 $archive = wfImageDir( $image );
1186 if ( ! unlink( "{$dest}/{$image}" ) ) {
1187 $wgOut->fileDeleteError( "{$dest}/{$image}" );
1188 return;
1190 $sql = "DELETE FROM image WHERE img_name='" .
1191 wfStrencode( $image ) . "'";
1192 wfQuery( $sql, $fname );
1194 $sql = "SELECT oi_archive_name FROM oldimage WHERE oi_name='" .
1195 wfStrencode( $image ) . "'";
1196 $res = wfQuery( $sql, $fname );
1198 while ( $s = wfFetchObject( $res ) ) {
1199 $this->doDeleteOldImage( $s->oi_archive_name );
1201 $sql = "DELETE FROM oldimage WHERE oi_name='" .
1202 wfStrencode( $image ) . "'";
1203 wfQuery( $sql, $fname );
1205 # Image itself is now gone, and database is cleaned.
1206 # Now we remove the image description page.
1208 $nt = Title::newFromText( $wgLang->getNsText( Namespace::getImage() ) . ":" . $image );
1209 $this->doDeleteArticle( $nt );
1211 $deleted = $image;
1212 } else if ( $oldimage ) {
1213 $this->doDeleteOldImage( $oldimage );
1214 $sql = "DELETE FROM oldimage WHERE oi_archive_name='" .
1215 wfStrencode( $oldimage ) . "'";
1216 wfQuery( $sql, $fname );
1218 $deleted = $oldimage;
1219 } else {
1220 $this->doDeleteArticle( $wgTitle );
1221 $deleted = $wgTitle->getPrefixedText();
1223 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1224 $wgOut->setRobotpolicy( "noindex,nofollow" );
1226 $sk = $wgUser->getSkin();
1227 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1228 Namespace::getWikipedia() ) .
1229 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1231 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1232 $text = str_replace( "$2", $loglink, $text );
1234 $wgOut->addHTML( "<p>" . $text );
1235 $wgOut->returnToMain( false );
1238 function doDeleteOldImage( $oldimage )
1240 global $wgOut;
1242 $name = substr( $oldimage, 15 );
1243 $archive = wfImageArchiveDir( $name );
1244 if ( ! unlink( "{$archive}/{$oldimage}" ) ) {
1245 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
1249 function doDeleteArticle( $title )
1251 global $wgUser, $wgOut, $wgLang, $wpReason, $wgTitle, $wgDeferredUpdateList;
1253 $fname = "Article::doDeleteArticle";
1254 $ns = $title->getNamespace();
1255 $t = wfStrencode( $title->getDBkey() );
1256 $id = $title->getArticleID();
1258 if ( "" == $t ) {
1259 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1260 return;
1263 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1264 array_push( $wgDeferredUpdateList, $u );
1266 # Move article and history to the "archive" table
1267 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1268 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1269 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1270 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1271 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1272 wfQuery( $sql, $fname );
1274 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1275 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1276 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1277 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1278 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1279 wfQuery( $sql, $fname );
1281 # Now that it's safely backed up, delete it
1283 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1284 "cur_title='{$t}'";
1285 wfQuery( $sql, $fname );
1287 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1288 "old_title='{$t}'";
1289 wfQuery( $sql, $fname );
1291 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1292 "rc_title='{$t}'";
1293 wfQuery( $sql, $fname );
1295 # Finally, clean up the link tables
1297 if ( 0 != $id ) {
1298 $t = wfStrencode( $title->getPrefixedDBkey() );
1299 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1300 $res = wfQuery( $sql, $fname );
1302 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1303 $now = wfTimestampNow();
1304 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1305 $first = true;
1307 while ( $s = wfFetchObject( $res ) ) {
1308 $nt = Title::newFromDBkey( $s->l_from );
1309 $lid = $nt->getArticleID();
1311 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1312 $first = false;
1313 $sql .= "({$lid},'{$t}')";
1314 $sql2 .= "{$lid}";
1316 $sql2 .= ")";
1317 if ( ! $first ) {
1318 wfQuery( $sql, $fname );
1319 wfQuery( $sql2, $fname );
1321 wfFreeResult( $res );
1323 $sql = "DELETE FROM links WHERE l_to={$id}";
1324 wfQuery( $sql, $fname );
1326 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1327 wfQuery( $sql, $fname );
1329 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1330 wfQuery( $sql, $fname );
1332 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1333 wfQuery( $sql, $fname );
1336 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1337 $art = $title->getPrefixedText();
1338 $wpReason = wfCleanQueryVar( $wpReason );
1339 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1341 # Clear the cached article id so the interface doesn't act like we exist
1342 $wgTitle->resetArticleID( 0 );
1343 $wgTitle->mArticleID = 0;
1346 function revert()
1348 global $wgOut;
1349 global $oldimage;
1351 if ( strlen( $oldimage ) < 16 ) {
1352 $wgOut->unexpectedValueError( "oldimage", $oldimage );
1353 return;
1355 if ( wfReadOnly() ) {
1356 $wgOut->readOnlyPage();
1357 return;
1359 $name = substr( $oldimage, 15 );
1361 $dest = wfImageDir( $name );
1362 $archive = wfImageArchiveDir( $name );
1363 $curfile = "{$dest}/{$name}";
1365 if ( ! is_file( $curfile ) ) {
1366 $wgOut->fileNotFoundError( $curfile );
1367 return;
1369 $oldver = wfTimestampNow() . "!{$name}";
1370 $size = wfGetSQL( "oldimage", "oi_size", "oi_archive_name='" .
1371 wfStrencode( $oldimage ) . "'" );
1373 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
1374 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
1375 return;
1377 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
1378 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
1380 wfRecordUpload( $name, $oldver, $size, wfMsg( "reverted" ) );
1382 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1383 $wgOut->setRobotpolicy( "noindex,nofollow" );
1384 $wgOut->addHTML( wfMsg( "imagereverted" ) );
1385 $wgOut->returnToMain( false );
1388 function rollback()
1390 global $wgUser, $wgTitle, $wgLang, $wgOut, $from;
1392 if ( ! $wgUser->isSysop() ) {
1393 $wgOut->sysopRequired();
1394 return;
1397 # Replace all this user's current edits with the next one down
1398 $tt = wfStrencode( $wgTitle->getDBKey() );
1399 $n = $wgTitle->getNamespace();
1401 # Get the last editor
1402 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1403 $res = wfQuery( $sql );
1404 if( ($x = wfNumRows( $res )) != 1 ) {
1405 # Something wrong
1406 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1407 return;
1409 $s = wfFetchObject( $res );
1410 $ut = wfStrencode( $s->cur_user_text );
1411 $uid = $s->cur_user;
1412 $pid = $s->cur_id;
1414 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
1415 if( $from != $s->cur_user_text ) {
1416 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
1417 $wgOut->addWikiText( wfMsg( "alreadyrolled",
1418 htmlspecialchars( $wgTitle->getPrefixedText()),
1419 htmlspecialchars( $from ),
1420 htmlspecialchars( $s->cur_user_text ) ) );
1421 if($s->cur_comment != "") {
1422 $wgOut->addHTML(
1423 wfMsg("editcomment",
1424 htmlspecialchars( $s->cur_comment ) ) );
1426 return;
1429 # Get the last edit not by this guy
1430 $sql = "SELECT old_text,old_user,old_user_text
1431 FROM old USE INDEX (name_title_timestamp)
1432 WHERE old_namespace={$n} AND old_title='{$tt}'
1433 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1434 ORDER BY inverse_timestamp LIMIT 1";
1435 $res = wfQuery( $sql );
1436 if( wfNumRows( $res ) != 1 ) {
1437 # Something wrong
1438 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1439 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1440 return;
1442 $s = wfFetchObject( $res );
1444 # Save it!
1445 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1446 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1447 $wgOut->setRobotpolicy( "noindex,nofollow" );
1448 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1449 $this->updateArticle( $s->old_text, $newcomment, 1, $wgTitle->userIsWatching() );
1451 $wgOut->returnToMain( false );
1455 # Do standard deferred updates after page view
1457 /* private */ function viewUpdates()
1459 global $wgDeferredUpdateList, $wgTitle;
1461 if ( 0 != $this->getID() ) {
1462 $u = new ViewCountUpdate( $this->getID() );
1463 array_push( $wgDeferredUpdateList, $u );
1464 $u = new SiteStatsUpdate( 1, 0, 0 );
1465 array_push( $wgDeferredUpdateList, $u );
1467 $u = new UserTalkUpdate( 0, $wgTitle->getNamespace(),
1468 $wgTitle->getDBkey() );
1469 array_push( $wgDeferredUpdateList, $u );
1473 # Do standard deferred updates after page edit.
1474 # Every 1000th edit, prune the recent changes table.
1476 /* private */ function editUpdates( $text )
1478 global $wgDeferredUpdateList, $wgTitle;
1480 wfSeedRandom();
1481 if ( 0 == mt_rand( 0, 999 ) ) {
1482 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1483 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1484 wfQuery( $sql );
1486 $id = $this->getID();
1487 $title = $wgTitle->getPrefixedDBkey();
1488 $adj = $this->mCountAdjustment;
1490 if ( 0 != $id ) {
1491 $u = new LinksUpdate( $id, $title );
1492 array_push( $wgDeferredUpdateList, $u );
1493 $u = new SiteStatsUpdate( 0, 1, $adj );
1494 array_push( $wgDeferredUpdateList, $u );
1495 $u = new SearchUpdate( $id, $title, $text );
1496 array_push( $wgDeferredUpdateList, $u );
1498 $u = new UserTalkUpdate( 1, $wgTitle->getNamespace(),
1499 $wgTitle->getDBkey() );
1500 array_push( $wgDeferredUpdateList, $u );
1504 /* private */ function setOldSubtitle()
1506 global $wgLang, $wgOut;
1508 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1509 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1510 $wgOut->setSubtitle( "({$r})" );
1513 function blockedIPpage()
1515 global $wgOut, $wgUser, $wgLang;
1517 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1518 $wgOut->setRobotpolicy( "noindex,nofollow" );
1519 $wgOut->setArticleFlag( false );
1521 $id = $wgUser->blockedBy();
1522 $reason = $wgUser->blockedFor();
1524 $name = User::whoIs( $id );
1525 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1526 ":{$name}|{$name}]]";
1528 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1529 $text = str_replace( "$2", $reason, $text );
1530 $wgOut->addWikiText( $text );
1531 $wgOut->returnToMain( false );
1534 # This function is called right before saving the wikitext,
1535 # so we can do things like signatures and links-in-context.
1537 function preSaveTransform( $text )
1539 $s = "";
1540 while ( "" != $text ) {
1541 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1542 $s .= $this->pstPass2( $p[0] );
1544 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1545 else {
1546 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1547 $s .= "<nowiki>{$q[0]}</nowiki>";
1548 $text = $q[1];
1551 return rtrim( $s );
1554 /* private */ function pstPass2( $text )
1556 global $wgUser, $wgLang, $wgTitle, $wgLocaltimezone;
1558 # Signatures
1560 $n = $wgUser->getName();
1561 $k = $wgUser->getOption( "nickname" );
1562 if ( "" == $k ) { $k = $n; }
1563 if(isset($wgLocaltimezone)) {
1564 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1566 /* Note: this is an ugly timezone hack for the European wikis */
1567 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1568 " (" . date( "T" ) . ")";
1569 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1571 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1572 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1573 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1574 Namespace::getUser() ) . ":$n|$k]]", $text );
1576 # Context links: [[|name]] and [[name (context)|]]
1578 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1579 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1580 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1582 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1583 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1584 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1585 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1586 # [[ns:page (cont)|]]
1587 $context = "";
1588 $t = $wgTitle->getText();
1589 if ( preg_match( $conpat, $t, $m ) ) {
1590 $context = $m[2];
1592 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1593 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1594 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1596 if ( "" == $context ) {
1597 $text = preg_replace( $p2, "[[\\1]]", $text );
1598 } else {
1599 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1601 # Replace local image links with new [[image:]] style
1603 $text = preg_replace(
1604 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/upload\/" .
1605 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1606 "\\1[[image:\\3.\\4]]", $text );
1607 $text = preg_replace(
1608 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/images\/uploads\/" .
1609 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1610 "\\1[[image:\\3.\\4]]", $text );
1612 return $text;
1616 /* Caching functions */
1618 function tryFileCache() {
1619 if($this->isFileCacheable()) {
1620 if($this->isFileCacheGood()) {
1621 wfDebug( " tryFileCache() - about to load\n" );
1622 $this->loadFromFileCache();
1623 exit;
1624 } else {
1625 wfDebug( " tryFileCache() - starting buffer\n" );
1626 ob_start( array(&$this, 'saveToFileCache' ) );
1628 } else {
1629 wfDebug( " tryFileCache() - not cacheable\n" );
1633 function isFileCacheable() {
1634 global $wgUser, $wgTitle, $wgUseFileCache, $wgShowIPinHeader;
1635 global $action, $oldid, $diff, $redirect, $printable;
1636 return $wgUseFileCache
1637 and (!$wgShowIPinHeader)
1638 and ($wgUser->getId() == 0)
1639 and (!$wgUser->getNewtalk())
1640 and ($wgTitle->getNamespace != Namespace::getSpecial())
1641 and ($action == "view")
1642 and (!isset($oldid))
1643 and (!isset($diff))
1644 and (!isset($redirect))
1645 and (!isset($printable))
1646 and (!$this->mRedirectedFrom);
1650 function fileCacheName() {
1651 global $wgTitle, $wgFileCacheDirectory, $wgLang;
1652 if( !$this->mFileCache ) {
1653 $hash = md5( $key = $wgTitle->getDbkey() );
1654 if( $wgTitle->getNamespace() )
1655 $key = $wgLang->getNsText( $wgTitle->getNamespace() ) . ":" . $key;
1656 $key = str_replace( ".", "%2E", urlencode( $key ) );
1657 $hash1 = substr( $hash, 0, 1 );
1658 $hash2 = substr( $hash, 0, 2 );
1659 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$key}.html";
1660 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
1662 return $this->mFileCache;
1665 function isFileCacheGood() {
1666 global $wgUser, $wgCacheEpoch;
1667 if(!file_exists( $fn = $this->fileCacheName() ) ) return false;
1668 $cachetime = wfUnix2Timestamp( filemtime( $fn ) );
1669 $good = (( $this->mTouched <= $cachetime ) &&
1670 ($wgCacheEpoch <= $cachetime ));
1671 wfDebug(" isFileCacheGood() - cachetime $cachetime, touched {$this->mTouched} epoch {$wgCacheEpoch}, good $good\n");
1672 return $good;
1675 function loadFromFileCache() {
1676 global $wgUseGzip, $wgOut;
1677 wfDebug(" loadFromFileCache()\n");
1678 $filename=$this->fileCacheName();
1679 $filenamegz = "{$filename}.gz";
1680 $wgOut->sendCacheControl();
1681 if( $wgUseGzip
1682 && wfClientAcceptsGzip()
1683 && file_exists( $filenamegz)
1684 && ( filemtime( $filenamegz ) >= filemtime( $filename ) ) ) {
1685 wfDebug(" sending gzip\n");
1686 header( "Content-Encoding: gzip" );
1687 header( "Vary: Accept-Encoding" );
1688 $filename = $filenamegz;
1690 readfile( $filename );
1693 function saveToFileCache( $text ) {
1694 global $wgUseGzip, $wgCompressByDefault;
1695 if(strcmp($text,"") == 0) return "";
1697 wfDebug(" saveToFileCache()\n", false);
1698 $filename=$this->fileCacheName();
1699 $mydir2=substr($filename,0,strrpos($filename,"/")); # subdirectory level 2
1700 $mydir1=substr($mydir2,0,strrpos($mydir2,"/")); # subdirectory level 1
1701 if(!file_exists($mydir1)) { mkdir($mydir1,0775); } # create if necessary
1702 if(!file_exists($mydir2)) { mkdir($mydir2,0775); }
1704 $f = fopen( $filename, "w" );
1705 if($f) {
1706 $now = wfTimestampNow();
1707 fwrite( $f, str_replace( "</html>",
1708 "<!-- Cached $now -->\n</html>",
1709 $text ) );
1710 fclose( $f );
1711 if( $wgUseGzip and $wgCompressByDefault ) {
1712 $start = microtime();
1713 wfDebug(" saving gzip\n");
1714 $gzout = gzencode( str_replace( "</html>",
1715 "<!-- Cached/compressed $now -->\n</html>",
1716 $text ) );
1717 if( $gzout === false ) {
1718 wfDebug(" failed to gzip compress, sending plaintext\n");
1719 return $text;
1721 if( $f = fopen( "{$filename}.gz", "w" ) ) {
1722 fwrite( $f, $gzout );
1723 fclose( $f );
1724 $end = microtime();
1726 list($usec1, $sec1) = explode(" ",$start);
1727 list($usec2, $sec2) = explode(" ",$end);
1728 $interval = ((float)$usec2 + (float)$sec2) -
1729 ((float)$usec1 + (float)$sec1);
1730 wfDebug(" saved gzip in $interval\n");
1731 } else {
1732 wfDebug(" failed to write gzip, still sending\n" );
1734 if(wfClientAcceptsGzip()) {
1735 header( "Content-Encoding: gzip" );
1736 header( "Vary: Accept-Encoding" );
1737 wfDebug(" sending NEW gzip now...\n" );
1738 return $gzout;
1742 return $text;