2a126e44c86a604f6ef219743ae45495f7a28ddb
[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 # determine whether this page has earlier revisions
1026 # and insert a warning if it does
1027 # we select the text because it might be useful below
1028 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
1029 $res=wfQuery($sql, DB_READ, $fname);
1030 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
1031 $skin=$wgUser->getSkin();
1032 $wgOut->addHTML("<B>".wfMsg("historywarning"));
1033 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
1034 }
1035
1036 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."'";
1037 $res=wfQuery($sql, DB_READ, $fname);
1038 if( ($s=wfFetchObject($res))) {
1039
1040 # if this is a mini-text, we can paste part of it into the deletion reason
1041
1042 #if this is empty, an earlier revision may contain "useful" text
1043 if($s->cur_text!="") {
1044 $text=$s->cur_text;
1045 } else {
1046 if($old) {
1047 $text=$old->old_text;
1048 $blanked=1;
1049 }
1050
1051 }
1052
1053 $length=strlen($text);
1054
1055 # this should not happen, since it is not possible to store an empty, new
1056 # page. Let's insert a standard text in case it does, though
1057 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
1058
1059
1060 if($length < 500 && !$wpReason) {
1061
1062 # comment field=255, let's grep the first 150 to have some user
1063 # space left
1064 $text=substr($text,0,150);
1065 # let's strip out newlines and HTML tags
1066 $text=preg_replace("/\"/","'",$text);
1067 $text=preg_replace("/\</","&lt;",$text);
1068 $text=preg_replace("/\>/","&gt;",$text);
1069 $text=preg_replace("/[\n\r]/","",$text);
1070 if(!$blanked) {
1071 $wpReason=wfMsg("excontent"). " '".$text;
1072 } else {
1073 $wpReason=wfMsg("exbeforeblank") . " '".$text;
1074 }
1075 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
1076 $wpReason.="'";
1077 }
1078 }
1079
1080 return $this->confirmDelete();
1081 }
1082
1083 function confirmDelete( $par = "" )
1084 {
1085 global $wgOut;
1086
1087 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1088 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
1089 $wgOut->setRobotpolicy( "noindex,nofollow" );
1090 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1091
1092 $t = $this->mTitle->getPrefixedURL();
1093
1094 $formaction = wfEscapeHTML( wfLocalUrl( $t, "action=delete" . $par ) );
1095 $confirm = wfMsg( "confirm" );
1096 $check = wfMsg( "confirmcheck" );
1097 $delcom = wfMsg( "deletecomment" );
1098
1099 $wgOut->addHTML( "
1100 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1101 <table border=0><tr><td align=right>
1102 {$delcom}:</td><td align=left>
1103 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
1104 </td></tr><tr><td>&nbsp;</td></tr>
1105 <tr><td align=right>
1106 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
1107 </td><td><label for=\"wpConfirm\">{$check}</label></td>
1108 </tr><tr><td>&nbsp;</td><td>
1109 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1110 </td></tr></table></form>\n" );
1111
1112 $wgOut->returnToMain( false );
1113 }
1114
1115 function doDelete()
1116 {
1117 global $wgOut, $wgUser, $wgLang;
1118 global $wpReason;
1119 $fname = "Article::doDelete";
1120
1121 $this->doDeleteArticle( $this->mTitle );
1122 $deleted = $this->mTitle->getPrefixedText();
1123
1124 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1125 $wgOut->setRobotpolicy( "noindex,nofollow" );
1126
1127 $sk = $wgUser->getSkin();
1128 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1129 Namespace::getWikipedia() ) .
1130 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1131
1132 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1133 $text = str_replace( "$2", $loglink, $text );
1134
1135 $wgOut->addHTML( "<p>" . $text );
1136 $wgOut->returnToMain( false );
1137 }
1138
1139 function doDeleteArticle( $title )
1140 {
1141 global $wgUser, $wgOut, $wgLang, $wpReason, $wgDeferredUpdateList;
1142
1143 $fname = "Article::doDeleteArticle";
1144 $ns = $title->getNamespace();
1145 $t = wfStrencode( $title->getDBkey() );
1146 $id = $title->getArticleID();
1147
1148 if ( "" == $t ) {
1149 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1150 return;
1151 }
1152
1153 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1154 array_push( $wgDeferredUpdateList, $u );
1155
1156 # Move article and history to the "archive" table
1157 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1158 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1159 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1160 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1161 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1162 wfQuery( $sql, DB_WRITE, $fname );
1163
1164 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1165 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1166 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1167 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1168 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1169 wfQuery( $sql, DB_WRITE, $fname );
1170
1171 # Now that it's safely backed up, delete it
1172
1173 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1174 "cur_title='{$t}'";
1175 wfQuery( $sql, DB_WRITE, $fname );
1176
1177 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1178 "old_title='{$t}'";
1179 wfQuery( $sql, DB_WRITE, $fname );
1180
1181 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1182 "rc_title='{$t}'";
1183 wfQuery( $sql, DB_WRITE, $fname );
1184
1185 # Finally, clean up the link tables
1186
1187 if ( 0 != $id ) {
1188
1189 $t = wfStrencode( $title->getPrefixedDBkey() );
1190
1191 if ( $wgEnablePersistentLC ) {
1192 // Purge related entries in links cache on delete,
1193 wfQuery("DELETE linkscc FROM linkscc,links ".
1194 "WHERE lcc_title=links.l_from AND l_to={$id}", DB_WRITE);
1195 wfQuery("DELETE FROM linkscc WHERE lcc_title='{$t}'", DB_WRITE);
1196 }
1197
1198 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1199 $res = wfQuery( $sql, DB_READ, $fname );
1200
1201 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1202 $now = wfTimestampNow();
1203 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1204 $first = true;
1205
1206 while ( $s = wfFetchObject( $res ) ) {
1207 $nt = Title::newFromDBkey( $s->l_from );
1208 $lid = $nt->getArticleID();
1209
1210 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1211 $first = false;
1212 $sql .= "({$lid},'{$t}')";
1213 $sql2 .= "{$lid}";
1214 }
1215 $sql2 .= ")";
1216 if ( ! $first ) {
1217 wfQuery( $sql, DB_WRITE, $fname );
1218 wfQuery( $sql2, DB_WRITE, $fname );
1219 }
1220 wfFreeResult( $res );
1221
1222 $sql = "DELETE FROM links WHERE l_to={$id}";
1223 wfQuery( $sql, DB_WRITE, $fname );
1224
1225 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1226 wfQuery( $sql, DB_WRITE, $fname );
1227
1228 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1229 wfQuery( $sql, DB_WRITE, $fname );
1230
1231 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1232 wfQuery( $sql, DB_WRITE, $fname );
1233 }
1234
1235 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1236 $art = $title->getPrefixedText();
1237 $wpReason = wfCleanQueryVar( $wpReason );
1238 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1239
1240 # Clear the cached article id so the interface doesn't act like we exist
1241 $this->mTitle->resetArticleID( 0 );
1242 $this->mTitle->mArticleID = 0;
1243 }
1244
1245 function rollback()
1246 {
1247 global $wgUser, $wgLang, $wgOut, $from;
1248
1249 if ( ! $wgUser->isSysop() ) {
1250 $wgOut->sysopRequired();
1251 return;
1252 }
1253
1254 # Replace all this user's current edits with the next one down
1255 $tt = wfStrencode( $this->mTitle->getDBKey() );
1256 $n = $this->mTitle->getNamespace();
1257
1258 # Get the last editor
1259 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1260 $res = wfQuery( $sql, DB_READ );
1261 if( ($x = wfNumRows( $res )) != 1 ) {
1262 # Something wrong
1263 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1264 return;
1265 }
1266 $s = wfFetchObject( $res );
1267 $ut = wfStrencode( $s->cur_user_text );
1268 $uid = $s->cur_user;
1269 $pid = $s->cur_id;
1270
1271 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
1272 if( $from != $s->cur_user_text ) {
1273 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
1274 $wgOut->addWikiText( wfMsg( "alreadyrolled",
1275 htmlspecialchars( $this->mTitle->getPrefixedText()),
1276 htmlspecialchars( $from ),
1277 htmlspecialchars( $s->cur_user_text ) ) );
1278 if($s->cur_comment != "") {
1279 $wgOut->addHTML(
1280 wfMsg("editcomment",
1281 htmlspecialchars( $s->cur_comment ) ) );
1282 }
1283 return;
1284 }
1285
1286 # Get the last edit not by this guy
1287 $sql = "SELECT old_text,old_user,old_user_text
1288 FROM old USE INDEX (name_title_timestamp)
1289 WHERE old_namespace={$n} AND old_title='{$tt}'
1290 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1291 ORDER BY inverse_timestamp LIMIT 1";
1292 $res = wfQuery( $sql, DB_READ );
1293 if( wfNumRows( $res ) != 1 ) {
1294 # Something wrong
1295 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1296 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1297 return;
1298 }
1299 $s = wfFetchObject( $res );
1300
1301 # Save it!
1302 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1303 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1304 $wgOut->setRobotpolicy( "noindex,nofollow" );
1305 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1306 $this->updateArticle( $s->old_text, $newcomment, 1, $this->mTitle->userIsWatching() );
1307
1308 $wgOut->returnToMain( false );
1309 }
1310
1311
1312 # Do standard deferred updates after page view
1313
1314 /* private */ function viewUpdates()
1315 {
1316 global $wgDeferredUpdateList;
1317
1318 if ( 0 != $this->getID() ) {
1319 global $wgDisableCounters;
1320 if( !$wgDisableCounters ) {
1321 $u = new ViewCountUpdate( $this->getID() );
1322 array_push( $wgDeferredUpdateList, $u );
1323 $u = new SiteStatsUpdate( 1, 0, 0 );
1324 array_push( $wgDeferredUpdateList, $u );
1325 }
1326 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1327 $this->mTitle->getDBkey() );
1328 array_push( $wgDeferredUpdateList, $u );
1329 }
1330 }
1331
1332 # Do standard deferred updates after page edit.
1333 # Every 1000th edit, prune the recent changes table.
1334
1335 /* private */ function editUpdates( $text )
1336 {
1337 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1338
1339 wfSeedRandom();
1340 if ( 0 == mt_rand( 0, 999 ) ) {
1341 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1342 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1343 wfQuery( $sql, DB_WRITE );
1344 }
1345 $id = $this->getID();
1346 $title = $this->mTitle->getPrefixedDBkey();
1347 $adj = $this->mCountAdjustment;
1348
1349 if ( 0 != $id ) {
1350 $u = new LinksUpdate( $id, $title );
1351 array_push( $wgDeferredUpdateList, $u );
1352 $u = new SiteStatsUpdate( 0, 1, $adj );
1353 array_push( $wgDeferredUpdateList, $u );
1354 $u = new SearchUpdate( $id, $title, $text );
1355 array_push( $wgDeferredUpdateList, $u );
1356
1357 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(),
1358 $this->mTitle->getDBkey() );
1359 array_push( $wgDeferredUpdateList, $u );
1360
1361 if ( $this->getNamespace == NS_MEDIAWIKI ) {
1362 $messageCache = $wgMemc->get( "$wgDBname:messages" );
1363 if (!$messageCache) {
1364 $messageCache = wfLoadAllMessages();
1365 }
1366 $messageCache[$title] = $text;
1367 $wgMemc->set( "$wgDBname:messages" );
1368 }
1369 }
1370 }
1371
1372 /* private */ function setOldSubtitle()
1373 {
1374 global $wgLang, $wgOut;
1375
1376 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1377 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1378 $wgOut->setSubtitle( "({$r})" );
1379 }
1380
1381 function blockedIPpage()
1382 {
1383 global $wgOut, $wgUser, $wgLang;
1384
1385 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1386 $wgOut->setRobotpolicy( "noindex,nofollow" );
1387 $wgOut->setArticleFlag( false );
1388
1389 $id = $wgUser->blockedBy();
1390 $reason = $wgUser->blockedFor();
1391
1392 $name = User::whoIs( $id );
1393 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1394 ":{$name}|{$name}]]";
1395
1396 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1397 $text = str_replace( "$2", $reason, $text );
1398 $text = str_replace( "$3", getenv( "REMOTE_ADDR" ), $text );
1399 $wgOut->addWikiText( $text );
1400 $wgOut->returnToMain( false );
1401 }
1402
1403 # This function is called right before saving the wikitext,
1404 # so we can do things like signatures and links-in-context.
1405
1406 function preSaveTransform( $text )
1407 {
1408 $s = "";
1409 while ( "" != $text ) {
1410 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1411 $s .= $this->pstPass2( $p[0] );
1412
1413 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1414 else {
1415 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1416 $s .= "<nowiki>{$q[0]}</nowiki>";
1417 $text = $q[1];
1418 }
1419 }
1420 return rtrim( $s );
1421 }
1422
1423 /* private */ function pstPass2( $text )
1424 {
1425 global $wgUser, $wgLang, $wgLocaltimezone;
1426
1427 # Signatures
1428 #
1429 $n = $wgUser->getName();
1430 $k = $wgUser->getOption( "nickname" );
1431 if ( "" == $k ) { $k = $n; }
1432 if(isset($wgLocaltimezone)) {
1433 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1434 }
1435 /* Note: this is an ugly timezone hack for the European wikis */
1436 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1437 " (" . date( "T" ) . ")";
1438 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1439
1440 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1441 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1442 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1443 Namespace::getUser() ) . ":$n|$k]]", $text );
1444
1445 # Context links: [[|name]] and [[name (context)|]]
1446 #
1447 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1448 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1449 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1450 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1451
1452 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1453 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1454 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1455 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1456 # [[ns:page (cont)|]]
1457 $context = "";
1458 $t = $this->mTitle->getText();
1459 if ( preg_match( $conpat, $t, $m ) ) {
1460 $context = $m[2];
1461 }
1462 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1463 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1464 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1465
1466 if ( "" == $context ) {
1467 $text = preg_replace( $p2, "[[\\1]]", $text );
1468 } else {
1469 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1470 }
1471
1472 # {{SUBST:xxx}} variables
1473 #
1474 $mw =& MagicWord::get( MAG_SUBST );
1475 $text = $mw->substituteCallback( $text, "wfReplaceSubstVar" );
1476
1477 return $text;
1478 }
1479
1480 /* Caching functions */
1481
1482 function tryFileCache() {
1483 if($this->isFileCacheable()) {
1484 $touched = $this->mTouched;
1485 if( strpos( $this->mContent, "{{" ) !== false ) {
1486 # Expire pages with variable replacements in an hour
1487 $expire = wfUnix2Timestamp( time() - 3600 );
1488 $touched = max( $expire, $touched );
1489 }
1490 $cache = new CacheManager( $this->mTitle );
1491 if($cache->isFileCacheGood( $touched )) {
1492 global $wgOut;
1493 wfDebug( " tryFileCache() - about to load\n" );
1494 $cache->loadFromFileCache();
1495 $wgOut->reportTime(); # For profiling
1496 exit;
1497 } else {
1498 wfDebug( " tryFileCache() - starting buffer\n" );
1499 if($cache->useGzip() && wfClientAcceptsGzip()) {
1500 /* For some reason, adding this header line over in
1501 CacheManager::saveToFileCache() fails on my test
1502 setup at home, though it works on the live install.
1503 Make double-sure... --brion */
1504 header( "Content-Encoding: gzip" );
1505 }
1506 ob_start( array(&$cache, 'saveToFileCache' ) );
1507 }
1508 } else {
1509 wfDebug( " tryFileCache() - not cacheable\n" );
1510 }
1511 }
1512
1513 function isFileCacheable() {
1514 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1515 global $action, $oldid, $diff, $redirect, $printable;
1516 return $wgUseFileCache
1517 and (!$wgShowIPinHeader)
1518 and ($this->getID() != 0)
1519 and ($wgUser->getId() == 0)
1520 and (!$wgUser->getNewtalk())
1521 and ($this->mTitle->getNamespace != Namespace::getSpecial())
1522 and ($action == "view")
1523 and (!isset($oldid))
1524 and (!isset($diff))
1525 and (!isset($redirect))
1526 and (!isset($printable))
1527 and (!$this->mRedirectedFrom);
1528 }
1529
1530 function checkTouched() {
1531 $id = $this->getID();
1532 $sql = "SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id=$id";
1533 $res = wfQuery( $sql, DB_READ, "Article::checkTouched" );
1534 if( $s = wfFetchObject( $res ) ) {
1535 $this->mTouched = $s->cur_touched;
1536 return !$s->cur_is_redirect;
1537 } else {
1538 return false;
1539 }
1540 }
1541 }
1542
1543 function wfReplaceSubstVar( $matches ) {
1544 return wfMsg( $matches[1] );
1545 }
1546
1547 ?>