Experimental code for caching page links
[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 include_once( "CacheManager.php" );
9
10 class Article {
11 /* private */ var $mContent, $mContentLoaded;
12 /* private */ var $mUser, $mTimestamp, $mUserText;
13 /* private */ var $mCounter, $mComment, $mCountAdjustment;
14 /* private */ var $mMinorEdit, $mRedirectedFrom;
15 /* private */ var $mTouched, $mFileCache;
16
17 function Article( &$title ) {
18 $this->mTitle =& $title;
19 $this->clear();
20 }
21
22 /* private */ function clear()
23 {
24 $this->mContentLoaded = false;
25 $this->mUser = $this->mCounter = -1; # Not loaded
26 $this->mRedirectedFrom = $this->mUserText =
27 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
28 $this->mCountAdjustment = 0;
29 $this->mTouched = "19700101000000";
30 }
31
32 # Note that getContent/loadContent may follow redirects if
33 # not told otherwise, and so may cause a change to wgTitle.
34
35 function getContent( $noredir = false )
36 {
37 global $action,$section,$count; # From query string
38 $fname = "Article::getContent";
39 wfProfileIn( $fname );
40
41 if ( 0 == $this->getID() ) {
42 if ( "edit" == $action ) {
43 wfProfileOut( $fname );
44 return ""; # was "newarticletext", now moved above the box)
45 }
46 wfProfileOut( $fname );
47 return wfMsg( "noarticletext" );
48 } else {
49 $this->loadContent( $noredir );
50
51 if(
52 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
53 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
54 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$this->mTitle->getText()) &&
55 $action=="view"
56 )
57 {
58 wfProfileOut( $fname );
59 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
60 else {
61 if($action=="edit") {
62 if($section!="") {
63 if($section=="new") {
64 wfProfileOut( $fname );
65 return "";
66 }
67
68 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
69 $this->mContent, -1,
70 PREG_SPLIT_DELIM_CAPTURE);
71 if($section==0) {
72 wfProfileOut( $fname );
73 return trim($secs[0]);
74 } else {
75 wfProfileOut( $fname );
76 return trim($secs[$section*2-1] . $secs[$section*2]);
77 }
78 }
79 }
80 wfProfileOut( $fname );
81 return $this->mContent;
82 }
83 }
84 }
85
86 function loadContent( $noredir = false )
87 {
88 global $wgOut, $wgMwRedir;
89 global $oldid, $redirect; # From query
90
91 if ( $this->mContentLoaded ) return;
92 $fname = "Article::loadContent";
93
94 # Pre-fill content with error message so that if something
95 # fails we'll have something telling us what we intended.
96
97 $t = $this->mTitle->getPrefixedText();
98 if ( $oldid ) { $t .= ",oldid={$oldid}"; }
99 if ( $redirect ) { $t .= ",redirect={$redirect}"; }
100
101 $this->mContent = str_replace( "$1", $t, wfMsg( "missingarticle" ) );
102
103 if ( ! $oldid ) { # Retrieve current version
104 $id = $this->getID();
105 if ( 0 == $id ) return;
106
107 $sql = "SELECT " .
108 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
109 "FROM cur WHERE cur_id={$id}";
110 wfDebug( "$sql\n" );
111 $res = wfQuery( $sql, DB_READ, $fname );
112 if ( 0 == wfNumRows( $res ) ) {
113 return;
114 }
115
116 $s = wfFetchObject( $res );
117 # If we got a redirect, follow it (unless we've been told
118 # not to by either the function parameter or the query
119 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
120 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
121 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
122 $s->cur_text, $m ) ) {
123 $rt = Title::newFromText( $m[1] );
124
125 # Gotta hand redirects to special pages differently:
126 # Fill the HTTP response "Location" header and ignore
127 # the rest of the page we're on.
128
129 if ( $rt->getInterwiki() != "" ) {
130 $wgOut->redirect( $rt->getFullURL() ) ;
131 return;
132 }
133 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
134 $wgOut->redirect( wfLocalUrl(
135 $rt->getPrefixedURL() ) );
136 return;
137 }
138 $rid = $rt->getArticleID();
139 if ( 0 != $rid ) {
140 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
141 "cur_counter,cur_touched FROM cur WHERE cur_id={$rid}";
142 $res = wfQuery( $sql, DB_READ, $fname );
143
144 if ( 0 != wfNumRows( $res ) ) {
145 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
146 $this->mTitle = $rt;
147 $s = wfFetchObject( $res );
148 }
149 }
150 }
151 }
152
153 $this->mContent = $s->cur_text;
154 $this->mUser = $s->cur_user;
155 $this->mCounter = $s->cur_counter;
156 $this->mTimestamp = $s->cur_timestamp;
157 $this->mTouched = $s->cur_touched;
158 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
159 $this->mTitle->mRestrictionsLoaded = true;
160 wfFreeResult( $res );
161 } else { # oldid set, retrieve historical version
162 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
163 "WHERE old_id={$oldid}";
164 $res = wfQuery( $sql, DB_READ, $fname );
165 if ( 0 == wfNumRows( $res ) ) { return; }
166
167 $s = wfFetchObject( $res );
168 $this->mContent = $s->old_text;
169 $this->mUser = $s->old_user;
170 $this->mCounter = 0;
171 $this->mTimestamp = $s->old_timestamp;
172 wfFreeResult( $res );
173 }
174 $this->mContentLoaded = true;
175 }
176
177 function getID() { return $this->mTitle->getArticleID(); }
178
179 function getCount()
180 {
181 if ( -1 == $this->mCounter ) {
182 $id = $this->getID();
183 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
184 }
185 return $this->mCounter;
186 }
187
188 # Would the given text make this article a "good" article (i.e.,
189 # suitable for including in the article count)?
190
191 function isCountable( $text )
192 {
193 global $wgUseCommaCount, $wgMwRedir;
194
195 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
196 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
197 $token = ($wgUseCommaCount ? "," : "[[" );
198 if ( false === strstr( $text, $token ) ) { return 0; }
199 return 1;
200 }
201
202 # Load the field related to the last edit time of the article.
203 # This isn't necessary for all uses, so it's only done if needed.
204
205 /* private */ function loadLastEdit()
206 {
207 global $wgOut;
208 if ( -1 != $this->mUser ) return;
209
210 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
211 "cur_comment,cur_minor_edit FROM cur WHERE " .
212 "cur_id=" . $this->getID();
213 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
214
215 if ( wfNumRows( $res ) > 0 ) {
216 $s = wfFetchObject( $res );
217 $this->mUser = $s->cur_user;
218 $this->mUserText = $s->cur_user_text;
219 $this->mTimestamp = $s->cur_timestamp;
220 $this->mComment = $s->cur_comment;
221 $this->mMinorEdit = $s->cur_minor_edit;
222 }
223 }
224
225 function getTimestamp()
226 {
227 $this->loadLastEdit();
228 return $this->mTimestamp;
229 }
230
231 function getUser()
232 {
233 $this->loadLastEdit();
234 return $this->mUser;
235 }
236
237 function getUserText()
238 {
239 $this->loadLastEdit();
240 return $this->mUserText;
241 }
242
243 function getComment()
244 {
245 $this->loadLastEdit();
246 return $this->mComment;
247 }
248
249 function getMinorEdit()
250 {
251 $this->loadLastEdit();
252 return $this->mMinorEdit;
253 }
254
255 # This is the default action of the script: just view the page of
256 # the given title.
257
258 function view()
259 {
260 global $wgUser, $wgOut, $wgLang;
261 global $oldid, $diff; # From query
262 global $wgLinkCache, $IP;
263 $fname = "Article::view";
264 wfProfileIn( $fname );
265
266 $wgOut->setArticleFlag( true );
267 $wgOut->setRobotpolicy( "index,follow" );
268
269 # If we got diff and oldid in the query, we want to see a
270 # diff page instead of the article.
271
272 if ( isset( $diff ) ) {
273 include_once( "$IP/DifferenceEngine.php" );
274 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
275 $de = new DifferenceEngine( $oldid, $diff );
276 $de->showDiffPage();
277 wfProfileOut( $fname );
278 return;
279 }
280 $text = $this->getContent(); # May change wgTitle!
281 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
282 $wgOut->setHTMLTitle( $this->mTitle->getPrefixedText() .
283 " - " . wfMsg( "wikititlesuffix" ) );
284
285 # We're looking at an old revision
286
287 if ( $oldid ) {
288 $this->setOldSubtitle();
289 $wgOut->setRobotpolicy( "noindex,follow" );
290 }
291 if ( "" != $this->mRedirectedFrom ) {
292 $sk = $wgUser->getSkin();
293 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
294 "redirect=no" );
295 $s = str_replace( "$1", $redir, wfMsg( "redirectedfrom" ) );
296 $wgOut->setSubtitle( $s );
297 }
298 $wgOut->checkLastModified( $this->mTouched );
299 $this->tryFileCache();
300 $wgLinkCache->preFill( $this->mTitle );
301 $wgOut->addWikiText( $text );
302
303 $this->viewUpdates();
304 wfProfileOut( $fname );
305 }
306
307 # Theoretically we could defer these whole insert and update
308 # functions for after display, but that's taking a big leap
309 # of faith, and we want to be able to report database
310 # errors at some point.
311
312 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
313 {
314 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
315 $fname = "Article::insertNewArticle";
316
317 $ns = $this->mTitle->getNamespace();
318 $ttl = $this->mTitle->getDBkey();
319 $text = $this->preSaveTransform( $text );
320 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
321 else { $redir = 0; }
322
323 $now = wfTimestampNow();
324 $won = wfInvertTimestamp( $now );
325 wfSeedRandom();
326 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
327 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
328 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
329 "cur_restrictions,cur_user_text,cur_is_redirect," .
330 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
331 wfStrencode( $text ) . "', '" .
332 wfStrencode( $summary ) . "', '" .
333 $wgUser->getID() . "', '{$now}', " .
334 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
335 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
336 $res = wfQuery( $sql, DB_WRITE, $fname );
337
338 $newid = wfInsertId();
339 $this->mTitle->resetArticleID( $newid );
340
341 // Purge related entries in links cache on new page, to heal broken links
342 $ptitle = wfStrencode( $ttl );
343 wfQuery("DELETE linkscc FROM linkscc,brokenlinks ".
344 "WHERE lcc_pageid=bl_from AND bl_to='{$ptitle}'", DB_WRITE);
345
346 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
347 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
348 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
349 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
350 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
351 wfStrencode( $wgUser->getName() ) . "','" .
352 wfStrencode( $summary ) . "',0,0," .
353 ( $wgUser->isBot() ? 1 : 0 ) . ")";
354 wfQuery( $sql, DB_WRITE, $fname );
355 if ($watchthis) {
356 if(!$this->mTitle->userIsWatching()) $this->watch();
357 } else {
358 if ( $this->mTitle->userIsWatching() ) {
359 $this->unwatch();
360 }
361 }
362
363 $this->showArticle( $text, wfMsg( "newarticle" ) );
364 }
365
366 function updateArticle( $text, $summary, $minor, $watchthis, $section="" )
367 {
368 global $wgOut, $wgUser, $wgLinkCache;
369 global $wgDBtransactions, $wgMwRedir;
370 $fname = "Article::updateArticle";
371
372 $this->loadLastEdit();
373
374 // insert updated section into old text if we have only edited part
375 // of the article
376 if ($section != "") {
377 $oldtext=$this->getContent();
378 if($section=="new") {
379 if($summary) $subject="== {$summary} ==\n\n";
380 $text=$oldtext."\n\n".$subject.$text;
381 } else {
382 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
383 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
384 $secs[$section*2]=$text."\n\n"; // replace with edited
385 if($section) { $secs[$section*2-1]=""; } // erase old headline
386 $text=join("",$secs);
387 }
388 }
389 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
390 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
391 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
392 $redir = 1;
393 $text = $m[1] . "\n"; # Remove all content but redirect
394 }
395 else { $redir = 0; }
396
397 $text = $this->preSaveTransform( $text );
398
399 # Update article, but only if changed.
400
401 if( $wgDBtransactions ) {
402 $sql = "BEGIN";
403 wfQuery( $sql, DB_WRITE );
404 }
405 $oldtext = $this->getContent( true );
406
407 if ( 0 != strcmp( $text, $oldtext ) ) {
408 $this->mCountAdjustment = $this->isCountable( $text )
409 - $this->isCountable( $oldtext );
410
411 $now = wfTimestampNow();
412 $won = wfInvertTimestamp( $now );
413 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
414 "',cur_comment='" . wfStrencode( $summary ) .
415 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
416 ",cur_timestamp='{$now}',cur_user_text='" .
417 wfStrencode( $wgUser->getName() ) .
418 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
419 "WHERE cur_id=" . $this->getID() .
420 " AND cur_timestamp='" . $this->getTimestamp() . "'";
421 $res = wfQuery( $sql, DB_WRITE, $fname );
422
423 if( wfAffectedRows() == 0 ) {
424 /* Belated edit conflict! Run away!! */
425 return false;
426 }
427
428 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
429 "old_comment,old_user,old_user_text,old_timestamp," .
430 "old_minor_edit,inverse_timestamp) VALUES (" .
431 $this->mTitle->getNamespace() . ", '" .
432 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
433 wfStrencode( $oldtext ) . "', '" .
434 wfStrencode( $this->getComment() ) . "', " .
435 $this->getUser() . ", '" .
436 wfStrencode( $this->getUserText() ) . "', '" .
437 $this->getTimestamp() . "', " . $me1 . ", '" .
438 wfInvertTimestamp( $this->getTimestamp() ) . "')";
439 $res = wfQuery( $sql, DB_WRITE, $fname );
440 $oldid = wfInsertID( $res );
441
442 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
443 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
444 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
445 "'{$now}','{$now}'," . $this->mTitle->getNamespace() . ",'" .
446 wfStrencode( $this->mTitle->getDBkey() ) . "',0,{$me2}," .
447 ( $wgUser->isBot() ? 1 : 0 ) . "," .
448 $this->getID() . "," . $wgUser->getID() . ",'" .
449 wfStrencode( $wgUser->getName() ) . "','" .
450 wfStrencode( $summary ) . "',0,{$oldid})";
451 wfQuery( $sql, DB_WRITE, $fname );
452
453 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
454 "WHERE rc_namespace=" . $this->mTitle->getNamespace() . " AND " .
455 "rc_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' AND " .
456 "rc_timestamp='" . $this->getTimestamp() . "'";
457 wfQuery( $sql, DB_WRITE, $fname );
458
459 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
460 "WHERE rc_cur_id=" . $this->getID();
461 wfQuery( $sql, DB_WRITE, $fname );
462
463 // Purge related entries in link cache when a page change
464 // (probably just affects anything when article changes stub state)
465 $pageid=$this->getID();
466 wfQuery("DELETE linkscc FROM linkscc,links ".
467 "WHERE lcc_title=links.l_from AND l_to={$pageid}", DB_WRITE);
468
469 }
470 if( $wgDBtransactions ) {
471 $sql = "COMMIT";
472 wfQuery( $sql, DB_WRITE );
473 }
474
475 if ($watchthis) {
476 if (!$this->mTitle->userIsWatching()) $this->watch();
477 } else {
478 if ( $this->mTitle->userIsWatching() ) {
479 $this->unwatch();
480 }
481 }
482
483 $this->showArticle( $text, wfMsg( "updated" ) );
484 return true;
485 }
486
487 # After we've either updated or inserted the article, update
488 # the link tables and redirect to the new page.
489
490 function showArticle( $text, $subtitle )
491 {
492 global $wgOut, $wgUser, $wgLinkCache, $wgUseBetterLinksUpdate;
493 global $wgMwRedir;
494
495 $wgLinkCache = new LinkCache();
496
497 # Get old version of link table to allow incremental link updates
498 if ( $wgUseBetterLinksUpdate ) {
499 $wgLinkCache->preFill( $this->mTitle );
500 $wgLinkCache->clear();
501 }
502
503 # Now update the link cache by parsing the text
504 $wgOut = new OutputPage();
505 $wgOut->addWikiText( $text );
506
507 $this->editUpdates( $text );
508 if( $wgMwRedir->matchStart( $text ) )
509 $r = "redirect=no";
510 else
511 $r = "";
512 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL(), $r ) );
513 }
514
515 # Add this page to my watchlist
516
517 function watch( $add = true )
518 {
519 global $wgUser, $wgOut, $wgLang;
520 global $wgDeferredUpdateList;
521
522 if ( 0 == $wgUser->getID() ) {
523 $wgOut->errorpage( "watchnologin", "watchnologintext" );
524 return;
525 }
526 if ( wfReadOnly() ) {
527 $wgOut->readOnlyPage();
528 return;
529 }
530 if( $add )
531 $wgUser->addWatch( $this->mTitle );
532 else
533 $wgUser->removeWatch( $this->mTitle );
534
535 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
536 $wgOut->setRobotpolicy( "noindex,follow" );
537
538 $sk = $wgUser->getSkin() ;
539 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
540
541 if($add)
542 $text = wfMsg( "addedwatchtext", $link );
543 else
544 $text = wfMsg( "removedwatchtext", $link );
545 $wgOut->addHTML( $text );
546
547 $up = new UserUpdate();
548 array_push( $wgDeferredUpdateList, $up );
549
550 $wgOut->returnToMain( false );
551 }
552
553 function unwatch()
554 {
555 $this->watch( false );
556 }
557
558 # This shares a lot of issues (and code) with Recent Changes
559
560 function history()
561 {
562 global $wgUser, $wgOut, $wgLang, $offset, $limit;
563
564 # If page hasn't changed, client can cache this
565
566 $wgOut->checkLastModified( $this->getTimestamp() );
567 $fname = "Article::history";
568 wfProfileIn( $fname );
569
570 $wgOut->setPageTitle( $this->mTitle->getPRefixedText() );
571 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
572 $wgOut->setArticleFlag( false );
573 $wgOut->setRobotpolicy( "noindex,nofollow" );
574
575 if( $this->mTitle->getArticleID() == 0 ) {
576 $wgOut->addHTML( wfMsg( "nohistory" ) );
577 wfProfileOut( $fname );
578 return;
579 }
580
581 $offset = (int)$offset;
582 $limit = (int)$limit;
583 if( $limit == 0 ) $limit = 50;
584 $namespace = $this->mTitle->getNamespace();
585 $title = $this->mTitle->getText();
586 $sql = "SELECT old_id,old_user," .
587 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
588 "FROM old USE INDEX (name_title_timestamp) " .
589 "WHERE old_namespace={$namespace} AND " .
590 "old_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' " .
591 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
592 $res = wfQuery( $sql, DB_READ, "Article::history" );
593
594 $revs = wfNumRows( $res );
595 if( $this->mTitle->getArticleID() == 0 ) {
596 $wgOut->addHTML( wfMsg( "nohistory" ) );
597 wfProfileOut( $fname );
598 return;
599 }
600
601 $sk = $wgUser->getSkin();
602 $numbar = wfViewPrevNext(
603 $offset, $limit,
604 $this->mTitle->getPrefixedText(),
605 "action=history" );
606 $s = $numbar;
607 $s .= $sk->beginHistoryList();
608
609 if($offset == 0 )
610 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
611 $this->getUserText(), $namespace,
612 $title, 0, $this->getComment(),
613 ( $this->getMinorEdit() > 0 ) );
614
615 $revs = wfNumRows( $res );
616 while ( $line = wfFetchObject( $res ) ) {
617 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
618 $line->old_user_text, $namespace,
619 $title, $line->old_id,
620 $line->old_comment, ( $line->old_minor_edit > 0 ) );
621 }
622 $s .= $sk->endHistoryList();
623 $s .= $numbar;
624 $wgOut->addHTML( $s );
625 wfProfileOut( $fname );
626 }
627
628 function protect( $limit = "sysop" )
629 {
630 global $wgUser, $wgOut;
631
632 if ( ! $wgUser->isSysop() ) {
633 $wgOut->sysopRequired();
634 return;
635 }
636 if ( wfReadOnly() ) {
637 $wgOut->readOnlyPage();
638 return;
639 }
640 $id = $this->mTitle->getArticleID();
641 if ( 0 == $id ) {
642 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
643 return;
644 }
645 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
646 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
647 wfQuery( $sql, DB_WRITE, "Article::protect" );
648
649 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL() ) );
650 }
651
652 function unprotect()
653 {
654 return $this->protect( "" );
655 }
656
657 function delete()
658 {
659 global $wgUser, $wgOut;
660 global $wpConfirm, $wpReason, $image, $oldimage;
661
662 # Anybody can delete old revisions of images; only sysops
663 # can delete articles and current images
664
665 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
666 $wgOut->sysopRequired();
667 return;
668 }
669 if ( wfReadOnly() ) {
670 $wgOut->readOnlyPage();
671 return;
672 }
673
674 # Better double-check that it hasn't been deleted yet!
675 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
676 if ( ( "" == trim( $this->mTitle->getText() ) )
677 or ( $this->mTitle->getArticleId() == 0 ) ) {
678 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
679 return;
680 }
681
682 # determine whether this page has earlier revisions
683 # and insert a warning if it does
684 # we select the text because it might be useful below
685 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
686 $res=wfQuery($sql, DB_READ, $fname);
687 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
688 $skin=$wgUser->getSkin();
689 $wgOut->addHTML("<B>".wfMsg("historywarning"));
690 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
691 }
692
693 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."'";
694 $res=wfQuery($sql, DB_READ, $fname);
695 if( ($s=wfFetchObject($res))) {
696
697 # if this is a mini-text, we can paste part of it into the deletion reason
698
699 #if this is empty, an earlier revision may contain "useful" text
700 if($s->cur_text!="") {
701 $text=$s->cur_text;
702 } else {
703 if($old) {
704 $text=$old->old_text;
705 $blanked=1;
706 }
707
708 }
709
710 $length=strlen($text);
711
712 # this should not happen, since it is not possible to store an empty, new
713 # page. Let's insert a standard text in case it does, though
714 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
715
716
717 if($length < 500 && !$wpReason) {
718
719 # comment field=255, let's grep the first 150 to have some user
720 # space left
721 $text=substr($text,0,150);
722 # let's strip out newlines and HTML tags
723 $text=preg_replace("/\"/","'",$text);
724 $text=preg_replace("/\</","&lt;",$text);
725 $text=preg_replace("/\>/","&gt;",$text);
726 $text=preg_replace("/[\n\r]/","",$text);
727 if(!$blanked) {
728 $wpReason=wfMsg("excontent"). " '".$text;
729 } else {
730 $wpReason=wfMsg("exbeforeblank") . " '".$text;
731 }
732 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
733 $wpReason.="'";
734 }
735 }
736
737 return $this->confirmDelete();
738 }
739
740 function confirmDelete( $par = "" )
741 {
742 global $wgOut;
743
744 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
745 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
746 $wgOut->setRobotpolicy( "noindex,nofollow" );
747 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
748
749 $t = $this->mTitle->getPrefixedURL();
750
751 $formaction = wfEscapeHTML( wfLocalUrl( $t, "action=delete" . $par ) );
752 $confirm = wfMsg( "confirm" );
753 $check = wfMsg( "confirmcheck" );
754 $delcom = wfMsg( "deletecomment" );
755
756 $wgOut->addHTML( "
757 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
758 <table border=0><tr><td align=right>
759 {$delcom}:</td><td align=left>
760 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
761 </td></tr><tr><td>&nbsp;</td></tr>
762 <tr><td align=right>
763 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
764 </td><td><label for=\"wpConfirm\">{$check}</label></td>
765 </tr><tr><td>&nbsp;</td><td>
766 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
767 </td></tr></table></form>\n" );
768
769 $wgOut->returnToMain( false );
770 }
771
772 function doDelete()
773 {
774 global $wgOut, $wgUser, $wgLang;
775 global $wpReason;
776 $fname = "Article::doDelete";
777
778 $this->doDeleteArticle( $this->mTitle );
779 $deleted = $this->mTitle->getPrefixedText();
780
781 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
782 $wgOut->setRobotpolicy( "noindex,nofollow" );
783
784 $sk = $wgUser->getSkin();
785 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
786 Namespace::getWikipedia() ) .
787 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
788
789 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
790 $text = str_replace( "$2", $loglink, $text );
791
792 $wgOut->addHTML( "<p>" . $text );
793 $wgOut->returnToMain( false );
794 }
795
796 function doDeleteArticle( $title )
797 {
798 global $wgUser, $wgOut, $wgLang, $wpReason, $wgDeferredUpdateList;
799
800 $fname = "Article::doDeleteArticle";
801 $ns = $title->getNamespace();
802 $t = wfStrencode( $title->getDBkey() );
803 $id = $title->getArticleID();
804
805 if ( "" == $t ) {
806 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
807 return;
808 }
809
810 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
811 array_push( $wgDeferredUpdateList, $u );
812
813 # Move article and history to the "archive" table
814 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
815 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
816 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
817 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
818 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
819 wfQuery( $sql, DB_WRITE, $fname );
820
821 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
822 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
823 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
824 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
825 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
826 wfQuery( $sql, DB_WRITE, $fname );
827
828 # Now that it's safely backed up, delete it
829
830 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
831 "cur_title='{$t}'";
832 wfQuery( $sql, DB_WRITE, $fname );
833
834 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
835 "old_title='{$t}'";
836 wfQuery( $sql, DB_WRITE, $fname );
837
838 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
839 "rc_title='{$t}'";
840 wfQuery( $sql, DB_WRITE, $fname );
841
842 # Finally, clean up the link tables
843
844 if ( 0 != $id ) {
845
846 // Purge related entries in links cache on delete,
847 wfQuery("DELETE linkscc FROM linkscc,links ".
848 "WHERE lcc_title=links.l_from AND l_to={$id}", DB_WRITE);
849 wfQuery("DELETE FROM linkscc WHERE lcc_title='{$t}'", DB_WRITE);
850
851 $t = wfStrencode( $title->getPrefixedDBkey() );
852 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
853 $res = wfQuery( $sql, DB_READ, $fname );
854
855 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
856 $now = wfTimestampNow();
857 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
858 $first = true;
859
860 while ( $s = wfFetchObject( $res ) ) {
861 $nt = Title::newFromDBkey( $s->l_from );
862 $lid = $nt->getArticleID();
863
864 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
865 $first = false;
866 $sql .= "({$lid},'{$t}')";
867 $sql2 .= "{$lid}";
868 }
869 $sql2 .= ")";
870 if ( ! $first ) {
871 wfQuery( $sql, DB_WRITE, $fname );
872 wfQuery( $sql2, DB_WRITE, $fname );
873 }
874 wfFreeResult( $res );
875
876 $sql = "DELETE FROM links WHERE l_to={$id}";
877 wfQuery( $sql, DB_WRITE, $fname );
878
879 $sql = "DELETE FROM links WHERE l_from='{$t}'";
880 wfQuery( $sql, DB_WRITE, $fname );
881
882 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
883 wfQuery( $sql, DB_WRITE, $fname );
884
885 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
886 wfQuery( $sql, DB_WRITE, $fname );
887 }
888
889 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
890 $art = $title->getPrefixedText();
891 $wpReason = wfCleanQueryVar( $wpReason );
892 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
893
894 # Clear the cached article id so the interface doesn't act like we exist
895 $this->mTitle->resetArticleID( 0 );
896 $this->mTitle->mArticleID = 0;
897 }
898
899 function rollback()
900 {
901 global $wgUser, $wgLang, $wgOut, $from;
902
903 if ( ! $wgUser->isSysop() ) {
904 $wgOut->sysopRequired();
905 return;
906 }
907
908 # Replace all this user's current edits with the next one down
909 $tt = wfStrencode( $this->mTitle->getDBKey() );
910 $n = $this->mTitle->getNamespace();
911
912 # Get the last editor
913 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
914 $res = wfQuery( $sql, DB_READ );
915 if( ($x = wfNumRows( $res )) != 1 ) {
916 # Something wrong
917 $wgOut->addHTML( wfMsg( "notanarticle" ) );
918 return;
919 }
920 $s = wfFetchObject( $res );
921 $ut = wfStrencode( $s->cur_user_text );
922 $uid = $s->cur_user;
923 $pid = $s->cur_id;
924
925 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
926 if( $from != $s->cur_user_text ) {
927 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
928 $wgOut->addWikiText( wfMsg( "alreadyrolled",
929 htmlspecialchars( $this->mTitle->getPrefixedText()),
930 htmlspecialchars( $from ),
931 htmlspecialchars( $s->cur_user_text ) ) );
932 if($s->cur_comment != "") {
933 $wgOut->addHTML(
934 wfMsg("editcomment",
935 htmlspecialchars( $s->cur_comment ) ) );
936 }
937 return;
938 }
939
940 # Get the last edit not by this guy
941 $sql = "SELECT old_text,old_user,old_user_text
942 FROM old USE INDEX (name_title_timestamp)
943 WHERE old_namespace={$n} AND old_title='{$tt}'
944 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
945 ORDER BY inverse_timestamp LIMIT 1";
946 $res = wfQuery( $sql, DB_READ );
947 if( wfNumRows( $res ) != 1 ) {
948 # Something wrong
949 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
950 $wgOut->addHTML( wfMsg( "cantrollback" ) );
951 return;
952 }
953 $s = wfFetchObject( $res );
954
955 # Save it!
956 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
957 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
958 $wgOut->setRobotpolicy( "noindex,nofollow" );
959 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
960 $this->updateArticle( $s->old_text, $newcomment, 1, $this->mTitle->userIsWatching() );
961
962 $wgOut->returnToMain( false );
963 }
964
965
966 # Do standard deferred updates after page view
967
968 /* private */ function viewUpdates()
969 {
970 global $wgDeferredUpdateList;
971
972 if ( 0 != $this->getID() ) {
973 $u = new ViewCountUpdate( $this->getID() );
974 array_push( $wgDeferredUpdateList, $u );
975 $u = new SiteStatsUpdate( 1, 0, 0 );
976 array_push( $wgDeferredUpdateList, $u );
977
978 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
979 $this->mTitle->getDBkey() );
980 array_push( $wgDeferredUpdateList, $u );
981 }
982 }
983
984 # Do standard deferred updates after page edit.
985 # Every 1000th edit, prune the recent changes table.
986
987 /* private */ function editUpdates( $text )
988 {
989 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
990
991 wfSeedRandom();
992 if ( 0 == mt_rand( 0, 999 ) ) {
993 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
994 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
995 wfQuery( $sql, DB_WRITE );
996 }
997 $id = $this->getID();
998 $title = $this->mTitle->getPrefixedDBkey();
999 $adj = $this->mCountAdjustment;
1000
1001 if ( 0 != $id ) {
1002 $u = new LinksUpdate( $id, $title );
1003 array_push( $wgDeferredUpdateList, $u );
1004 $u = new SiteStatsUpdate( 0, 1, $adj );
1005 array_push( $wgDeferredUpdateList, $u );
1006 $u = new SearchUpdate( $id, $title, $text );
1007 array_push( $wgDeferredUpdateList, $u );
1008
1009 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(),
1010 $this->mTitle->getDBkey() );
1011 array_push( $wgDeferredUpdateList, $u );
1012
1013 if ( $this->getNamespace == NS_MEDIAWIKI ) {
1014 $messageCache = $wgMemc->get( "$wgDBname:messages" );
1015 if (!$messageCache) {
1016 $messageCache = wfLoadAllMessages();
1017 }
1018 $messageCache[$title] = $text;
1019 $wgMemc->set( "$wgDBname:messages" );
1020 }
1021 }
1022 }
1023
1024 /* private */ function setOldSubtitle()
1025 {
1026 global $wgLang, $wgOut;
1027
1028 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1029 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1030 $wgOut->setSubtitle( "({$r})" );
1031 }
1032
1033 # This function is called right before saving the wikitext,
1034 # so we can do things like signatures and links-in-context.
1035
1036 function preSaveTransform( $text )
1037 {
1038 $s = "";
1039 while ( "" != $text ) {
1040 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1041 $s .= $this->pstPass2( $p[0] );
1042
1043 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1044 else {
1045 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1046 $s .= "<nowiki>{$q[0]}</nowiki>";
1047 $text = $q[1];
1048 }
1049 }
1050 return rtrim( $s );
1051 }
1052
1053 /* private */ function pstPass2( $text )
1054 {
1055 global $wgUser, $wgLang, $wgLocaltimezone;
1056
1057 # Signatures
1058 #
1059 $n = $wgUser->getName();
1060 $k = $wgUser->getOption( "nickname" );
1061 if ( "" == $k ) { $k = $n; }
1062 if(isset($wgLocaltimezone)) {
1063 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1064 }
1065 /* Note: this is an ugly timezone hack for the European wikis */
1066 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1067 " (" . date( "T" ) . ")";
1068 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1069
1070 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1071 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1072 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1073 Namespace::getUser() ) . ":$n|$k]]", $text );
1074
1075 # Context links: [[|name]] and [[name (context)|]]
1076 #
1077 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1078 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1079 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1080
1081 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1082 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1083 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1084 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1085 # [[ns:page (cont)|]]
1086 $context = "";
1087 $t = $this->mTitle->getText();
1088 if ( preg_match( $conpat, $t, $m ) ) {
1089 $context = $m[2];
1090 }
1091 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1092 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1093 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1094
1095 if ( "" == $context ) {
1096 $text = preg_replace( $p2, "[[\\1]]", $text );
1097 } else {
1098 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1099 }
1100
1101 # {{SUBST:xxx}} variables
1102 #
1103 $mw =& MagicWord::get( MAG_SUBST );
1104 $text = $mw->substituteCallback( $text, "wfReplaceSubstVar" );
1105
1106 return $text;
1107 }
1108
1109 /* Caching functions */
1110
1111 function tryFileCache() {
1112 if($this->isFileCacheable()) {
1113 $touched = $this->mTouched;
1114 if( strpos( $this->mContent, "{{" ) !== false ) {
1115 # Expire pages with variable replacements in an hour
1116 $expire = wfUnix2Timestamp( time() - 3600 );
1117 $touched = max( $expire, $touched );
1118 }
1119 $cache = new CacheManager( $this->mTitle );
1120 if($cache->isFileCacheGood( $touched )) {
1121 wfDebug( " tryFileCache() - about to load\n" );
1122 $cache->loadFromFileCache();
1123 exit;
1124 } else {
1125 wfDebug( " tryFileCache() - starting buffer\n" );
1126 if($cache->useGzip() && wfClientAcceptsGzip()) {
1127 /* For some reason, adding this header line over in
1128 CacheManager::saveToFileCache() fails on my test
1129 setup at home, though it works on the live install.
1130 Make double-sure... --brion */
1131 header( "Content-Encoding: gzip" );
1132 }
1133 ob_start( array(&$cache, 'saveToFileCache' ) );
1134 }
1135 } else {
1136 wfDebug( " tryFileCache() - not cacheable\n" );
1137 }
1138 }
1139
1140 function isFileCacheable() {
1141 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1142 global $action, $oldid, $diff, $redirect, $printable;
1143 return $wgUseFileCache
1144 and (!$wgShowIPinHeader)
1145 and ($this->getID() != 0)
1146 and ($wgUser->getId() == 0)
1147 and (!$wgUser->getNewtalk())
1148 and ($this->mTitle->getNamespace != Namespace::getSpecial())
1149 and ($action == "view")
1150 and (!isset($oldid))
1151 and (!isset($diff))
1152 and (!isset($redirect))
1153 and (!isset($printable))
1154 and (!$this->mRedirectedFrom);
1155
1156 }
1157
1158
1159 }
1160
1161 function wfReplaceSubstVar( $matches ) {
1162 return wfMsg( $matches[1] );
1163 }
1164
1165 ?>