fixed edit conflict bug
[lhc/web/wiklou.git] / includes / Article.php
1 <?
2 # Class representing a Wikipedia article and history.
3 # See design.doc for an overview.
4
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;
11
12 function Article() { $this->clear(); }
13
14 /* private */ function clear()
15 {
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";
22 }
23
24 /* static */ function newFromID( $newid )
25 {
26 global $wgOut, $wgTitle, $wgArticle;
27 $a = new Article();
28 $n = Article::nameOf( $newid );
29
30 $wgTitle = Title::newFromDBkey( $n );
31 $wgTitle->resetArticleID( $newid );
32
33 return $a;
34 }
35
36 /* static */ function nameOf( $id )
37 {
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; }
42
43 $s = wfFetchObject( $res );
44 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
45 return $n;
46 }
47
48 # Note that getContent/loadContent may follow redirects if
49 # not told otherwise, and so may cause a change to wgTitle.
50
51 function getContent( $noredir = false )
52 {
53 global $action,$wgTitle; # From query string
54 wfProfileIn( "Article::getContent" );
55
56 if ( 0 == $this->getID() ) {
57 if ( "edit" == $action ) {
58
59 global $wgTitle;
60 return ""; # was "newarticletext", now moved above the box)
61
62
63 }
64 wfProfileOut();
65 return wfMsg( "noarticletext" );
66 } else {
67 $this->loadContent( $noredir );
68 wfProfileOut();
69
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"
75 )
76 {
77 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
78 else {
79 return $this->mContent;
80 }
81 }
82 }
83
84 function loadContent( $noredir = false )
85 {
86 global $wgOut, $wgTitle;
87 global $oldid, $redirect; # From query
88
89 if ( $this->mContentLoaded ) return;
90 $fname = "Article::loadContent";
91
92 # Pre-fill content with error message so that if something
93 # fails we'll have something telling us what we intended.
94
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" ) );
99
100 if ( ! $oldid ) { # Retrieve current version
101 $id = $this->getID();
102 if ( 0 == $id ) return;
103
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; }
109
110 $s = wfFetchObject( $res );
111
112 # If we got a redirect, follow it (unless we've been told
113 # not to by either the function parameter or the query
114
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] );
120
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.
124
125 if ( $rt->getInterwiki() != "" ) {
126 $wgOut->redirect( $rt->getFullURL() ) ;
127 return;
128 }
129 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
130 $wgOut->redirect( wfLocalUrl(
131 $rt->getPrefixedURL() ) );
132 return;
133 }
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 );
139
140 if ( 0 != wfNumRows( $res ) ) {
141 $this->mRedirectedFrom = $wgTitle->getPrefixedText();
142 $wgTitle = $rt;
143 $s = wfFetchObject( $res );
144 }
145 }
146 }
147 }
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; }
161
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 );
168 }
169 $this->mContentLoaded = true;
170 }
171
172 function getID() { global $wgTitle; return $wgTitle->getArticleID(); }
173
174 function getCount()
175 {
176 if ( -1 == $this->mCounter ) {
177 $id = $this->getID();
178 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
179 }
180 return $this->mCounter;
181 }
182
183 # Would the given text make this article a "good" article (i.e.,
184 # suitable for including in the article count)?
185
186 function isCountable( $text )
187 {
188 global $wgTitle, $wgUseCommaCount;
189
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;
195 }
196
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.
199
200 /* private */ function loadLastEdit()
201 {
202 global $wgOut;
203 if ( -1 != $this->mUser ) return;
204
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" );
209
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;
217 }
218 }
219
220 function getTimestamp()
221 {
222 $this->loadLastEdit();
223 return $this->mTimestamp;
224 }
225
226 function getUser()
227 {
228 $this->loadLastEdit();
229 return $this->mUser;
230 }
231
232 function getUserText()
233 {
234 $this->loadLastEdit();
235 return $this->mUserText;
236 }
237
238 function getComment()
239 {
240 $this->loadLastEdit();
241 return $this->mComment;
242 }
243
244 function getMinorEdit()
245 {
246 $this->loadLastEdit();
247 return $this->mMinorEdit;
248 }
249
250 # This is the default action of the script: just view the page of
251 # the given title.
252
253 function view()
254 {
255 global $wgUser, $wgOut, $wgTitle, $wgLang;
256 global $oldid, $diff; # From query
257 global $wgLinkCache;
258 wfProfileIn( "Article::view" );
259
260 $wgOut->setArticleFlag( true );
261 $wgOut->setRobotpolicy( "index,follow" );
262
263 # If we got diff and oldid in the query, we want to see a
264 # diff page instead of the article.
265
266 if ( isset( $diff ) ) {
267 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
268 $de = new DifferenceEngine( $oldid, $diff );
269 $de->showDiffPage();
270 wfProfileOut();
271 return;
272 }
273 $text = $this->getContent(); # May change wgTitle!
274 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
275 $wgOut->setHTMLTitle( $wgTitle->getPrefixedText() .
276 " - " . wfMsg( "wikititlesuffix" ) );
277
278 # We're looking at an old revision
279
280 if ( $oldid ) {
281 $this->setOldSubtitle();
282 $wgOut->setRobotpolicy( "noindex,follow" );
283 }
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 );
290 }
291 $wgOut->checkLastModified( $this->mTouched );
292 $this->tryFileCache();
293 $wgLinkCache->preFill( $wgTitle );
294 $wgOut->addWikiText( $text );
295
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.
299
300 if ( Namespace::getImage() == $wgTitle->getNamespace() ) {
301 $this->imageHistory();
302 $this->imageLinks();
303 }
304 $this->viewUpdates();
305 wfProfileOut();
306 }
307
308 # This is the function that gets called for "action=edit".
309
310 function edit()
311 {
312 global $wgOut, $wgUser, $wgTitle;
313 global $wpTextbox1, $wpSummary, $wpSave, $wpPreview;
314 global $wpMinoredit, $wpEdittime, $wpTextbox2;
315
316 $fields = array( "wpTextbox1", "wpSummary", "wpTextbox2" );
317 wfCleanFormFields( $fields );
318
319 if ( ! $wgTitle->userCanEdit() ) {
320 $this->view();
321 return;
322 }
323 if ( $wgUser->isBlocked() ) {
324 $this->blockedIPpage();
325 return;
326 }
327 if ( wfReadOnly() ) {
328 if( isset( $wpSave ) or isset( $wpPreview ) ) {
329 $this->editForm( "preview" );
330 } else {
331 $wgOut->readOnlyPage();
332 }
333 return;
334 }
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" );
342 }
343 }
344
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.
350
351 function submit()
352 {
353 global $wpSave, $wpPreview;
354 if ( ! isset( $wpPreview ) ) { $wpSave = 1; }
355
356 $this->edit();
357 }
358
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.
364
365 function editForm( $formtype )
366 {
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;
373
374 $sk = $wgUser->getSkin();
375 $isConflict = false;
376 $wpTextbox1 = rtrim ( $wpTextbox1 ) ; # To avoid text getting longer on each preview
377
378 if(!$wgTitle->getArticleID()) { # new article
379
380 $wgOut->addWikiText(wfmsg("newarticletext"));
381
382 }
383
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.
388
389 if ( "save" == $formtype ) {
390 if ( $wgUser->isBlocked() ) {
391 $this->blockedIPpage();
392 return;
393 }
394 if ( wfReadOnly() ) {
395 $wgOut->readOnlyPage();
396 return;
397 }
398 # If article is new, insert it.
399
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;
409 }
410 $this->mCountAdjustment = $this->isCountable( $wpTextbox1 );
411 $this->insertNewArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
412 return;
413 }
414 # Article exists. Check for edit conflict.
415
416 $this->clear(); # Force reload of dates, etc.
417 if ( $this->getTimestamp() != $wpEdittime ) { $isConflict = true; }
418 $u = $wgUser->getID();
419
420 # Supress edit conflict with self
421
422 if ( ( 0 != $u ) && ( $this->getUser() == $u ) ) {
423 $isConflict = false;
424 }
425 if ( ! $isConflict ) {
426 # All's well: update the article here
427 $this->updateArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
428 return;
429 }
430 }
431 # First time through: get contents, set time for conflict
432 # checking, etc.
433
434 if ( "initial" == $formtype ) {
435 $wpEdittime = $this->getTimestamp();
436 $wpTextbox1 = $this->getContent(true);
437 $wpSummary = "";
438 }
439 $wgOut->setRobotpolicy( "noindex,nofollow" );
440 $wgOut->setArticleFlag( false );
441
442 if ( $isConflict ) {
443 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
444 wfMsg( "editconflict" ) );
445 $wgOut->setPageTitle( $s );
446 $wgOut->addHTML( wfMsg( "explainconflict" ) );
447
448 $wpTextbox2 = $wpTextbox1;
449 $wpTextbox1 = $this->getContent(true);
450 $wpEdittime = $this->getTimestamp();
451 } else {
452 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
453 wfMsg( "editing" ) );
454 $wgOut->setPageTitle( $s );
455 if ( $oldid ) {
456 $this->setOldSubtitle();
457 $wgOut->addHTML( wfMsg( "editingold" ) );
458 }
459 }
460
461 if( wfReadOnly() ) {
462 $wgOut->addHTML( "<strong>" .
463 wfMsg( "readonlywarning" ) .
464 "</strong>" );
465 }
466 if( $wgTitle->isProtected() ) {
467 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
468 "</strong><br />\n" );
469 }
470
471 $kblength = (int)(strlen( $wpTextbox1 ) / 1024);
472 if( $kblength > 29 ) {
473 $wgOut->addHTML( "<strong>" .
474 str_replace( '$1', $kblength , wfMsg( "longpagewarning" ) )
475 . "</strong>" );
476 }
477
478 $rows = $wgUser->getOption( "rows" );
479 $cols = $wgUser->getOption( "cols" );
480
481 $ew = $wgUser->getOption( "editwidth" );
482 if ( $ew ) $ew = " style=\"width:100%\"";
483 else $ew = "" ;
484
485 $q = "action=submit";
486 if ( "no" == $redirect ) { $q .= "&redirect=no"; }
487 $action = wfEscapeHTML( wfLocalUrl( $wgTitle->getPrefixedURL(), $q ) );
488
489 $summary = wfMsg( "summary" );
490 $minor = wfMsg( "minoredit" );
491 $watchthis = wfMsg ("watchthis");
492 $save = wfMsg( "savearticle" );
493 $prev = wfMsg( "showpreview" );
494
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" ) );
501
502 $wpTextbox1 = wfEscapeHTML( $wpTextbox1 );
503 $wpTextbox2 = wfEscapeHTML( $wpTextbox2 );
504 $wpSummary = wfEscapeHTML( $wpSummary );
505
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;
509
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;
514
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>";
519
520 } else {
521 $checkboxhtml="";
522 }
523
524
525 if ( "preview" == $formtype) {
526
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";
532 }
533 $previewtext = wfUnescapeHTML( $wpTextbox1 );
534
535 if($wgUser->getOption("previewontop")) {
536 $wgOut->addHTML($previewhead);
537 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) ."\n\n");
538 }
539 }
540 $wgOut->addHTML( "
541 <form id=\"editform\" name=\"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 ) .
546 "
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" );
556
557 if ( $isConflict ) {
558 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
559 DifferenceEngine::showDiff( $wpTextbox2, $wpTextbox1,
560 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
561
562 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
563 <textarea tabindex=6 name=\"wpTextbox2\" rows={$rows} cols={$cols} wrap=virtual>"
564 . $wgLang->recodeForEdit( $wpTextbox2 ) .
565 "
566 </textarea>" );
567 }
568 $wgOut->addHTML( "</form>\n" );
569 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
570 $wgOut->addHTML($previewhead);
571 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) );
572 }
573
574 }
575
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.
580
581 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
582 {
583 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
584 $fname = "Article::insertNewArticle";
585
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; }
591
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 );
604
605 $newid = wfInsertId();
606 $wgTitle->resetArticleID( $newid );
607
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();
622 }
623 }
624
625 $this->showArticle( $text, wfMsg( "newarticle" ) );
626 }
627
628 function updateArticle( $text, $summary, $minor, $watchthis )
629 {
630 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
631 global $wgDBtransactions;
632 $fname = "Article::updateArticle";
633
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
639 }
640 else { $redir = 0; }
641 $this->loadLastEdit();
642
643 $text = $this->preSaveTransform( $text );
644
645 # Update article, but only if changed.
646
647 if( $wgDBtransactions ) {
648 $sql = "BEGIN";
649 wfQuery( $sql );
650 }
651 $oldtext = $this->getContent( true );
652
653 if ( 0 != strcmp( $text, $oldtext ) ) {
654 $this->mCountAdjustment = $this->isCountable( $text )
655 - $this->isCountable( $oldtext );
656
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 );
670
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 );
681
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 );
692
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 );
698
699 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
700 "WHERE rc_cur_id=" . $this->getID();
701 wfQuery( $sql, $fname );
702 }
703 if( $wgDBtransactions ) {
704 $sql = "COMMIT";
705 wfQuery( $sql );
706 }
707
708 if ($watchthis) {
709 if (!$wgTitle->userIsWatching()) $this->watch();
710 } else {
711 if ( $wgTitle->userIsWatching() ) {
712 $this->unwatch();
713 }
714 }
715
716 $this->showArticle( $text, wfMsg( "updated" ) );
717 }
718
719 # After we've either updated or inserted the article, update
720 # the link tables and redirect to the new page.
721
722 function showArticle( $text, $subtitle )
723 {
724 global $wgOut, $wgTitle, $wgUser, $wgLinkCache;
725
726 $wgLinkCache = new LinkCache();
727 $wgOut->addWikiText( $text ); # Just to update links
728
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 ) );
735 }
736
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.
739
740 function imageHistory()
741 {
742 global $wgUser, $wgOut, $wgLang, $wgTitle;
743 $fname = "Article::imageHistory";
744
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 );
749
750 if ( 0 == wfNumRows( $res ) ) { return; }
751
752 $sk = $wgUser->getSkin();
753 $s = $sk->beginImageHistoryList();
754
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 );
759
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 );
765
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 );
770 }
771 $s .= $sk->endImageHistoryList();
772 $wgOut->addHTML( $s );
773 }
774
775 function imageLinks()
776 {
777 global $wgUser, $wgOut, $wgTitle;
778
779 $wgOut->addHTML( "<h2>" . wfMsg( "imagelinks" ) . "</h2>\n" );
780
781 $sql = "SELECT il_from FROM imagelinks WHERE il_to='" .
782 wfStrencode( $wgTitle->getDBkey() ) . "'";
783 $res = wfQuery( $sql, "Article::imageLinks" );
784
785 if ( 0 == wfNumRows( $res ) ) {
786 $wgOut->addHtml( "<p>" . wfMsg( "nolinkstoimage" ) . "\n" );
787 return;
788 }
789 $wgOut->addHTML( "<p>" . wfMsg( "linkstoimage" ) . "\n<ul>" );
790
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" );
796 }
797 $wgOut->addHTML( "</ul>\n" );
798 }
799
800 # Add this page to my watchlist
801
802 function watch()
803 {
804 global $wgUser, $wgTitle, $wgOut, $wgLang;
805 global $wgDeferredUpdateList;
806
807 if ( 0 == $wgUser->getID() ) {
808 $wgOut->errorpage( "watchnologin", "watchnologintext" );
809 return;
810 }
811 if ( wfReadOnly() ) {
812 $wgOut->readOnlyPage();
813 return;
814 }
815 $wgUser->addWatch( $wgTitle );
816
817 $wgOut->setPagetitle( wfMsg( "addedwatch" ) );
818 $wgOut->setRobotpolicy( "noindex,follow" );
819
820 $sk = $wgUser->getSkin() ;
821 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
822
823 $text = str_replace( "$1", $link ,
824 wfMsg( "addedwatchtext" ) );
825 $wgOut->addHTML( $text );
826
827 $up = new UserUpdate();
828 array_push( $wgDeferredUpdateList, $up );
829
830 $wgOut->returnToMain( false );
831 }
832
833 function unwatch()
834 {
835 global $wgUser, $wgTitle, $wgOut, $wgLang;
836 global $wgDeferredUpdateList;
837
838 if ( 0 == $wgUser->getID() ) {
839 $wgOut->errorpage( "watchnologin", "watchnologintext" );
840 return;
841 }
842 if ( wfReadOnly() ) {
843 $wgOut->readOnlyPage();
844 return;
845 }
846 $wgUser->removeWatch( $wgTitle );
847
848 $wgOut->setPagetitle( wfMsg( "removedwatch" ) );
849 $wgOut->setRobotpolicy( "noindex,follow" );
850
851 $sk = $wgUser->getSkin() ;
852 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
853
854 $text = str_replace( "$1", $link ,
855 wfMsg( "removedwatchtext" ) );
856 $wgOut->addHTML( $text );
857
858 $up = new UserUpdate();
859 array_push( $wgDeferredUpdateList, $up );
860
861 $wgOut->returnToMain( false );
862 }
863
864 # This shares a lot of issues (and code) with Recent Changes
865
866 function history()
867 {
868 global $wgUser, $wgOut, $wgLang, $wgTitle, $offset, $limit;
869
870 # If page hasn't changed, client can cache this
871
872 $wgOut->checkLastModified( $this->getTimestamp() );
873 wfProfileIn( "Article::history" );
874
875 $wgOut->setPageTitle( $wgTitle->getPRefixedText() );
876 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
877 $wgOut->setArticleFlag( false );
878 $wgOut->setRobotpolicy( "noindex,nofollow" );
879
880 if( $wgTitle->getArticleID() == 0 ) {
881 $wgOut->addHTML( wfMsg( "nohistory" ) );
882 wfProfileOut();
883 return;
884 }
885
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" );
898
899 $revs = wfNumRows( $res );
900 if( $wgTitle->getArticleID() == 0 ) {
901 $wgOut->addHTML( wfMsg( "nohistory" ) );
902 wfProfileOut();
903 return;
904 }
905
906 $sk = $wgUser->getSkin();
907 $numbar = wfViewPrevNext(
908 $offset, $limit,
909 $wgTitle->getPrefixedText(),
910 "action=history" );
911 $s = $numbar;
912 $s .= $sk->beginHistoryList();
913
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 ) );
919
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 ) );
926 }
927 $s .= $sk->endHistoryList();
928 $s .= $numbar;
929 $wgOut->addHTML( $s );
930 wfProfileOut();
931 }
932
933 function protect()
934 {
935 global $wgUser, $wgOut, $wgTitle;
936
937 if ( ! $wgUser->isSysop() ) {
938 $wgOut->sysopRequired();
939 return;
940 }
941 if ( wfReadOnly() ) {
942 $wgOut->readOnlyPage();
943 return;
944 }
945 $id = $wgTitle->getArticleID();
946 if ( 0 == $id ) {
947 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
948 return;
949 }
950 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
951 "cur_restrictions='sysop' WHERE cur_id={$id}";
952 wfQuery( $sql, "Article::protect" );
953
954 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
955 }
956
957 function unprotect()
958 {
959 global $wgUser, $wgOut, $wgTitle;
960
961 if ( ! $wgUser->isSysop() ) {
962 $wgOut->sysopRequired();
963 return;
964 }
965 if ( wfReadOnly() ) {
966 $wgOut->readOnlyPage();
967 return;
968 }
969 $id = $wgTitle->getArticleID();
970 if ( 0 == $id ) {
971 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
972 return;
973 }
974 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
975 "cur_restrictions='' WHERE cur_id={$id}";
976 wfQuery( $sql, "Article::unprotect" );
977
978 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
979 }
980
981 function delete()
982 {
983 global $wgUser, $wgOut, $wgTitle;
984 global $wpConfirm, $wpReason, $image, $oldimage;
985
986 # Anybody can delete old revisions of images; only sysops
987 # can delete articles and current images
988
989 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
990 $wgOut->sysopRequired();
991 return;
992 }
993 if ( wfReadOnly() ) {
994 $wgOut->readOnlyPage();
995 return;
996 }
997
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;
1004 }
1005 $sub = str_replace( "$1", $image, wfMsg( "deletesub" ) );
1006 } else {
1007
1008 if ( ( "" == trim( $wgTitle->getText() ) )
1009 or ( $wgTitle->getArticleId() == 0 ) ) {
1010 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1011 return;
1012 }
1013 $sub = str_replace( "$1", $wgTitle->getPrefixedText(),
1014 wfMsg( "deletesub" ) );
1015
1016 # determine whether this page has earlier revisions
1017 # and insert a warning if it does
1018 # we select the text because it might be useful below
1019 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
1020 $res=wfQuery($sql,$fname);
1021 if( $old=wfFetchObject($res)) {
1022 $skin=$wgUser->getSkin();
1023 $wgOut->addHTML("<B>".wfMsg("historywarning"));
1024 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
1025 }
1026
1027 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."'";
1028 $res=wfQuery($sql,$fname);
1029 if( ($s=wfFetchObject($res))) {
1030
1031 # if this is a mini-text, we can paste part of it into the deletion reason
1032
1033 #if this is empty, an earlier revision may contain "useful" text
1034 if($s->cur_text!="") {
1035 $text=$s->cur_text;
1036 } else {
1037 if($old) {
1038 $text=$old->old_text;
1039 $blanked=1;
1040 }
1041
1042 }
1043
1044 $length=strlen($text);
1045
1046 # this should not happen, since it is not possible to store an empty, new
1047 # page. Let's insert a standard text in case it does, though
1048 if($length==0) { $wpreason=wfmsg("exblank");}
1049
1050
1051 if($length < 500) {
1052
1053 # comment field=255, let's grep the first 150 to have some user
1054 # space left
1055 $text=substr($text,0,150);
1056 # let's strip out newlines and HTML tags
1057 $text=preg_replace("/\"/","'",$text);
1058 $text=preg_replace("/\</","&lt;",$text);
1059 $text=preg_replace("/\>/","&gt;",$text);
1060 $text=preg_replace("/[\n\r]/","",$text);
1061 if(!$blanked) {
1062 $wpReason=wfMsg("excontent"). " '".$text;
1063 } else {
1064 $wpReason=wfMsg("exbeforeblank") . " '".$text;
1065 }
1066 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
1067 $wpReason.="'";
1068 }
1069 }
1070
1071 }
1072
1073 # Likewise, deleting old images doesn't require confirmation
1074 if ( $oldimage || 1 == $wpConfirm ) {
1075 $this->doDelete();
1076 return;
1077 }
1078
1079 $wgOut->setSubtitle( $sub );
1080 $wgOut->setRobotpolicy( "noindex,nofollow" );
1081 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1082
1083 $t = $wgTitle->getPrefixedURL();
1084 $q = "action=delete";
1085
1086 if ( $image ) {
1087 $q .= "&image={$image}";
1088 } else if ( $oldimage ) {
1089 $q .= "&oldimage={$oldimage}";
1090 } else {
1091 $q .= "&title={$t}";
1092 }
1093 $formaction = wfEscapeHTML( wfLocalUrl( "", $q ) );
1094 $confirm = wfMsg( "confirm" );
1095 $check = wfMsg( "confirmcheck" );
1096 $delcom = wfMsg( "deletecomment" );
1097
1098 $wgOut->addHTML( "
1099 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1100 <table border=0><tr><td align=right>
1101 {$delcom}:</td><td align=left>
1102 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
1103 </td></tr><tr><td>&nbsp;</td></tr>
1104 <tr><td align=right>
1105 <input type=checkbox name=\"wpConfirm\" value='1'>
1106 </td><td>{$check}</td>
1107 </tr><tr><td>&nbsp;</td><td>
1108 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1109 </td></tr></table></form>\n" );
1110
1111 $wgOut->returnToMain( false );
1112 }
1113
1114 function doDelete()
1115 {
1116 global $wgOut, $wgTitle, $wgUser, $wgLang;
1117 global $image, $oldimage, $wpReason;
1118 $fname = "Article::doDelete";
1119
1120 if ( $image ) {
1121 $dest = wfImageDir( $image );
1122 $archive = wfImageDir( $image );
1123 if ( ! unlink( "{$dest}/{$image}" ) ) {
1124 $wgOut->fileDeleteError( "{$dest}/{$image}" );
1125 return;
1126 }
1127 $sql = "DELETE FROM image WHERE img_name='" .
1128 wfStrencode( $image ) . "'";
1129 wfQuery( $sql, $fname );
1130
1131 $sql = "SELECT oi_archive_name FROM oldimage WHERE oi_name='" .
1132 wfStrencode( $image ) . "'";
1133 $res = wfQuery( $sql, $fname );
1134
1135 while ( $s = wfFetchObject( $res ) ) {
1136 $this->doDeleteOldImage( $s->oi_archive_name );
1137 }
1138 $sql = "DELETE FROM oldimage WHERE oi_name='" .
1139 wfStrencode( $image ) . "'";
1140 wfQuery( $sql, $fname );
1141
1142 # Image itself is now gone, and database is cleaned.
1143 # Now we remove the image description page.
1144
1145 $nt = Title::newFromText( $wgLang->getNsText( Namespace::getImage() ) . ":" . $image );
1146 $this->doDeleteArticle( $nt );
1147
1148 $deleted = $image;
1149 } else if ( $oldimage ) {
1150 $this->doDeleteOldImage( $oldimage );
1151 $sql = "DELETE FROM oldimage WHERE oi_archive_name='" .
1152 wfStrencode( $oldimage ) . "'";
1153 wfQuery( $sql, $fname );
1154
1155 $deleted = $oldimage;
1156 } else {
1157 $this->doDeleteArticle( $wgTitle );
1158 $deleted = $wgTitle->getPrefixedText();
1159 }
1160 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1161 $wgOut->setRobotpolicy( "noindex,nofollow" );
1162
1163 $sk = $wgUser->getSkin();
1164 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1165 Namespace::getWikipedia() ) .
1166 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1167
1168 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1169 $text = str_replace( "$2", $loglink, $text );
1170
1171 $wgOut->addHTML( "<p>" . $text );
1172 $wgOut->returnToMain( false );
1173 }
1174
1175 function doDeleteOldImage( $oldimage )
1176 {
1177 global $wgOut;
1178
1179 $name = substr( $oldimage, 15 );
1180 $archive = wfImageArchiveDir( $name );
1181 if ( ! unlink( "{$archive}/{$oldimage}" ) ) {
1182 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
1183 }
1184 }
1185
1186 function doDeleteArticle( $title )
1187 {
1188 global $wgUser, $wgOut, $wgLang, $wpReason, $wgTitle, $wgDeferredUpdateList;
1189
1190 $fname = "Article::doDeleteArticle";
1191 $ns = $title->getNamespace();
1192 $t = wfStrencode( $title->getDBkey() );
1193 $id = $title->getArticleID();
1194
1195 if ( "" == $t ) {
1196 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1197 return;
1198 }
1199
1200 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1201 array_push( $wgDeferredUpdateList, $u );
1202
1203 # Move article and history to the "archive" table
1204 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1205 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1206 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1207 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1208 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1209 wfQuery( $sql, $fname );
1210
1211 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1212 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1213 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1214 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1215 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1216 wfQuery( $sql, $fname );
1217
1218 # Now that it's safely backed up, delete it
1219
1220 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1221 "cur_title='{$t}'";
1222 wfQuery( $sql, $fname );
1223
1224 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1225 "old_title='{$t}'";
1226 wfQuery( $sql, $fname );
1227
1228 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1229 "rc_title='{$t}'";
1230 wfQuery( $sql, $fname );
1231
1232 # Finally, clean up the link tables
1233
1234 if ( 0 != $id ) {
1235 $t = wfStrencode( $title->getPrefixedDBkey() );
1236 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1237 $res = wfQuery( $sql, $fname );
1238
1239 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1240 $now = wfTimestampNow();
1241 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1242 $first = true;
1243
1244 while ( $s = wfFetchObject( $res ) ) {
1245 $nt = Title::newFromDBkey( $s->l_from );
1246 $lid = $nt->getArticleID();
1247
1248 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1249 $first = false;
1250 $sql .= "({$lid},'{$t}')";
1251 $sql2 .= "{$lid}";
1252 }
1253 $sql2 .= ")";
1254 if ( ! $first ) {
1255 wfQuery( $sql, $fname );
1256 wfQuery( $sql2, $fname );
1257 }
1258 wfFreeResult( $res );
1259
1260 $sql = "DELETE FROM links WHERE l_to={$id}";
1261 wfQuery( $sql, $fname );
1262
1263 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1264 wfQuery( $sql, $fname );
1265
1266 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1267 wfQuery( $sql, $fname );
1268
1269 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1270 wfQuery( $sql, $fname );
1271 }
1272
1273 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1274 $art = $title->getPrefixedText();
1275 $wpReason = wfCleanQueryVar( $wpReason );
1276 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1277
1278 # Clear the cached article id so the interface doesn't act like we exist
1279 $wgTitle->resetArticleID( 0 );
1280 $wgTitle->mArticleID = 0;
1281 }
1282
1283 function revert()
1284 {
1285 global $wgOut;
1286 global $oldimage;
1287
1288 if ( strlen( $oldimage ) < 16 ) {
1289 $wgOut->unexpectedValueError( "oldimage", $oldimage );
1290 return;
1291 }
1292 if ( wfReadOnly() ) {
1293 $wgOut->readOnlyPage();
1294 return;
1295 }
1296 $name = substr( $oldimage, 15 );
1297
1298 $dest = wfImageDir( $name );
1299 $archive = wfImageArchiveDir( $name );
1300 $curfile = "{$dest}/{$name}";
1301
1302 if ( ! is_file( $curfile ) ) {
1303 $wgOut->fileNotFoundError( $curfile );
1304 return;
1305 }
1306 $oldver = wfTimestampNow() . "!{$name}";
1307 $size = wfGetSQL( "oldimage", "oi_size", "oi_archive_name='" .
1308 wfStrencode( $oldimage ) . "'" );
1309
1310 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
1311 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
1312 return;
1313 }
1314 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
1315 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
1316 }
1317 wfRecordUpload( $name, $oldver, $size, wfMsg( "reverted" ) );
1318
1319 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1320 $wgOut->setRobotpolicy( "noindex,nofollow" );
1321 $wgOut->addHTML( wfMsg( "imagereverted" ) );
1322 $wgOut->returnToMain( false );
1323 }
1324
1325 function rollback()
1326 {
1327 global $wgUser, $wgTitle, $wgLang, $wgOut, $from;
1328
1329 if ( ! $wgUser->isSysop() ) {
1330 $wgOut->sysopRequired();
1331 return;
1332 }
1333
1334 # Replace all this user's current edits with the next one down
1335 $tt = wfStrencode( $wgTitle->getDBKey() );
1336 $n = $wgTitle->getNamespace();
1337
1338 # Get the last editor
1339 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1340 $res = wfQuery( $sql );
1341 if( ($x = wfNumRows( $res )) != 1 ) {
1342 # Something wrong
1343 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1344 return;
1345 }
1346 $s = wfFetchObject( $res );
1347 $ut = wfStrencode( $s->cur_user_text );
1348 $uid = $s->cur_user;
1349 $pid = $s->cur_id;
1350
1351 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
1352 if( $from != $s->cur_user_text ) {
1353 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
1354 $wgOut->addWikiText( wfMsg( "alreadyrolled",
1355 htmlspecialchars( $wgTitle->getPrefixedText()),
1356 htmlspecialchars( $from ),
1357 htmlspecialchars( $s->cur_user_text ) ) );
1358 if($s->cur_comment != "") {
1359 $wgOut->addHTML(
1360 wfMsg("editcomment",
1361 htmlspecialchars( $s->cur_comment ) ) );
1362 }
1363 return;
1364 }
1365
1366 # Get the last edit not by this guy
1367 $sql = "SELECT old_text,old_user,old_user_text
1368 FROM old USE INDEX (name_title_timestamp)
1369 WHERE old_namespace={$n} AND old_title='{$tt}'
1370 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1371 ORDER BY inverse_timestamp LIMIT 1";
1372 $res = wfQuery( $sql );
1373 if( wfNumRows( $res ) != 1 ) {
1374 # Something wrong
1375 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1376 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1377 return;
1378 }
1379 $s = wfFetchObject( $res );
1380
1381 # Save it!
1382 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1383 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1384 $wgOut->setRobotpolicy( "noindex,nofollow" );
1385 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1386 $this->updateArticle( $s->old_text, $newcomment, 1, $wgTitle->userIsWatching() );
1387
1388 $wgOut->returnToMain( false );
1389 }
1390
1391
1392 # Do standard deferred updates after page view
1393
1394 /* private */ function viewUpdates()
1395 {
1396 global $wgDeferredUpdateList, $wgTitle;
1397
1398 if ( 0 != $this->getID() ) {
1399 $u = new ViewCountUpdate( $this->getID() );
1400 array_push( $wgDeferredUpdateList, $u );
1401 $u = new SiteStatsUpdate( 1, 0, 0 );
1402 array_push( $wgDeferredUpdateList, $u );
1403
1404 $u = new UserTalkUpdate( 0, $wgTitle->getNamespace(),
1405 $wgTitle->getDBkey() );
1406 array_push( $wgDeferredUpdateList, $u );
1407 }
1408 }
1409
1410 # Do standard deferred updates after page edit.
1411 # Every 1000th edit, prune the recent changes table.
1412
1413 /* private */ function editUpdates( $text )
1414 {
1415 global $wgDeferredUpdateList, $wgTitle;
1416
1417 wfSeedRandom();
1418 if ( 0 == mt_rand( 0, 999 ) ) {
1419 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1420 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1421 wfQuery( $sql );
1422 }
1423 $id = $this->getID();
1424 $title = $wgTitle->getPrefixedDBkey();
1425 $adj = $this->mCountAdjustment;
1426
1427 if ( 0 != $id ) {
1428 $u = new LinksUpdate( $id, $title );
1429 array_push( $wgDeferredUpdateList, $u );
1430 $u = new SiteStatsUpdate( 0, 1, $adj );
1431 array_push( $wgDeferredUpdateList, $u );
1432 $u = new SearchUpdate( $id, $title, $text );
1433 array_push( $wgDeferredUpdateList, $u );
1434
1435 $u = new UserTalkUpdate( 1, $wgTitle->getNamespace(),
1436 $wgTitle->getDBkey() );
1437 array_push( $wgDeferredUpdateList, $u );
1438 }
1439 }
1440
1441 /* private */ function setOldSubtitle()
1442 {
1443 global $wgLang, $wgOut;
1444
1445 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1446 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1447 $wgOut->setSubtitle( "({$r})" );
1448 }
1449
1450 function blockedIPpage()
1451 {
1452 global $wgOut, $wgUser, $wgLang;
1453
1454 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1455 $wgOut->setRobotpolicy( "noindex,nofollow" );
1456 $wgOut->setArticleFlag( false );
1457
1458 $id = $wgUser->blockedBy();
1459 $reason = $wgUser->blockedFor();
1460
1461 $name = User::whoIs( $id );
1462 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1463 ":{$name}|{$name}]]";
1464
1465 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1466 $text = str_replace( "$2", $reason, $text );
1467 $wgOut->addWikiText( $text );
1468 $wgOut->returnToMain( false );
1469 }
1470
1471 # This function is called right before saving the wikitext,
1472 # so we can do things like signatures and links-in-context.
1473
1474 function preSaveTransform( $text )
1475 {
1476 $s = "";
1477 while ( "" != $text ) {
1478 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1479 $s .= $this->pstPass2( $p[0] );
1480
1481 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1482 else {
1483 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1484 $s .= "<nowiki>{$q[0]}</nowiki>";
1485 $text = $q[1];
1486 }
1487 }
1488 return rtrim( $s );
1489 }
1490
1491 /* private */ function pstPass2( $text )
1492 {
1493 global $wgUser, $wgLang, $wgTitle, $wgLocaltimezone;
1494
1495 # Signatures
1496 #
1497 $n = $wgUser->getName();
1498 $k = $wgUser->getOption( "nickname" );
1499 if ( "" == $k ) { $k = $n; }
1500 if(isset($wgLocaltimezone)) {
1501 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1502 }
1503 $d = $wgLang->timeanddate( wfTimestampNow(), false ) .
1504 " (" . date( "T" ) . ")";
1505 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1506
1507 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1508 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1509 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1510 Namespace::getUser() ) . ":$n|$k]]", $text );
1511
1512 # Context links: [[|name]] and [[name (context)|]]
1513 #
1514 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1515 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1516 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1517
1518 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1519 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1520 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1521 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1522 # [[ns:page (cont)|]]
1523 $context = "";
1524 $t = $wgTitle->getText();
1525 if ( preg_match( $conpat, $t, $m ) ) {
1526 $context = $m[2];
1527 }
1528 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1529 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1530 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1531
1532 if ( "" == $context ) {
1533 $text = preg_replace( $p2, "[[\\1]]", $text );
1534 } else {
1535 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1536 }
1537 # Replace local image links with new [[image:]] style
1538
1539 $text = preg_replace(
1540 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/upload\/" .
1541 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1542 "\\1[[image:\\3.\\4]]", $text );
1543 $text = preg_replace(
1544 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/images\/uploads\/" .
1545 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1546 "\\1[[image:\\3.\\4]]", $text );
1547
1548 return $text;
1549 }
1550
1551
1552 /* Caching functions */
1553
1554 function tryFileCache() {
1555 if($this->isFileCacheable()) {
1556 if($this->isFileCacheGood()) {
1557 wfDebug( " tryFileCache() - about to load\n" );
1558 $this->loadFromFileCache();
1559 exit;
1560 } else {
1561 wfDebug( " tryFileCache() - starting buffer\n" );
1562 ob_start( array(&$this, 'saveToFileCache' ) );
1563 }
1564 } else {
1565 wfDebug( " tryFileCache() - not cacheable\n" );
1566 }
1567 }
1568
1569 function isFileCacheable() {
1570 global $wgUser, $wgTitle, $wgUseFileCache, $wgShowIPinHeader;
1571 global $action, $oldid, $diff, $redirect, $printable;
1572 return $wgUseFileCache
1573 and (!$wgShowIPinHeader)
1574 and ($wgUser->getId() == 0)
1575 and (!$wgUser->getNewtalk())
1576 and ($wgTitle->getNamespace != Namespace::getSpecial())
1577 and ($action == "view")
1578 and (!isset($oldid))
1579 and (!isset($diff))
1580 and (!isset($redirect))
1581 and (!isset($printable))
1582 and (!$this->mRedirectedFrom);
1583
1584 }
1585
1586 function fileCacheName() {
1587 global $wgTitle, $wgFileCacheDirectory, $wgLang;
1588 if( !$this->mFileCache ) {
1589 $hash = md5( $key = $wgTitle->getDbkey() );
1590 if( $wgTitle->getNamespace() )
1591 $key = $wgLang->getNsText( $wgTitle->getNamespace() ) . ":" . $key;
1592 $key = str_replace( ".", "%2E", urlencode( $key ) );
1593 $hash1 = substr( $hash, 0, 1 );
1594 $hash2 = substr( $hash, 0, 2 );
1595 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$key}.html";
1596 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
1597 }
1598 return $this->mFileCache;
1599 }
1600
1601 function isFileCacheGood() {
1602 global $wgUser, $wgCacheEpoch;
1603 if(!file_exists( $fn = $this->fileCacheName() ) ) return false;
1604 $cachetime = wfUnix2Timestamp( filemtime( $fn ) );
1605 $good = ( $this->mTouched <= $cachetime ) &&
1606 ($wgCacheEpoch <= $cachetime );
1607 wfDebug(" isFileCacheGood() - cachetime $cachetime, touched {$this->mTouched} epoch {$wgCacheEpoch}, good $good\n");
1608 return $good;
1609 }
1610
1611 function loadFromFileCache() {
1612 global $wgUseGzip;
1613 wfDebug(" loadFromFileCache()\n");
1614 $filename=$this->fileCacheName();
1615 $filenamegz = "{$filename}.gz";
1616 if( $wgUseGzip
1617 && wfClientAcceptsGzip()
1618 && file_exists( $filenamegz)
1619 && ( filemtime( $filenamegz ) >= filemtime( $filename ) ) ) {
1620 wfDebug(" sending gzip\n");
1621 header( "Content-Encoding: gzip" );
1622 header( "Vary: Accept-Encoding" );
1623 $filename = $filenamegz;
1624 }
1625 readfile( $filename );
1626 }
1627
1628 function saveToFileCache( $text ) {
1629 global $wgUseGzip, $wgCompressByDefault;
1630
1631 wfDebug(" saveToFileCache()\n");
1632 $filename=$this->fileCacheName();
1633 $mydir2=substr($filename,0,strrpos($filename,"/")); # subdirectory level 2
1634 $mydir1=substr($mydir2,0,strrpos($mydir2,"/")); # subdirectory level 1
1635 if(!file_exists($mydir1)) { mkdir($mydir1,0777); } # create if necessary
1636 if(!file_exists($mydir2)) { mkdir($mydir2,0777); }
1637 $f = fopen( $filename, "w" );
1638 if($f) {
1639 $now = wfTimestampNow();
1640 fwrite( $f, str_replace( "</html>",
1641 "<!-- Cached $now -->\n</html>",
1642 $text ) );
1643 fclose( $f );
1644 if( $wgUseGzip and $wgCompressByDefault ) {
1645 $start = microtime();
1646 wfDebug(" saving gzip\n");
1647 $gzout = gzencode( str_replace( "</html>",
1648 "<!-- Cached/compressed $now -->\n</html>",
1649 $text ) );
1650 if( $gzout === false ) {
1651 wfDebug(" failed to gzip compress, sending plaintext\n");
1652 return $text;
1653 }
1654 if( $f = fopen( "{$filename}.gz", "w" ) ) {
1655 fwrite( $f, $gzout );
1656 fclose( $f );
1657 $end = microtime();
1658
1659 list($usec1, $sec1) = explode(" ",$start);
1660 list($usec2, $sec2) = explode(" ",$end);
1661 $interval = ((float)$usec2 + (float)$sec2) -
1662 ((float)$usec1 + (float)$sec1);
1663 wfDebug(" saved gzip in $interval\n");
1664 } else {
1665 wfDebug(" failed to write gzip, still sending\n" );
1666 }
1667 header( "Content-Encoding: gzip" );
1668 header( "Vary: Accept-Encoding" );
1669 return $gzout;
1670 }
1671 }
1672 return $text;
1673 }
1674
1675 }
1676
1677 ?>