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