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