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