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