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