fixed edit conflict bug with sections
[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,$section,$count,$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 if($action=="edit") {
80 if($section!="") {
81 if($section=="new") { return ""; }
82
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]);
90 }
91 }
92 }
93 return $this->mContent;
94 }
95 }
96 }
97
98 function loadContent( $noredir = false )
99 {
100 global $wgOut, $wgTitle;
101 global $oldid, $redirect; # From query
102
103 if ( $this->mContentLoaded ) return;
104 $fname = "Article::loadContent";
105
106 # Pre-fill content with error message so that if something
107 # fails we'll have something telling us what we intended.
108
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" ) );
113
114 if ( ! $oldid ) { # Retrieve current version
115 $id = $this->getID();
116 if ( 0 == $id ) return;
117
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; }
123
124 $s = wfFetchObject( $res );
125
126 # If we got a redirect, follow it (unless we've been told
127 # not to by either the function parameter or the query
128
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] );
134
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.
138
139 if ( $rt->getInterwiki() != "" ) {
140 $wgOut->redirect( $rt->getFullURL() ) ;
141 return;
142 }
143 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
144 $wgOut->redirect( wfLocalUrl(
145 $rt->getPrefixedURL() ) );
146 return;
147 }
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 );
153
154 if ( 0 != wfNumRows( $res ) ) {
155 $this->mRedirectedFrom = $wgTitle->getPrefixedText();
156 $wgTitle = $rt;
157 $s = wfFetchObject( $res );
158 }
159 }
160 }
161 }
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; }
175
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 );
182 }
183 $this->mContentLoaded = true;
184 }
185
186 function getID() { global $wgTitle; return $wgTitle->getArticleID(); }
187
188 function getCount()
189 {
190 if ( -1 == $this->mCounter ) {
191 $id = $this->getID();
192 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
193 }
194 return $this->mCounter;
195 }
196
197 # Would the given text make this article a "good" article (i.e.,
198 # suitable for including in the article count)?
199
200 function isCountable( $text )
201 {
202 global $wgTitle, $wgUseCommaCount;
203
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;
209 }
210
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.
213
214 /* private */ function loadLastEdit()
215 {
216 global $wgOut;
217 if ( -1 != $this->mUser ) return;
218
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" );
223
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;
231 }
232 }
233
234 function getTimestamp()
235 {
236 $this->loadLastEdit();
237 return $this->mTimestamp;
238 }
239
240 function getUser()
241 {
242 $this->loadLastEdit();
243 return $this->mUser;
244 }
245
246 function getUserText()
247 {
248 $this->loadLastEdit();
249 return $this->mUserText;
250 }
251
252 function getComment()
253 {
254 $this->loadLastEdit();
255 return $this->mComment;
256 }
257
258 function getMinorEdit()
259 {
260 $this->loadLastEdit();
261 return $this->mMinorEdit;
262 }
263
264 # This is the default action of the script: just view the page of
265 # the given title.
266
267 function view()
268 {
269 global $wgUser, $wgOut, $wgTitle, $wgLang;
270 global $oldid, $diff; # From query
271 global $wgLinkCache;
272 wfProfileIn( "Article::view" );
273
274 $wgOut->setArticleFlag( true );
275 $wgOut->setRobotpolicy( "index,follow" );
276
277 # If we got diff and oldid in the query, we want to see a
278 # diff page instead of the article.
279
280 if ( isset( $diff ) ) {
281 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
282 $de = new DifferenceEngine( $oldid, $diff );
283 $de->showDiffPage();
284 wfProfileOut();
285 return;
286 }
287 $text = $this->getContent(); # May change wgTitle!
288 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
289 $wgOut->setHTMLTitle( $wgTitle->getPrefixedText() .
290 " - " . wfMsg( "wikititlesuffix" ) );
291
292 # We're looking at an old revision
293
294 if ( $oldid ) {
295 $this->setOldSubtitle();
296 $wgOut->setRobotpolicy( "noindex,follow" );
297 }
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 );
304 }
305 $wgOut->checkLastModified( $this->mTouched );
306 $this->tryFileCache();
307 $wgLinkCache->preFill( $wgTitle );
308 $wgOut->addWikiText( $text );
309
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.
313
314 if ( Namespace::getImage() == $wgTitle->getNamespace() ) {
315 $this->imageHistory();
316 $this->imageLinks();
317 }
318 $this->viewUpdates();
319 wfProfileOut();
320 }
321
322 # This is the function that gets called for "action=edit".
323
324 function edit()
325 {
326 global $wgOut, $wgUser, $wgTitle;
327 global $wpTextbox1, $wpSummary, $wpSave, $wpPreview;
328 global $wpMinoredit, $wpEdittime, $wpTextbox2;
329
330 $fields = array( "wpTextbox1", "wpSummary", "wpTextbox2" );
331 wfCleanFormFields( $fields );
332
333 if ( ! $wgTitle->userCanEdit() ) {
334 $this->view();
335 return;
336 }
337 if ( $wgUser->isBlocked() ) {
338 $this->blockedIPpage();
339 return;
340 }
341 if ( wfReadOnly() ) {
342 if( isset( $wpSave ) or isset( $wpPreview ) ) {
343 $this->editForm( "preview" );
344 } else {
345 $wgOut->readOnlyPage();
346 }
347 return;
348 }
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" );
356 }
357 }
358
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.
364
365 function submit()
366 {
367 global $wpSave, $wpPreview;
368 if ( ! isset( $wpPreview ) ) { $wpSave = 1; }
369
370 $this->edit();
371 }
372
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.
378
379 function editForm( $formtype )
380 {
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;
387
388 if(isset($wpSection)) { $section=$wpSection; }
389
390 $sk = $wgUser->getSkin();
391 $isConflict = false;
392 $wpTextbox1 = rtrim ( $wpTextbox1 ) ; # To avoid text getting longer on each preview
393
394 if(!$wgTitle->getArticleID()) { # new article
395
396 $wgOut->addWikiText(wfmsg("newarticletext"));
397
398 }
399
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.
404
405 if ( "save" == $formtype ) {
406 if ( $wgUser->isBlocked() ) {
407 $this->blockedIPpage();
408 return;
409 }
410 if ( wfReadOnly() ) {
411 $wgOut->readOnlyPage();
412 return;
413 }
414 # If article is new, insert it.
415
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;
425 }
426 $this->mCountAdjustment = $this->isCountable( $wpTextbox1 );
427 $this->insertNewArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
428 return;
429 }
430 # Article exists. Check for edit conflict.
431 # Don't check for conflict when appending a comment - this should always work
432 # switch from section editing to normal editing in edit conflict
433
434 $this->clear(); # Force reload of dates, etc.
435 if ( $section!="new" && ( $this->getTimestamp() != $wpEdittime ) ) { $isConflict = true;$section="";$wpSection=""; }
436 $u = $wgUser->getID();
437
438 # Supress edit conflict with self
439
440 if ( ( 0 != $u ) && ( $this->getUser() == $u ) ) {
441 $isConflict = false;
442 }
443 if ( ! $isConflict ) {
444 # All's well: update the article here
445 $this->updateArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis, $wpSection );
446 return;
447 }
448 }
449 # First time through: get contents, set time for conflict
450 # checking, etc.
451
452 if ( "initial" == $formtype ) {
453 $wpEdittime = $this->getTimestamp();
454 $wpTextbox1 = $this->getContent(true);
455 $wpSummary = "";
456 }
457 $wgOut->setRobotpolicy( "noindex,nofollow" );
458 $wgOut->setArticleFlag( false );
459
460 if ( $isConflict ) {
461 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
462 wfMsg( "editconflict" ) );
463 $wgOut->setPageTitle( $s );
464 $wgOut->addHTML( wfMsg( "explainconflict" ) );
465
466 $wpTextbox2 = $wpTextbox1;
467 $wpTextbox1 = $this->getContent(true);
468 $wpEdittime = $this->getTimestamp();
469 } else {
470 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
471 wfMsg( "editing" ) );
472
473 if($section!="") {
474 if($section=="new") {
475 $s.=wfMsg("commentedit");
476 } else {
477 $s.=wfMsg("sectionedit");
478 }
479 }
480 $wgOut->setPageTitle( $s );
481 if ( $oldid ) {
482 $this->setOldSubtitle();
483 $wgOut->addHTML( wfMsg( "editingold" ) );
484 }
485 }
486
487 if( wfReadOnly() ) {
488 $wgOut->addHTML( "<strong>" .
489 wfMsg( "readonlywarning" ) .
490 "</strong>" );
491 }
492 if( $wgTitle->isProtected() ) {
493 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
494 "</strong><br />\n" );
495 }
496
497 $kblength = (int)(strlen( $wpTextbox1 ) / 1024);
498 if( $kblength > 29 ) {
499 $wgOut->addHTML( "<strong>" .
500 str_replace( '$1', $kblength , wfMsg( "longpagewarning" ) )
501 . "</strong>" );
502 }
503
504 $rows = $wgUser->getOption( "rows" );
505 $cols = $wgUser->getOption( "cols" );
506
507 $ew = $wgUser->getOption( "editwidth" );
508 if ( $ew ) $ew = " style=\"width:100%\"";
509 else $ew = "" ;
510
511 $q = "action=submit";
512 if ( "no" == $redirect ) { $q .= "&redirect=no"; }
513 $action = wfEscapeHTML( wfLocalUrl( $wgTitle->getPrefixedURL(), $q ) );
514
515 $summary = wfMsg( "summary" );
516 $subject = wfMsg("subject");
517 $minor = wfMsg( "minoredit" );
518 $watchthis = wfMsg ("watchthis");
519 $save = wfMsg( "savearticle" );
520 $prev = wfMsg( "showpreview" );
521
522 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedURL(),
523 wfMsg( "cancel" ) );
524 $edithelp = $sk->makeKnownLink( wfMsg( "edithelppage" ),
525 wfMsg( "edithelp" ) );
526 $copywarn = str_replace( "$1", $sk->makeKnownLink(
527 wfMsg( "copyrightpage" ) ), wfMsg( "copyrightwarning" ) );
528
529 $wpTextbox1 = wfEscapeHTML( $wpTextbox1 );
530 $wpTextbox2 = wfEscapeHTML( $wpTextbox2 );
531 $wpSummary = wfEscapeHTML( $wpSummary );
532
533 // activate checkboxes if user wants them to be always active
534 if (!$wpPreview && $wgUser->getOption("watchdefault")) $wpWatchthis=1;
535 if (!$wpPreview && $wgUser->getOption("minordefault")) $wpMinoredit=1;
536
537 // activate checkbox also if user is already watching the page,
538 // require wpWatchthis to be unset so that second condition is not
539 // checked unnecessarily
540 if (!$wpWatchthis && !$wpPreview && $wgTitle->userIsWatching()) $wpWatchthis=1;
541
542 if ( 0 != $wgUser->getID() ) {
543 $checkboxhtml=
544 "<input tabindex=3 type=checkbox value=1 name='wpMinoredit'".($wpMinoredit?" checked":"").">{$minor}".
545 "<input tabindex=4 type=checkbox name='wpWatchthis'".($wpWatchthis?" checked":"").">{$watchthis}<br>";
546
547 } else {
548 $checkboxhtml="";
549 }
550
551
552 if ( "preview" == $formtype) {
553
554 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
555 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large><P>\n";
556 if ( $isConflict ) {
557 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
558 "</h2>\n";
559 }
560 $previewtext = wfUnescapeHTML( $wpTextbox1 );
561
562 if($wgUser->getOption("previewontop")) {
563 $wgOut->addHTML($previewhead);
564 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) ."\n\n");
565 }
566 $wgOut->addHTML( "<br clear=\"all\" />\n" );
567 }
568
569 # if this is a comment, show a subject line at the top, which is also the edit summary.
570 # Otherwise, show a summary field at the bottom
571 if($section=="new") {
572
573 $commentsubject="{$subject}: <input tabindex=1 type=text value=\"{$wpSummary}\" name=\"wpSummary\" maxlength=200 size=60><br>";
574 } else {
575
576 $editsummary="{$summary}: <input tabindex=3 type=text value=\"{$wpSummary}\" name=\"wpSummary\" maxlength=200 size=60><br>";
577 }
578
579 $wgOut->addHTML( "
580 <form id=\"editform\" name=\"editform\" method=\"post\" action=\"$action\"
581 enctype=\"application/x-www-form-urlencoded\">
582 {$commentsubject}
583 <textarea tabindex=2 name=\"wpTextbox1\" rows={$rows}
584 cols={$cols}{$ew} wrap=\"virtual\">" .
585 $wgLang->recodeForEdit( $wpTextbox1 ) .
586 "
587 </textarea>
588 <br>{$editsummary}
589 {$checkboxhtml}
590 <input tabindex=5 type=submit value=\"{$save}\" name=\"wpSave\">
591 <input tabindex=6 type=submit value=\"{$prev}\" name=\"wpPreview\">
592 <em>{$cancel}</em> | <em>{$edithelp}</em>
593 <br><br>{$copywarn}
594 <input type=hidden value=\"{$section}\" name=\"wpSection\">
595 <input type=hidden value=\"{$wpEdittime}\" name=\"wpEdittime\">\n" );
596
597 if ( $isConflict ) {
598 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
599 DifferenceEngine::showDiff( $wpTextbox2, $wpTextbox1,
600 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
601
602 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
603 <textarea tabindex=6 name=\"wpTextbox2\" rows={$rows} cols={$cols} wrap=virtual>"
604 . $wgLang->recodeForEdit( $wpTextbox2 ) .
605 "
606 </textarea>" );
607 }
608 $wgOut->addHTML( "</form>\n" );
609 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
610 $wgOut->addHTML($previewhead);
611 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) );
612 }
613
614 }
615
616 # Theoretically we could defer these whole insert and update
617 # functions for after display, but that's taking a big leap
618 # of faith, and we want to be able to report database
619 # errors at some point.
620
621 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
622 {
623 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
624 $fname = "Article::insertNewArticle";
625
626 $ns = $wgTitle->getNamespace();
627 $ttl = $wgTitle->getDBkey();
628 $text = $this->preSaveTransform( $text );
629 if ( preg_match( "/^#redirect/i", $text ) ) { $redir = 1; }
630 else { $redir = 0; }
631
632 $now = wfTimestampNow();
633 $won = wfInvertTimestamp( $now );
634 wfSeedRandom();
635 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
636 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
637 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
638 "cur_restrictions,cur_user_text,cur_is_redirect," .
639 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
640 wfStrencode( $text ) . "', '" .
641 wfStrencode( $summary ) . "', '" .
642 $wgUser->getID() . "', '{$now}', " .
643 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
644 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
645 $res = wfQuery( $sql, $fname );
646
647 $newid = wfInsertId();
648 $wgTitle->resetArticleID( $newid );
649
650 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
651 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
652 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
653 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
654 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
655 wfStrencode( $wgUser->getName() ) . "','" .
656 wfStrencode( $summary ) . "',0,0," .
657 ( $wgUser->isBot() ? 1 : 0 ) . ")";
658 wfQuery( $sql, $fname );
659 if ($watchthis) {
660 if(!$wgTitle->userIsWatching()) $this->watch();
661 } else {
662 if ( $wgTitle->userIsWatching() ) {
663 $this->unwatch();
664 }
665 }
666
667 $this->showArticle( $text, wfMsg( "newarticle" ) );
668 }
669
670 function updateArticle( $text, $summary, $minor, $watchthis, $section )
671 {
672 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
673 global $wgDBtransactions;
674 $fname = "Article::updateArticle";
675
676 // insert updated section into old text if we have only edited part
677 // of the article
678 if ($section != "") {
679 $oldtext=$this->getContent();
680 if($section=="new") {
681 if($summary) $summary="== {$summary} ==\n\n";
682 $text=$oldtext."\n\n".$summary.$text;
683 } else {
684 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
685 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
686 $secs[$section*2]=$text."\n\n"; // replace with edited
687 if($section) { $secs[$section*2-1]=""; } // erase old headline
688 $text=join("",$secs);
689 }
690 }
691 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
692 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
693 if ( preg_match( "/^(#redirect[^\\n]+)/i", $text, $m ) ) {
694 $redir = 1;
695 $text = $m[1] . "\n"; # Remove all content but redirect
696 }
697 else { $redir = 0; }
698 $this->loadLastEdit();
699
700 $text = $this->preSaveTransform( $text );
701
702 # Update article, but only if changed.
703
704 if( $wgDBtransactions ) {
705 $sql = "BEGIN";
706 wfQuery( $sql );
707 }
708 $oldtext = $this->getContent( true );
709
710 if ( 0 != strcmp( $text, $oldtext ) ) {
711 $this->mCountAdjustment = $this->isCountable( $text )
712 - $this->isCountable( $oldtext );
713
714 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
715 "old_comment,old_user,old_user_text,old_timestamp," .
716 "old_minor_edit,inverse_timestamp) VALUES (" .
717 $wgTitle->getNamespace() . ", '" .
718 wfStrencode( $wgTitle->getDBkey() ) . "', '" .
719 wfStrencode( $oldtext ) . "', '" .
720 wfStrencode( $this->getComment() ) . "', " .
721 $this->getUser() . ", '" .
722 wfStrencode( $this->getUserText() ) . "', '" .
723 $this->getTimestamp() . "', " . $me1 . ", '" .
724 wfInvertTimestamp( $this->getTimestamp() ) . "')";
725 $res = wfQuery( $sql, $fname );
726 $oldid = wfInsertID( $res );
727
728 $now = wfTimestampNow();
729 $won = wfInvertTimestamp( $now );
730 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
731 "',cur_comment='" . wfStrencode( $summary ) .
732 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
733 ",cur_timestamp='{$now}',cur_user_text='" .
734 wfStrencode( $wgUser->getName() ) .
735 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
736 "WHERE cur_id=" . $this->getID();
737 wfQuery( $sql, $fname );
738
739 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
740 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
741 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
742 "'{$now}','{$now}'," . $wgTitle->getNamespace() . ",'" .
743 wfStrencode( $wgTitle->getDBkey() ) . "',0,{$me2}," .
744 ( $wgUser->isBot() ? 1 : 0 ) . "," .
745 $this->getID() . "," . $wgUser->getID() . ",'" .
746 wfStrencode( $wgUser->getName() ) . "','" .
747 wfStrencode( $summary ) . "',0,{$oldid})";
748 wfQuery( $sql, $fname );
749
750 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
751 "WHERE rc_namespace=" . $wgTitle->getNamespace() . " AND " .
752 "rc_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' AND " .
753 "rc_timestamp='" . $this->getTimestamp() . "'";
754 wfQuery( $sql, $fname );
755
756 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
757 "WHERE rc_cur_id=" . $this->getID();
758 wfQuery( $sql, $fname );
759 }
760 if( $wgDBtransactions ) {
761 $sql = "COMMIT";
762 wfQuery( $sql );
763 }
764
765 if ($watchthis) {
766 if (!$wgTitle->userIsWatching()) $this->watch();
767 } else {
768 if ( $wgTitle->userIsWatching() ) {
769 $this->unwatch();
770 }
771 }
772
773 $this->showArticle( $text, wfMsg( "updated" ) );
774 }
775
776 # After we've either updated or inserted the article, update
777 # the link tables and redirect to the new page.
778
779 function showArticle( $text, $subtitle )
780 {
781 global $wgOut, $wgTitle, $wgUser, $wgLinkCache, $wgUseBetterLinksUpdate;
782
783 $wgLinkCache = new LinkCache();
784
785 # Get old version of link table to allow incremental link updates
786 if ( $wgUseBetterLinksUpdate ) {
787 $wgLinkCache->preFill( $wgTitle );
788 $wgLinkCache->clear();
789 }
790
791 # Now update the link cache by parsing the text
792 $wgOut->addWikiText( $text );
793
794 $this->editUpdates( $text );
795 if( preg_match( "/^#redirect/i", $text ) )
796 $r = "redirect=no";
797 else
798 $r = "";
799 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL(), $r ) );
800 }
801
802 # If the page we've just displayed is in the "Image" namespace,
803 # we follow it with an upload history of the image and its usage.
804
805 function imageHistory()
806 {
807 global $wgUser, $wgOut, $wgLang, $wgTitle;
808 $fname = "Article::imageHistory";
809
810 $sql = "SELECT img_size,img_description,img_user," .
811 "img_user_text,img_timestamp FROM image WHERE " .
812 "img_name='" . wfStrencode( $wgTitle->getDBkey() ) . "'";
813 $res = wfQuery( $sql, $fname );
814
815 if ( 0 == wfNumRows( $res ) ) { return; }
816
817 $sk = $wgUser->getSkin();
818 $s = $sk->beginImageHistoryList();
819
820 $line = wfFetchObject( $res );
821 $s .= $sk->imageHistoryLine( true, $line->img_timestamp,
822 $wgTitle->getText(), $line->img_user,
823 $line->img_user_text, $line->img_size, $line->img_description );
824
825 $sql = "SELECT oi_size,oi_description,oi_user," .
826 "oi_user_text,oi_timestamp,oi_archive_name FROM oldimage WHERE " .
827 "oi_name='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
828 "ORDER BY oi_timestamp DESC";
829 $res = wfQuery( $sql, $fname );
830
831 while ( $line = wfFetchObject( $res ) ) {
832 $s .= $sk->imageHistoryLine( false, $line->oi_timestamp,
833 $line->oi_archive_name, $line->oi_user,
834 $line->oi_user_text, $line->oi_size, $line->oi_description );
835 }
836 $s .= $sk->endImageHistoryList();
837 $wgOut->addHTML( $s );
838 }
839
840 function imageLinks()
841 {
842 global $wgUser, $wgOut, $wgTitle;
843
844 $wgOut->addHTML( "<h2>" . wfMsg( "imagelinks" ) . "</h2>\n" );
845
846 $sql = "SELECT il_from FROM imagelinks WHERE il_to='" .
847 wfStrencode( $wgTitle->getDBkey() ) . "'";
848 $res = wfQuery( $sql, "Article::imageLinks" );
849
850 if ( 0 == wfNumRows( $res ) ) {
851 $wgOut->addHtml( "<p>" . wfMsg( "nolinkstoimage" ) . "\n" );
852 return;
853 }
854 $wgOut->addHTML( "<p>" . wfMsg( "linkstoimage" ) . "\n<ul>" );
855
856 $sk = $wgUser->getSkin();
857 while ( $s = wfFetchObject( $res ) ) {
858 $name = $s->il_from;
859 $link = $sk->makeKnownLink( $name, "" );
860 $wgOut->addHTML( "<li>{$link}</li>\n" );
861 }
862 $wgOut->addHTML( "</ul>\n" );
863 }
864
865 # Add this page to my watchlist
866
867 function watch()
868 {
869 global $wgUser, $wgTitle, $wgOut, $wgLang;
870 global $wgDeferredUpdateList;
871
872 if ( 0 == $wgUser->getID() ) {
873 $wgOut->errorpage( "watchnologin", "watchnologintext" );
874 return;
875 }
876 if ( wfReadOnly() ) {
877 $wgOut->readOnlyPage();
878 return;
879 }
880 $wgUser->addWatch( $wgTitle );
881
882 $wgOut->setPagetitle( wfMsg( "addedwatch" ) );
883 $wgOut->setRobotpolicy( "noindex,follow" );
884
885 $sk = $wgUser->getSkin() ;
886 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
887
888 $text = str_replace( "$1", $link ,
889 wfMsg( "addedwatchtext" ) );
890 $wgOut->addHTML( $text );
891
892 $up = new UserUpdate();
893 array_push( $wgDeferredUpdateList, $up );
894
895 $wgOut->returnToMain( false );
896 }
897
898 function unwatch()
899 {
900 global $wgUser, $wgTitle, $wgOut, $wgLang;
901 global $wgDeferredUpdateList;
902
903 if ( 0 == $wgUser->getID() ) {
904 $wgOut->errorpage( "watchnologin", "watchnologintext" );
905 return;
906 }
907 if ( wfReadOnly() ) {
908 $wgOut->readOnlyPage();
909 return;
910 }
911 $wgUser->removeWatch( $wgTitle );
912
913 $wgOut->setPagetitle( wfMsg( "removedwatch" ) );
914 $wgOut->setRobotpolicy( "noindex,follow" );
915
916 $sk = $wgUser->getSkin() ;
917 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
918
919 $text = str_replace( "$1", $link ,
920 wfMsg( "removedwatchtext" ) );
921 $wgOut->addHTML( $text );
922
923 $up = new UserUpdate();
924 array_push( $wgDeferredUpdateList, $up );
925
926 $wgOut->returnToMain( false );
927 }
928
929 # This shares a lot of issues (and code) with Recent Changes
930
931 function history()
932 {
933 global $wgUser, $wgOut, $wgLang, $wgTitle, $offset, $limit;
934
935 # If page hasn't changed, client can cache this
936
937 $wgOut->checkLastModified( $this->getTimestamp() );
938 wfProfileIn( "Article::history" );
939
940 $wgOut->setPageTitle( $wgTitle->getPRefixedText() );
941 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
942 $wgOut->setArticleFlag( false );
943 $wgOut->setRobotpolicy( "noindex,nofollow" );
944
945 if( $wgTitle->getArticleID() == 0 ) {
946 $wgOut->addHTML( wfMsg( "nohistory" ) );
947 wfProfileOut();
948 return;
949 }
950
951 $offset = (int)$offset;
952 $limit = (int)$limit;
953 if( $limit == 0 ) $limit = 50;
954 $namespace = $wgTitle->getNamespace();
955 $title = $wgTitle->getText();
956 $sql = "SELECT old_id,old_user," .
957 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
958 "FROM old USE INDEX (name_title_timestamp) " .
959 "WHERE old_namespace={$namespace} AND " .
960 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
961 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
962 $res = wfQuery( $sql, "Article::history" );
963
964 $revs = wfNumRows( $res );
965 if( $wgTitle->getArticleID() == 0 ) {
966 $wgOut->addHTML( wfMsg( "nohistory" ) );
967 wfProfileOut();
968 return;
969 }
970
971 $sk = $wgUser->getSkin();
972 $numbar = wfViewPrevNext(
973 $offset, $limit,
974 $wgTitle->getPrefixedText(),
975 "action=history" );
976 $s = $numbar;
977 $s .= $sk->beginHistoryList();
978
979 if($offset == 0 )
980 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
981 $this->getUserText(), $namespace,
982 $title, 0, $this->getComment(),
983 ( $this->getMinorEdit() > 0 ) );
984
985 $revs = wfNumRows( $res );
986 while ( $line = wfFetchObject( $res ) ) {
987 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
988 $line->old_user_text, $namespace,
989 $title, $line->old_id,
990 $line->old_comment, ( $line->old_minor_edit > 0 ) );
991 }
992 $s .= $sk->endHistoryList();
993 $s .= $numbar;
994 $wgOut->addHTML( $s );
995 wfProfileOut();
996 }
997
998 function protect()
999 {
1000 global $wgUser, $wgOut, $wgTitle;
1001
1002 if ( ! $wgUser->isSysop() ) {
1003 $wgOut->sysopRequired();
1004 return;
1005 }
1006 if ( wfReadOnly() ) {
1007 $wgOut->readOnlyPage();
1008 return;
1009 }
1010 $id = $wgTitle->getArticleID();
1011 if ( 0 == $id ) {
1012 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
1013 return;
1014 }
1015 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1016 "cur_restrictions='sysop' WHERE cur_id={$id}";
1017 wfQuery( $sql, "Article::protect" );
1018
1019 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
1020 }
1021
1022 function unprotect()
1023 {
1024 global $wgUser, $wgOut, $wgTitle;
1025
1026 if ( ! $wgUser->isSysop() ) {
1027 $wgOut->sysopRequired();
1028 return;
1029 }
1030 if ( wfReadOnly() ) {
1031 $wgOut->readOnlyPage();
1032 return;
1033 }
1034 $id = $wgTitle->getArticleID();
1035 if ( 0 == $id ) {
1036 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
1037 return;
1038 }
1039 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1040 "cur_restrictions='' WHERE cur_id={$id}";
1041 wfQuery( $sql, "Article::unprotect" );
1042
1043 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
1044 }
1045
1046 function delete()
1047 {
1048 global $wgUser, $wgOut, $wgTitle;
1049 global $wpConfirm, $wpReason, $image, $oldimage;
1050
1051 # Anybody can delete old revisions of images; only sysops
1052 # can delete articles and current images
1053
1054 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
1055 $wgOut->sysopRequired();
1056 return;
1057 }
1058 if ( wfReadOnly() ) {
1059 $wgOut->readOnlyPage();
1060 return;
1061 }
1062
1063 # Better double-check that it hasn't been deleted yet!
1064 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
1065 if ( $image ) {
1066 if ( "" == trim( $image ) ) {
1067 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1068 return;
1069 }
1070 $sub = str_replace( "$1", $image, wfMsg( "deletesub" ) );
1071 } else {
1072
1073 if ( ( "" == trim( $wgTitle->getText() ) )
1074 or ( $wgTitle->getArticleId() == 0 ) ) {
1075 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1076 return;
1077 }
1078 $sub = str_replace( "$1", $wgTitle->getPrefixedText(),
1079 wfMsg( "deletesub" ) );
1080
1081 # determine whether this page has earlier revisions
1082 # and insert a warning if it does
1083 # we select the text because it might be useful below
1084 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
1085 $res=wfQuery($sql,$fname);
1086 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
1087 $skin=$wgUser->getSkin();
1088 $wgOut->addHTML("<B>".wfMsg("historywarning"));
1089 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
1090 }
1091
1092 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."'";
1093 $res=wfQuery($sql,$fname);
1094 if( ($s=wfFetchObject($res))) {
1095
1096 # if this is a mini-text, we can paste part of it into the deletion reason
1097
1098 #if this is empty, an earlier revision may contain "useful" text
1099 if($s->cur_text!="") {
1100 $text=$s->cur_text;
1101 } else {
1102 if($old) {
1103 $text=$old->old_text;
1104 $blanked=1;
1105 }
1106
1107 }
1108
1109 $length=strlen($text);
1110
1111 # this should not happen, since it is not possible to store an empty, new
1112 # page. Let's insert a standard text in case it does, though
1113 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
1114
1115
1116 if($length < 500 && !$wpReason) {
1117
1118 # comment field=255, let's grep the first 150 to have some user
1119 # space left
1120 $text=substr($text,0,150);
1121 # let's strip out newlines and HTML tags
1122 $text=preg_replace("/\"/","'",$text);
1123 $text=preg_replace("/\</","&lt;",$text);
1124 $text=preg_replace("/\>/","&gt;",$text);
1125 $text=preg_replace("/[\n\r]/","",$text);
1126 if(!$blanked) {
1127 $wpReason=wfMsg("excontent"). " '".$text;
1128 } else {
1129 $wpReason=wfMsg("exbeforeblank") . " '".$text;
1130 }
1131 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
1132 $wpReason.="'";
1133 }
1134 }
1135
1136 }
1137
1138 # Likewise, deleting old images doesn't require confirmation
1139 if ( $oldimage || 1 == $wpConfirm ) {
1140 $this->doDelete();
1141 return;
1142 }
1143
1144 $wgOut->setSubtitle( $sub );
1145 $wgOut->setRobotpolicy( "noindex,nofollow" );
1146 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1147
1148 $t = $wgTitle->getPrefixedURL();
1149 $q = "action=delete";
1150
1151 if ( $image ) {
1152 $q .= "&image={$image}";
1153 } else if ( $oldimage ) {
1154 $q .= "&oldimage={$oldimage}";
1155 } else {
1156 $q .= "&title={$t}";
1157 }
1158 $formaction = wfEscapeHTML( wfLocalUrl( "", $q ) );
1159 $confirm = wfMsg( "confirm" );
1160 $check = wfMsg( "confirmcheck" );
1161 $delcom = wfMsg( "deletecomment" );
1162
1163 $wgOut->addHTML( "
1164 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1165 <table border=0><tr><td align=right>
1166 {$delcom}:</td><td align=left>
1167 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
1168 </td></tr><tr><td>&nbsp;</td></tr>
1169 <tr><td align=right>
1170 <input type=checkbox name=\"wpConfirm\" value='1'>
1171 </td><td>{$check}</td>
1172 </tr><tr><td>&nbsp;</td><td>
1173 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1174 </td></tr></table></form>\n" );
1175
1176 $wgOut->returnToMain( false );
1177 }
1178
1179 function doDelete()
1180 {
1181 global $wgOut, $wgTitle, $wgUser, $wgLang;
1182 global $image, $oldimage, $wpReason;
1183 $fname = "Article::doDelete";
1184
1185 if ( $image ) {
1186 $dest = wfImageDir( $image );
1187 $archive = wfImageDir( $image );
1188 if ( ! unlink( "{$dest}/{$image}" ) ) {
1189 $wgOut->fileDeleteError( "{$dest}/{$image}" );
1190 return;
1191 }
1192 $sql = "DELETE FROM image WHERE img_name='" .
1193 wfStrencode( $image ) . "'";
1194 wfQuery( $sql, $fname );
1195
1196 $sql = "SELECT oi_archive_name FROM oldimage WHERE oi_name='" .
1197 wfStrencode( $image ) . "'";
1198 $res = wfQuery( $sql, $fname );
1199
1200 while ( $s = wfFetchObject( $res ) ) {
1201 $this->doDeleteOldImage( $s->oi_archive_name );
1202 }
1203 $sql = "DELETE FROM oldimage WHERE oi_name='" .
1204 wfStrencode( $image ) . "'";
1205 wfQuery( $sql, $fname );
1206
1207 # Image itself is now gone, and database is cleaned.
1208 # Now we remove the image description page.
1209
1210 $nt = Title::newFromText( $wgLang->getNsText( Namespace::getImage() ) . ":" . $image );
1211 $this->doDeleteArticle( $nt );
1212
1213 $deleted = $image;
1214 } else if ( $oldimage ) {
1215 $this->doDeleteOldImage( $oldimage );
1216 $sql = "DELETE FROM oldimage WHERE oi_archive_name='" .
1217 wfStrencode( $oldimage ) . "'";
1218 wfQuery( $sql, $fname );
1219
1220 $deleted = $oldimage;
1221 } else {
1222 $this->doDeleteArticle( $wgTitle );
1223 $deleted = $wgTitle->getPrefixedText();
1224 }
1225 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1226 $wgOut->setRobotpolicy( "noindex,nofollow" );
1227
1228 $sk = $wgUser->getSkin();
1229 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1230 Namespace::getWikipedia() ) .
1231 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1232
1233 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1234 $text = str_replace( "$2", $loglink, $text );
1235
1236 $wgOut->addHTML( "<p>" . $text );
1237 $wgOut->returnToMain( false );
1238 }
1239
1240 function doDeleteOldImage( $oldimage )
1241 {
1242 global $wgOut;
1243
1244 $name = substr( $oldimage, 15 );
1245 $archive = wfImageArchiveDir( $name );
1246 if ( ! unlink( "{$archive}/{$oldimage}" ) ) {
1247 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
1248 }
1249 }
1250
1251 function doDeleteArticle( $title )
1252 {
1253 global $wgUser, $wgOut, $wgLang, $wpReason, $wgTitle, $wgDeferredUpdateList;
1254
1255 $fname = "Article::doDeleteArticle";
1256 $ns = $title->getNamespace();
1257 $t = wfStrencode( $title->getDBkey() );
1258 $id = $title->getArticleID();
1259
1260 if ( "" == $t ) {
1261 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1262 return;
1263 }
1264
1265 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1266 array_push( $wgDeferredUpdateList, $u );
1267
1268 # Move article and history to the "archive" table
1269 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1270 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1271 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1272 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1273 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1274 wfQuery( $sql, $fname );
1275
1276 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1277 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1278 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1279 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1280 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1281 wfQuery( $sql, $fname );
1282
1283 # Now that it's safely backed up, delete it
1284
1285 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1286 "cur_title='{$t}'";
1287 wfQuery( $sql, $fname );
1288
1289 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1290 "old_title='{$t}'";
1291 wfQuery( $sql, $fname );
1292
1293 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1294 "rc_title='{$t}'";
1295 wfQuery( $sql, $fname );
1296
1297 # Finally, clean up the link tables
1298
1299 if ( 0 != $id ) {
1300 $t = wfStrencode( $title->getPrefixedDBkey() );
1301 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1302 $res = wfQuery( $sql, $fname );
1303
1304 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1305 $now = wfTimestampNow();
1306 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1307 $first = true;
1308
1309 while ( $s = wfFetchObject( $res ) ) {
1310 $nt = Title::newFromDBkey( $s->l_from );
1311 $lid = $nt->getArticleID();
1312
1313 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1314 $first = false;
1315 $sql .= "({$lid},'{$t}')";
1316 $sql2 .= "{$lid}";
1317 }
1318 $sql2 .= ")";
1319 if ( ! $first ) {
1320 wfQuery( $sql, $fname );
1321 wfQuery( $sql2, $fname );
1322 }
1323 wfFreeResult( $res );
1324
1325 $sql = "DELETE FROM links WHERE l_to={$id}";
1326 wfQuery( $sql, $fname );
1327
1328 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1329 wfQuery( $sql, $fname );
1330
1331 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1332 wfQuery( $sql, $fname );
1333
1334 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1335 wfQuery( $sql, $fname );
1336 }
1337
1338 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1339 $art = $title->getPrefixedText();
1340 $wpReason = wfCleanQueryVar( $wpReason );
1341 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1342
1343 # Clear the cached article id so the interface doesn't act like we exist
1344 $wgTitle->resetArticleID( 0 );
1345 $wgTitle->mArticleID = 0;
1346 }
1347
1348 function revert()
1349 {
1350 global $wgOut;
1351 global $oldimage;
1352
1353 if ( strlen( $oldimage ) < 16 ) {
1354 $wgOut->unexpectedValueError( "oldimage", $oldimage );
1355 return;
1356 }
1357 if ( wfReadOnly() ) {
1358 $wgOut->readOnlyPage();
1359 return;
1360 }
1361 $name = substr( $oldimage, 15 );
1362
1363 $dest = wfImageDir( $name );
1364 $archive = wfImageArchiveDir( $name );
1365 $curfile = "{$dest}/{$name}";
1366
1367 if ( ! is_file( $curfile ) ) {
1368 $wgOut->fileNotFoundError( $curfile );
1369 return;
1370 }
1371 $oldver = wfTimestampNow() . "!{$name}";
1372 $size = wfGetSQL( "oldimage", "oi_size", "oi_archive_name='" .
1373 wfStrencode( $oldimage ) . "'" );
1374
1375 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
1376 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
1377 return;
1378 }
1379 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
1380 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
1381 }
1382 wfRecordUpload( $name, $oldver, $size, wfMsg( "reverted" ) );
1383
1384 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1385 $wgOut->setRobotpolicy( "noindex,nofollow" );
1386 $wgOut->addHTML( wfMsg( "imagereverted" ) );
1387 $wgOut->returnToMain( false );
1388 }
1389
1390 function rollback()
1391 {
1392 global $wgUser, $wgTitle, $wgLang, $wgOut, $from;
1393
1394 if ( ! $wgUser->isSysop() ) {
1395 $wgOut->sysopRequired();
1396 return;
1397 }
1398
1399 # Replace all this user's current edits with the next one down
1400 $tt = wfStrencode( $wgTitle->getDBKey() );
1401 $n = $wgTitle->getNamespace();
1402
1403 # Get the last editor
1404 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1405 $res = wfQuery( $sql );
1406 if( ($x = wfNumRows( $res )) != 1 ) {
1407 # Something wrong
1408 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1409 return;
1410 }
1411 $s = wfFetchObject( $res );
1412 $ut = wfStrencode( $s->cur_user_text );
1413 $uid = $s->cur_user;
1414 $pid = $s->cur_id;
1415
1416 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
1417 if( $from != $s->cur_user_text ) {
1418 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
1419 $wgOut->addWikiText( wfMsg( "alreadyrolled",
1420 htmlspecialchars( $wgTitle->getPrefixedText()),
1421 htmlspecialchars( $from ),
1422 htmlspecialchars( $s->cur_user_text ) ) );
1423 if($s->cur_comment != "") {
1424 $wgOut->addHTML(
1425 wfMsg("editcomment",
1426 htmlspecialchars( $s->cur_comment ) ) );
1427 }
1428 return;
1429 }
1430
1431 # Get the last edit not by this guy
1432 $sql = "SELECT old_text,old_user,old_user_text
1433 FROM old USE INDEX (name_title_timestamp)
1434 WHERE old_namespace={$n} AND old_title='{$tt}'
1435 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1436 ORDER BY inverse_timestamp LIMIT 1";
1437 $res = wfQuery( $sql );
1438 if( wfNumRows( $res ) != 1 ) {
1439 # Something wrong
1440 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1441 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1442 return;
1443 }
1444 $s = wfFetchObject( $res );
1445
1446 # Save it!
1447 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1448 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1449 $wgOut->setRobotpolicy( "noindex,nofollow" );
1450 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1451 $this->updateArticle( $s->old_text, $newcomment, 1, $wgTitle->userIsWatching() );
1452
1453 $wgOut->returnToMain( false );
1454 }
1455
1456
1457 # Do standard deferred updates after page view
1458
1459 /* private */ function viewUpdates()
1460 {
1461 global $wgDeferredUpdateList, $wgTitle;
1462
1463 if ( 0 != $this->getID() ) {
1464 $u = new ViewCountUpdate( $this->getID() );
1465 array_push( $wgDeferredUpdateList, $u );
1466 $u = new SiteStatsUpdate( 1, 0, 0 );
1467 array_push( $wgDeferredUpdateList, $u );
1468
1469 $u = new UserTalkUpdate( 0, $wgTitle->getNamespace(),
1470 $wgTitle->getDBkey() );
1471 array_push( $wgDeferredUpdateList, $u );
1472 }
1473 }
1474
1475 # Do standard deferred updates after page edit.
1476 # Every 1000th edit, prune the recent changes table.
1477
1478 /* private */ function editUpdates( $text )
1479 {
1480 global $wgDeferredUpdateList, $wgTitle;
1481
1482 wfSeedRandom();
1483 if ( 0 == mt_rand( 0, 999 ) ) {
1484 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1485 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1486 wfQuery( $sql );
1487 }
1488 $id = $this->getID();
1489 $title = $wgTitle->getPrefixedDBkey();
1490 $adj = $this->mCountAdjustment;
1491
1492 if ( 0 != $id ) {
1493 $u = new LinksUpdate( $id, $title );
1494 array_push( $wgDeferredUpdateList, $u );
1495 $u = new SiteStatsUpdate( 0, 1, $adj );
1496 array_push( $wgDeferredUpdateList, $u );
1497 $u = new SearchUpdate( $id, $title, $text );
1498 array_push( $wgDeferredUpdateList, $u );
1499
1500 $u = new UserTalkUpdate( 1, $wgTitle->getNamespace(),
1501 $wgTitle->getDBkey() );
1502 array_push( $wgDeferredUpdateList, $u );
1503 }
1504 }
1505
1506 /* private */ function setOldSubtitle()
1507 {
1508 global $wgLang, $wgOut;
1509
1510 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1511 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1512 $wgOut->setSubtitle( "({$r})" );
1513 }
1514
1515 function blockedIPpage()
1516 {
1517 global $wgOut, $wgUser, $wgLang;
1518
1519 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1520 $wgOut->setRobotpolicy( "noindex,nofollow" );
1521 $wgOut->setArticleFlag( false );
1522
1523 $id = $wgUser->blockedBy();
1524 $reason = $wgUser->blockedFor();
1525
1526 $name = User::whoIs( $id );
1527 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1528 ":{$name}|{$name}]]";
1529
1530 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1531 $text = str_replace( "$2", $reason, $text );
1532 $wgOut->addWikiText( $text );
1533 $wgOut->returnToMain( false );
1534 }
1535
1536 # This function is called right before saving the wikitext,
1537 # so we can do things like signatures and links-in-context.
1538
1539 function preSaveTransform( $text )
1540 {
1541 $s = "";
1542 while ( "" != $text ) {
1543 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1544 $s .= $this->pstPass2( $p[0] );
1545
1546 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1547 else {
1548 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1549 $s .= "<nowiki>{$q[0]}</nowiki>";
1550 $text = $q[1];
1551 }
1552 }
1553 return rtrim( $s );
1554 }
1555
1556 /* private */ function pstPass2( $text )
1557 {
1558 global $wgUser, $wgLang, $wgTitle, $wgLocaltimezone;
1559
1560 # Signatures
1561 #
1562 $n = $wgUser->getName();
1563 $k = $wgUser->getOption( "nickname" );
1564 if ( "" == $k ) { $k = $n; }
1565 if(isset($wgLocaltimezone)) {
1566 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1567 }
1568 /* Note: this is an ugly timezone hack for the European wikis */
1569 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1570 " (" . date( "T" ) . ")";
1571 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1572
1573 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1574 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1575 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1576 Namespace::getUser() ) . ":$n|$k]]", $text );
1577
1578 # Context links: [[|name]] and [[name (context)|]]
1579 #
1580 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1581 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1582 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1583
1584 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1585 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1586 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1587 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1588 # [[ns:page (cont)|]]
1589 $context = "";
1590 $t = $wgTitle->getText();
1591 if ( preg_match( $conpat, $t, $m ) ) {
1592 $context = $m[2];
1593 }
1594 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1595 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1596 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1597
1598 if ( "" == $context ) {
1599 $text = preg_replace( $p2, "[[\\1]]", $text );
1600 } else {
1601 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1602 }
1603 # Replace local image links with new [[image:]] style
1604
1605 $text = preg_replace(
1606 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/upload\/" .
1607 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1608 "\\1[[image:\\3.\\4]]", $text );
1609 $text = preg_replace(
1610 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/images\/uploads\/" .
1611 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1612 "\\1[[image:\\3.\\4]]", $text );
1613
1614 return $text;
1615 }
1616
1617
1618 /* Caching functions */
1619
1620 function tryFileCache() {
1621 if($this->isFileCacheable()) {
1622 if($this->isFileCacheGood()) {
1623 wfDebug( " tryFileCache() - about to load\n" );
1624 $this->loadFromFileCache();
1625 exit;
1626 } else {
1627 wfDebug( " tryFileCache() - starting buffer\n" );
1628 ob_start( array(&$this, 'saveToFileCache' ) );
1629 }
1630 } else {
1631 wfDebug( " tryFileCache() - not cacheable\n" );
1632 }
1633 }
1634
1635 function isFileCacheable() {
1636 global $wgUser, $wgTitle, $wgUseFileCache, $wgShowIPinHeader;
1637 global $action, $oldid, $diff, $redirect, $printable;
1638 return $wgUseFileCache
1639 and (!$wgShowIPinHeader)
1640 and ($wgUser->getId() == 0)
1641 and (!$wgUser->getNewtalk())
1642 and ($wgTitle->getNamespace != Namespace::getSpecial())
1643 and ($action == "view")
1644 and (!isset($oldid))
1645 and (!isset($diff))
1646 and (!isset($redirect))
1647 and (!isset($printable))
1648 and (!$this->mRedirectedFrom);
1649
1650 }
1651
1652 function fileCacheName() {
1653 global $wgTitle, $wgFileCacheDirectory, $wgLang;
1654 if( !$this->mFileCache ) {
1655 $hash = md5( $key = $wgTitle->getDbkey() );
1656 if( $wgTitle->getNamespace() )
1657 $key = $wgLang->getNsText( $wgTitle->getNamespace() ) . ":" . $key;
1658 $key = str_replace( ".", "%2E", urlencode( $key ) );
1659 $hash1 = substr( $hash, 0, 1 );
1660 $hash2 = substr( $hash, 0, 2 );
1661 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$key}.html";
1662 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
1663 }
1664 return $this->mFileCache;
1665 }
1666
1667 function isFileCacheGood() {
1668 global $wgUser, $wgCacheEpoch;
1669 if(!file_exists( $fn = $this->fileCacheName() ) ) return false;
1670 $cachetime = wfUnix2Timestamp( filemtime( $fn ) );
1671 $good = (( $this->mTouched <= $cachetime ) &&
1672 ($wgCacheEpoch <= $cachetime ));
1673 wfDebug(" isFileCacheGood() - cachetime $cachetime, touched {$this->mTouched} epoch {$wgCacheEpoch}, good $good\n");
1674 return $good;
1675 }
1676
1677 function loadFromFileCache() {
1678 global $wgUseGzip, $wgOut;
1679 wfDebug(" loadFromFileCache()\n");
1680 $filename=$this->fileCacheName();
1681 $filenamegz = "{$filename}.gz";
1682 $wgOut->sendCacheControl();
1683 if( $wgUseGzip
1684 && wfClientAcceptsGzip()
1685 && file_exists( $filenamegz)
1686 && ( filemtime( $filenamegz ) >= filemtime( $filename ) ) ) {
1687 wfDebug(" sending gzip\n");
1688 header( "Content-Encoding: gzip" );
1689 header( "Vary: Accept-Encoding" );
1690 $filename = $filenamegz;
1691 }
1692 readfile( $filename );
1693 }
1694
1695 function saveToFileCache( $text ) {
1696 global $wgUseGzip, $wgCompressByDefault;
1697 if(strcmp($text,"") == 0) return "";
1698
1699 wfDebug(" saveToFileCache()\n", false);
1700 $filename=$this->fileCacheName();
1701 $mydir2=substr($filename,0,strrpos($filename,"/")); # subdirectory level 2
1702 $mydir1=substr($mydir2,0,strrpos($mydir2,"/")); # subdirectory level 1
1703 if(!file_exists($mydir1)) { mkdir($mydir1,0775); } # create if necessary
1704 if(!file_exists($mydir2)) { mkdir($mydir2,0775); }
1705
1706 $f = fopen( $filename, "w" );
1707 if($f) {
1708 $now = wfTimestampNow();
1709 fwrite( $f, str_replace( "</html>",
1710 "<!-- Cached $now -->\n</html>",
1711 $text ) );
1712 fclose( $f );
1713 if( $wgUseGzip and $wgCompressByDefault ) {
1714 $start = microtime();
1715 wfDebug(" saving gzip\n");
1716 $gzout = gzencode( str_replace( "</html>",
1717 "<!-- Cached/compressed $now -->\n</html>",
1718 $text ) );
1719 if( $gzout === false ) {
1720 wfDebug(" failed to gzip compress, sending plaintext\n");
1721 return $text;
1722 }
1723 if( $f = fopen( "{$filename}.gz", "w" ) ) {
1724 fwrite( $f, $gzout );
1725 fclose( $f );
1726 $end = microtime();
1727
1728 list($usec1, $sec1) = explode(" ",$start);
1729 list($usec2, $sec2) = explode(" ",$end);
1730 $interval = ((float)$usec2 + (float)$sec2) -
1731 ((float)$usec1 + (float)$sec1);
1732 wfDebug(" saved gzip in $interval\n");
1733 } else {
1734 wfDebug(" failed to write gzip, still sending\n" );
1735 }
1736 if(wfClientAcceptsGzip()) {
1737 header( "Content-Encoding: gzip" );
1738 header( "Vary: Accept-Encoding" );
1739 wfDebug(" sending NEW gzip now...\n" );
1740 return $gzout;
1741 }
1742 }
1743 }
1744 return $text;
1745 }
1746
1747 }
1748
1749 ?>