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