71ffb693ab8bd47cb181b83e26eea08bc5e53e98
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
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 require_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, $mTitle;
16 /* private */ var $mId, $mTable;
17
18 function Article( &$title ) {
19 $this->mTitle =& $title;
20 $this->clear();
21 }
22
23 /* private */ function clear()
24 {
25 $this->mContentLoaded = false;
26 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
27 $this->mRedirectedFrom = $this->mUserText =
28 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
29 $this->mCountAdjustment = 0;
30 $this->mTouched = "19700101000000";
31 }
32
33 /* static */ function getRevisionText( $row, $prefix = "old_" ) {
34 # Deal with optional compression of archived pages.
35 # This can be done periodically via maintenance/compressOld.php, and
36 # as pages are saved if $wgCompressRevisions is set.
37 $text = $prefix . "text";
38 $flags = $prefix . "flags";
39 if( isset( $row->$flags ) && (false !== strpos( $row->$flags, "gzip" ) ) ) {
40 return gzinflate( $row->$text );
41 }
42 if( isset( $row->$text ) ) {
43 return $row->$text;
44 }
45 return false;
46 }
47
48 /* static */ function compressRevisionText( &$text ) {
49 global $wgCompressRevisions;
50 if( !$wgCompressRevisions ) {
51 return "";
52 }
53 if( !function_exists( "gzdeflate" ) ) {
54 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
55 return "";
56 }
57 $text = gzdeflate( $text );
58 return "gzip";
59 }
60
61 # Note that getContent/loadContent may follow redirects if
62 # not told otherwise, and so may cause a change to mTitle.
63
64 # Return the text of this revision
65 function getContent( $noredir )
66 {
67 global $wgRequest,$wgUser,$wgOut;
68
69 $fname = "Article::getContent";
70 wfProfileIn( $fname );
71
72 # Get variables from query string :P
73 $action = $wgRequest->getText( 'action', 'view' );
74 $section = $wgRequest->getText( 'section' );
75 $sectiontitle = $wgRequest->getText( 'sectiontitle' );
76 $oid = $wgRequest->getInt( 'oldid' );
77
78 if ( 0 == $this->getID() ) {
79 if ( "edit" == $action ) {
80 wfProfileOut( $fname );
81 return ""; # was "newarticletext", now moved above the box)
82 }
83 wfProfileOut( $fname );
84 return wfMsg( "noarticletext" );
85 } else {
86 $this->loadContent( $noredir );
87
88 # size threshold at which pages are automatically collapsed
89 $collapsethreshold=$wgUser->getOption( "collapsethreshold" );
90 if($collapsethreshold && strlen($this->mContent)>=$collapsethreshold) {
91 $collapse=true;
92 } else {
93 $collapse=false;
94 }
95 #override user pref is expansion is explicitly requested
96 if($wgRequest->getBool('collapse')) { $collapse=true; }
97 if( $wgRequest->getText( 'collapse' ) == 'false') {
98 $collapse=false;
99 }
100 if($oid) { $collapse=false; }
101 $wgOut->setCollapse($collapse);
102
103 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
104 # if so, a "This is an anonymous talk page .." message must be appended to the
105 # displayed page (but not during editing!).
106 $anontalk=false;
107 if( ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
108 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$this->mTitle->getText()) &&
109 $action=="view"
110 ) { $anontalk=true; }
111
112 # When a page is viewed in collapsed mode, only the intro section and, for
113 # pages with multiple sections, a table of contents are shown.
114 if($collapse && $action=="view" && $section=="") {
115 $rv=$this->getSection($this->mContent,0,$sectiontitle);
116 $wgOut->setToc(Parser::getTocFromSource($this->mContent));
117 if($anontalk) { $rv = $rv . "\n" . wfMsg("anontalkpage"); }
118 wfProfileOut( $fname );
119 return $rv;
120 }
121 # $section contains a section number and is used for section viewing and editing.
122 if($section!="") {
123 if($section=="new" && $action=="edit") {
124 wfProfileOut( $fname );
125 return "";
126 }
127 $rv=$this->getSection($this->mContent,$section,$sectiontitle);
128 if($anontalk) { $rv = $rv . "\n" . wfMsg("anontalkpage"); }
129 wfProfileOut( $fname );
130 return $rv;
131 }
132 }
133
134 if($anontalk) { return $this->mContent . "\n" . wfMsg("anontalkpage"); }
135 wfProfileOut( $fname );
136 return $this->mContent;
137
138 }
139
140 # This function returns the text of a section, specified by a number ($section)
141 # and a section title ($sectiontitle). A section is text under a heading like
142 # == Heading == or <h1>Heading</h1>, or the first section before any such
143 # heading (section 0).
144 #
145 # If a section contains subsections, these are also returned.
146 #
147 function getSection($text,$section,$sectiontitle) {
148
149 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
150 # comments to be stripped as well)
151 $striparray=array();
152 $parser=new Parser();
153 $parser->mOutputType=OT_WIKI;
154 $striptext=$parser->strip($text, $striparray, true);
155
156 # now that we can be sure that no pseudo-sections are in the source,
157 # split it up by section
158 $secs =
159 preg_split(
160 "/(^=+.*?=+|^<h[1-6].*?" . ">.*?<\/h[1-6].*?" . ">)/mi",
161 $striptext, -1,
162 PREG_SPLIT_DELIM_CAPTURE);
163 if($section==0) {
164 $rv=$secs[0];
165 } else {
166 $headline=$secs[$section*2-1];
167 preg_match( "/^(=+).*?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>/mi",$headline,$matches);
168 $hlevel=$matches[1];
169
170 # translate wiki heading into level
171 if(strpos($hlevel,"=")!==false) {
172 $hlevel=strlen($hlevel);
173 }
174
175 $rv=$headline. $secs[$section*2];
176 $count=$section+1;
177
178 $break=false;
179 while(!empty($secs[$count*2-1]) && !$break) {
180
181 $subheadline=$secs[$count*2-1];
182 preg_match( "/^(=+).*?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>/mi",$subheadline,$matches);
183 $subhlevel=$matches[1];
184 if(strpos($subhlevel,"=")!==false) {
185 $subhlevel=strlen($subhlevel);
186 }
187 if($subhlevel > $hlevel) {
188 $rv.=$subheadline.$secs[$count*2];
189 }
190 if($subhlevel <= $hlevel) {
191 $break=true;
192 }
193 $count++;
194
195 }
196 }
197 # reinsert stripped tags
198 $rv=$parser->unstrip($rv,$striparray);
199 $rv=trim($rv);
200 return $rv;
201
202 }
203
204
205 # Load the revision (including cur_text) into this object
206 function loadContent( $noredir = false )
207 {
208 global $wgOut, $wgMwRedir, $wgRequest;
209
210 # Query variables :P
211 $oldid = $wgRequest->getVal( 'oldid' );
212 $redirect = $wgRequest->getVal( 'redirect' );
213
214 if ( $this->mContentLoaded ) return;
215 $fname = "Article::loadContent";
216
217 # Pre-fill content with error message so that if something
218 # fails we'll have something telling us what we intended.
219
220 $t = $this->mTitle->getPrefixedText();
221 if ( isset( $oldid ) ) {
222 $oldid = IntVal( $oldid );
223 $t .= ",oldid={$oldid}";
224 }
225 if ( isset( $redirect ) ) {
226 $redirect = ($redirect == "no") ? "no" : "yes";
227 $t .= ",redirect={$redirect}";
228 }
229 $this->mContent = wfMsg( "missingarticle", $t );
230
231 if ( ! $oldid ) { # Retrieve current version
232 $id = $this->getID();
233 if ( 0 == $id ) return;
234
235 $sql = "SELECT " .
236 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
237 "FROM cur WHERE cur_id={$id}";
238 wfDebug( "$sql\n" );
239 $res = wfQuery( $sql, DB_READ, $fname );
240 if ( 0 == wfNumRows( $res ) ) {
241 return;
242 }
243
244 $s = wfFetchObject( $res );
245 # If we got a redirect, follow it (unless we've been told
246 # not to by either the function parameter or the query
247 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
248 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
249 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
250 $s->cur_text, $m ) ) {
251 $rt = Title::newFromText( $m[1] );
252 if( $rt ) {
253 # Gotta hand redirects to special pages differently:
254 # Fill the HTTP response "Location" header and ignore
255 # the rest of the page we're on.
256
257 if ( $rt->getInterwiki() != "" ) {
258 $wgOut->redirect( $rt->getFullURL() ) ;
259 return;
260 }
261 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
262 $wgOut->redirect( $rt->getFullURL() );
263 return;
264 }
265 $rid = $rt->getArticleID();
266 if ( 0 != $rid ) {
267 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
268 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
269 $res = wfQuery( $sql, DB_READ, $fname );
270
271 if ( 0 != wfNumRows( $res ) ) {
272 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
273 $this->mTitle = $rt;
274 $s = wfFetchObject( $res );
275 }
276 }
277 }
278 }
279 }
280
281 $this->mContent = $s->cur_text;
282 $this->mUser = $s->cur_user;
283 $this->mCounter = $s->cur_counter;
284 $this->mTimestamp = $s->cur_timestamp;
285 $this->mTouched = $s->cur_touched;
286 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
287 $this->mTitle->mRestrictionsLoaded = true;
288 wfFreeResult( $res );
289 } else { # oldid set, retrieve historical version
290 $sql = "SELECT old_namespace,old_title,old_text,old_timestamp,old_user,old_flags FROM old " .
291 "WHERE old_id={$oldid}";
292 $res = wfQuery( $sql, DB_READ, $fname );
293 if ( 0 == wfNumRows( $res ) ) {
294 return;
295 }
296
297 $s = wfFetchObject( $res );
298 if( $this->mTitle->getNamespace() != $s->old_namespace ||
299 $this->mTitle->getDBkey() != $s->old_title ) {
300 $oldTitle = Title::makeTitle( $s->old_namesapce, $s->old_title );
301 $this->mTitle = $oldTitle;
302 $wgTitle = $oldTitle;
303 }
304 $this->mContent = Article::getRevisionText( $s );
305 $this->mUser = $s->old_user;
306 $this->mCounter = 0;
307 $this->mTimestamp = $s->old_timestamp;
308 wfFreeResult( $res );
309 }
310 $this->mContentLoaded = true;
311 return $this->mContent;
312 }
313
314 # Gets the article text without using so many damn globals
315 # Returns false on error
316 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
317 global $wgMwRedir;
318
319 if ( $this->mContentLoaded ) {
320 return $this->mContent;
321 }
322 $this->mContent = false;
323
324 $fname = "Article::loadContent";
325
326 if ( ! $oldid ) { # Retrieve current version
327 $id = $this->getID();
328 if ( 0 == $id ) {
329 return false;
330 }
331
332 $sql = "SELECT " .
333 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
334 "FROM cur WHERE cur_id={$id}";
335 $res = wfQuery( $sql, DB_READ, $fname );
336 if ( 0 == wfNumRows( $res ) ) {
337 return false;
338 }
339
340 $s = wfFetchObject( $res );
341 # If we got a redirect, follow it (unless we've been told
342 # not to by either the function parameter or the query
343 if ( !$noredir && $wgMwRedir->matchStart( $s->cur_text ) ) {
344 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
345 $s->cur_text, $m ) ) {
346 $rt = Title::newFromText( $m[1] );
347 if( $rt && $rt->getInterwiki() == "" && $rt->getNamespace() != Namespace::getSpecial() ) {
348 $rid = $rt->getArticleID();
349 if ( 0 != $rid ) {
350 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
351 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
352 $res = wfQuery( $sql, DB_READ, $fname );
353
354 if ( 0 != wfNumRows( $res ) ) {
355 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
356 $this->mTitle = $rt;
357 $s = wfFetchObject( $res );
358 }
359 }
360 }
361 }
362 }
363
364 $this->mContent = $s->cur_text;
365 $this->mUser = $s->cur_user;
366 $this->mCounter = $s->cur_counter;
367 $this->mTimestamp = $s->cur_timestamp;
368 $this->mTouched = $s->cur_touched;
369 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
370 $this->mTitle->mRestrictionsLoaded = true;
371 wfFreeResult( $res );
372 } else { # oldid set, retrieve historical version
373 $sql = "SELECT old_text,old_timestamp,old_user,old_flags FROM old " .
374 "WHERE old_id={$oldid}";
375 $res = wfQuery( $sql, DB_READ, $fname );
376 if ( 0 == wfNumRows( $res ) ) {
377 return false;
378 }
379
380 $s = wfFetchObject( $res );
381 $this->mContent = Article::getRevisionText( $s );
382 $this->mUser = $s->old_user;
383 $this->mCounter = 0;
384 $this->mTimestamp = $s->old_timestamp;
385 wfFreeResult( $res );
386 }
387 $this->mContentLoaded = true;
388 return $this->mContent;
389 }
390
391 function getID() {
392 if( $this->mTitle ) {
393 return $this->mTitle->getArticleID();
394 } else {
395 return 0;
396 }
397 }
398
399 function getCount()
400 {
401 if ( -1 == $this->mCounter ) {
402 $id = $this->getID();
403 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
404 }
405 return $this->mCounter;
406 }
407
408 # Would the given text make this article a "good" article (i.e.,
409 # suitable for including in the article count)?
410
411 function isCountable( $text )
412 {
413 global $wgUseCommaCount, $wgMwRedir;
414
415 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
416 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
417 $token = ($wgUseCommaCount ? "," : "[[" );
418 if ( false === strstr( $text, $token ) ) { return 0; }
419 return 1;
420 }
421
422 # Loads everything from cur except cur_text
423 # This isn't necessary for all uses, so it's only done if needed.
424
425 /* private */ function loadLastEdit()
426 {
427 global $wgOut;
428 if ( -1 != $this->mUser ) return;
429
430 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
431 "cur_comment,cur_minor_edit FROM cur WHERE " .
432 "cur_id=" . $this->getID();
433 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
434
435 if ( wfNumRows( $res ) > 0 ) {
436 $s = wfFetchObject( $res );
437 $this->mUser = $s->cur_user;
438 $this->mUserText = $s->cur_user_text;
439 $this->mTimestamp = $s->cur_timestamp;
440 $this->mComment = $s->cur_comment;
441 $this->mMinorEdit = $s->cur_minor_edit;
442 }
443 }
444
445 function getTimestamp()
446 {
447 $this->loadLastEdit();
448 return $this->mTimestamp;
449 }
450
451 function getUser()
452 {
453 $this->loadLastEdit();
454 return $this->mUser;
455 }
456
457 function getUserText()
458 {
459 $this->loadLastEdit();
460 return $this->mUserText;
461 }
462
463 function getComment()
464 {
465 $this->loadLastEdit();
466 return $this->mComment;
467 }
468
469 function getMinorEdit()
470 {
471 $this->loadLastEdit();
472 return $this->mMinorEdit;
473 }
474
475 function getContributors($limit = 0, $offset = 0)
476 {
477 $fname = "Article::getContributors";
478
479 # XXX: this is expensive; cache this info somewhere.
480
481 $title = $this->mTitle;
482
483 $contribs = array();
484
485 $sql = "SELECT old.old_user, old.old_user_text, " .
486 " user.user_real_name, MAX(old.old_timestamp) as timestamp" .
487 " FROM old, user " .
488 " WHERE old.old_user = user.user_id " .
489 " AND old.old_namespace = " . $title->getNamespace() .
490 " AND old.old_title = \"" . $title->getDBkey() . "\"" .
491 " AND old.old_user != 0 " .
492 " AND old.old_user != " . $this->getUser() .
493 " GROUP BY old.old_user " .
494 " ORDER BY timestamp DESC ";
495
496 if ($limit > 0) {
497 $sql .= " LIMIT $limit";
498 }
499
500 $res = wfQuery($sql, DB_READ, $fname);
501
502 while ( $line = wfFetchObject( $res ) ) {
503 $contribs[$line->old_user] =
504 array($line->old_user_text, $line->user_real_name);
505 }
506
507 # Count anonymous users
508
509 $res = wfQuery("SELECT COUNT(*) AS cnt " .
510 " FROM old " .
511 " WHERE old_namespace = " . $title->getNamespace() .
512 " AND old_title = '" . $title->getDBkey() . "'" .
513 " AND old_user = 0 ", DB_READ, $fname);
514
515 while ( $line = wfFetchObject( $res ) ) {
516 $contribs[0] = array($line->cnt, 'Anonymous');
517 }
518
519 return $contribs;
520 }
521
522 # This is the default action of the script: just view the page of
523 # the given title.
524
525 function view()
526 {
527 global $wgUser, $wgOut, $wgLang, $wgRequest;
528 global $wgLinkCache, $IP, $wgEnableParserCache;
529
530 $fname = "Article::view";
531 wfProfileIn( $fname );
532
533 # Get variables from query string :P
534 $oldid = $wgRequest->getVal( 'oldid' );
535 $diff = $wgRequest->getVal( 'diff' );
536
537 $wgOut->setArticleFlag( true );
538 $wgOut->setRobotpolicy( "index,follow" );
539
540 # If we got diff and oldid in the query, we want to see a
541 # diff page instead of the article.
542
543 if ( !is_null( $diff ) ) {
544 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
545 $de = new DifferenceEngine( intval($oldid), intval($diff) );
546 $de->showDiffPage();
547 wfProfileOut( $fname );
548 return;
549 }
550
551 if ( !is_null( $oldid ) and $this->checkTouched() ) {
552 if( $wgOut->checkLastModified( $this->mTouched ) ){
553 return;
554 } else if ( $this->tryFileCache() ) {
555 # tell wgOut that output is taken care of
556 $wgOut->disable();
557 $this->viewUpdates();
558 return;
559 }
560 }
561
562 $text = $this->getContent( false ); # May change mTitle by following a redirect
563
564 # Another whitelist check in case oldid or redirects are altering the title
565 if ( !$this->mTitle->userCanRead() ) {
566 $wgOut->loginToUse();
567 $wgOut->output();
568 exit;
569 }
570
571 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
572
573 # We're looking at an old revision
574
575 if ( !empty( $oldid ) ) {
576 $this->setOldSubtitle();
577 $wgOut->setRobotpolicy( "noindex,follow" );
578 }
579 if ( "" != $this->mRedirectedFrom ) {
580 $sk = $wgUser->getSkin();
581 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
582 "redirect=no" );
583 $s = wfMsg( "redirectedfrom", $redir );
584 $wgOut->setSubtitle( $s );
585 }
586
587 $wgLinkCache->preFill( $this->mTitle );
588
589 # wrap user css and user js in pre and don't parse
590 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
591 if (
592 $this->mTitle->getNamespace() == Namespace::getUser() &&
593 preg_match("/\\/[\\w]+\\.(css|js)$/", $this->mTitle->getDBkey())
594 ) {
595 $wgOut->addWikiText( wfMsg('usercssjs'));
596 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
597 } else if( $wgEnableParserCache && intval($wgUser->getOption( "stubthreshold" )) == 0 ){
598 $wgOut->addWikiText( $text, true, $this );
599 } else {
600 $wgOut->addWikiText( $text );
601 }
602
603 # Add link titles as META keywords
604 $wgOut->addMetaTags() ;
605
606 $this->viewUpdates();
607 wfProfileOut( $fname );
608 }
609
610 # Theoretically we could defer these whole insert and update
611 # functions for after display, but that's taking a big leap
612 # of faith, and we want to be able to report database
613 # errors at some point.
614
615 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
616 {
617 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
618 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
619
620 $fname = "Article::insertNewArticle";
621
622 $this->mCountAdjustment = $this->isCountable( $text );
623
624 $ns = $this->mTitle->getNamespace();
625 $ttl = $this->mTitle->getDBkey();
626 $text = $this->preSaveTransform( $text );
627 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
628 else { $redir = 0; }
629
630 $now = wfTimestampNow();
631 $won = wfInvertTimestamp( $now );
632 wfSeedRandom();
633 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
634 $isminor = ( $isminor && $wgUser->getID() ) ? 1 : 0;
635 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
636 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
637 "cur_restrictions,cur_user_text,cur_is_redirect," .
638 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
639 wfStrencode( $text ) . "', '" .
640 wfStrencode( $summary ) . "', '" .
641 $wgUser->getID() . "', '{$now}', " .
642 $isminor . ", 0, '', '" .
643 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
644 $res = wfQuery( $sql, DB_WRITE, $fname );
645
646 $newid = wfInsertId();
647 $this->mTitle->resetArticleID( $newid );
648
649 Article::onArticleCreate( $this->mTitle );
650 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
651
652 if ($watchthis) {
653 if(!$this->mTitle->userIsWatching()) $this->watch();
654 } else {
655 if ( $this->mTitle->userIsWatching() ) {
656 $this->unwatch();
657 }
658 }
659
660 # The talk page isn't in the regular link tables, so we need to update manually:
661 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
662 $sql = "UPDATE cur set cur_touched='$now' WHERE cur_namespace=$talkns AND cur_title='" . wfStrencode( $ttl ) . "'";
663 wfQuery( $sql, DB_WRITE );
664
665 # standard deferred updates
666 $this->editUpdates( $text );
667
668 $this->showArticle( $text, wfMsg( "newarticle" ) );
669 }
670
671
672 /* Side effects: loads last edit */
673 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ""){
674 $this->loadLastEdit();
675 $oldtext = $this->getContent( true );
676 if ($section != "") {
677 if($section=="new") {
678 if($summary) $subject="== {$summary} ==\n\n";
679 $text=$oldtext."\n\n".$subject.$text;
680 } else {
681
682 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
683 # comments to be stripped as well)
684 $striparray=array();
685 $parser=new Parser();
686 $parser->mOutputType=OT_WIKI;
687 $oldtext=$parser->strip($oldtext, $striparray, true);
688
689 # now that we can be sure that no pseudo-sections are in the source,
690 # split it up
691 # Unfortunately we can't simply do a preg_replace because that might
692 # replace the wrong section, so we have to use the section counter instead
693 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?" . ">.*?<\/h[1-6].*?" . ">)/mi",
694 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
695 $secs[$section*2]=$text."\n\n"; // replace with edited
696
697 # section 0 is top (intro) section
698 if($section!=0) {
699
700 # headline of old section - we need to go through this section
701 # to determine if there are any subsections that now need to
702 # be erased, as the mother section has been replaced with
703 # the text of all subsections.
704 $headline=$secs[$section*2-1];
705 preg_match( "/^(=+).*?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>/mi",$headline,$matches);
706 $hlevel=$matches[1];
707
708 # determine headline level for wikimarkup headings
709 if(strpos($hlevel,"=")!==false) {
710 $hlevel=strlen($hlevel);
711 }
712
713 $secs[$section*2-1]=""; // erase old headline
714 $count=$section+1;
715 $break=false;
716 while(!empty($secs[$count*2-1]) && !$break) {
717
718 $subheadline=$secs[$count*2-1];
719 preg_match(
720 "/^(=+).*?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>/mi",$subheadline,$matches);
721 $subhlevel=$matches[1];
722 if(strpos($subhlevel,"=")!==false) {
723 $subhlevel=strlen($subhlevel);
724 }
725 if($subhlevel > $hlevel) {
726 // erase old subsections
727 $secs[$count*2-1]="";
728 $secs[$count*2]="";
729 }
730 if($subhlevel <= $hlevel) {
731 $break=true;
732 }
733 $count++;
734
735 }
736
737 }
738 $text=join("",$secs);
739 # reinsert the stuff that we stripped out earlier
740 $text=$parser->unstrip($text,$striparray);
741 }
742
743 }
744 return $text;
745 }
746
747 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false )
748 {
749 global $wgOut, $wgUser, $wgLinkCache;
750 global $wgDBtransactions, $wgMwRedir;
751 global $wgUseSquid, $wgInternalServer;
752 $fname = "Article::updateArticle";
753
754 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
755 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
756 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
757 $redir = 1;
758 $text = $m[1] . "\n"; # Remove all content but redirect
759 }
760 else { $redir = 0; }
761
762 $text = $this->preSaveTransform( $text );
763
764 # Update article, but only if changed.
765
766 if( $wgDBtransactions ) {
767 $sql = "BEGIN";
768 wfQuery( $sql, DB_WRITE );
769 }
770 $oldtext = $this->getContent( true );
771
772 if ( 0 != strcmp( $text, $oldtext ) ) {
773 $this->mCountAdjustment = $this->isCountable( $text )
774 - $this->isCountable( $oldtext );
775
776 $now = wfTimestampNow();
777 $won = wfInvertTimestamp( $now );
778 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
779 "',cur_comment='" . wfStrencode( $summary ) .
780 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
781 ",cur_timestamp='{$now}',cur_user_text='" .
782 wfStrencode( $wgUser->getName() ) .
783 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
784 "WHERE cur_id=" . $this->getID() .
785 " AND cur_timestamp='" . $this->getTimestamp() . "'";
786 $res = wfQuery( $sql, DB_WRITE, $fname );
787
788 if( wfAffectedRows() == 0 ) {
789 /* Belated edit conflict! Run away!! */
790 return false;
791 }
792
793 # This overwrites $oldtext if revision compression is on
794 $flags = Article::compressRevisionText( $oldtext );
795
796 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
797 "old_comment,old_user,old_user_text,old_timestamp," .
798 "old_minor_edit,inverse_timestamp,old_flags) VALUES (" .
799 $this->mTitle->getNamespace() . ", '" .
800 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
801 wfStrencode( $oldtext ) . "', '" .
802 wfStrencode( $this->getComment() ) . "', " .
803 $this->getUser() . ", '" .
804 wfStrencode( $this->getUserText() ) . "', '" .
805 $this->getTimestamp() . "', " . $me1 . ", '" .
806 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
807 $res = wfQuery( $sql, DB_WRITE, $fname );
808 $oldid = wfInsertID( $res );
809
810 $bot = (int)($wgUser->isBot() || $forceBot);
811 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
812 $oldid, $this->getTimestamp(), $bot );
813 Article::onArticleEdit( $this->mTitle );
814 }
815
816 if( $wgDBtransactions ) {
817 $sql = "COMMIT";
818 wfQuery( $sql, DB_WRITE );
819 }
820
821 if ($watchthis) {
822 if (!$this->mTitle->userIsWatching()) $this->watch();
823 } else {
824 if ( $this->mTitle->userIsWatching() ) {
825 $this->unwatch();
826 }
827 }
828 # standard deferred updates
829 $this->editUpdates( $text );
830
831
832 $urls = array();
833 # Template namespace
834 # Purge all articles linking here
835 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
836 $titles = $this->mTitle->getLinksTo();
837 Title::touchArray( $titles );
838 if ( $wgUseSquid ) {
839 foreach ( $titles as $title ) {
840 $urls[] = $title->getInternalURL();
841 }
842 }
843 }
844
845 # Squid updates
846 if ( $wgUseSquid ) {
847 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
848 $u = new SquidUpdate( $urls );
849 $u->doUpdate();
850 }
851
852 $this->showArticle( $text, wfMsg( "updated" ) );
853 return true;
854 }
855
856 # After we've either updated or inserted the article, update
857 # the link tables and redirect to the new page.
858
859 function showArticle( $text, $subtitle )
860 {
861 global $wgOut, $wgUser, $wgLinkCache;
862 global $wgMwRedir;
863
864 $wgLinkCache = new LinkCache();
865
866 # Get old version of link table to allow incremental link updates
867 $wgLinkCache->preFill( $this->mTitle );
868 $wgLinkCache->clear();
869
870 # Now update the link cache by parsing the text
871 $wgOut = new OutputPage();
872 $wgOut->addWikiText( $text );
873
874 if( $wgMwRedir->matchStart( $text ) )
875 $r = "redirect=no";
876 else
877 $r = "";
878 $wgOut->redirect( $this->mTitle->getFullURL( $r ) );
879 }
880
881 # Add this page to my watchlist
882
883 function watch( $add = true )
884 {
885 global $wgUser, $wgOut, $wgLang;
886 global $wgDeferredUpdateList;
887
888 if ( 0 == $wgUser->getID() ) {
889 $wgOut->errorpage( "watchnologin", "watchnologintext" );
890 return;
891 }
892 if ( wfReadOnly() ) {
893 $wgOut->readOnlyPage();
894 return;
895 }
896 if( $add )
897 $wgUser->addWatch( $this->mTitle );
898 else
899 $wgUser->removeWatch( $this->mTitle );
900
901 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
902 $wgOut->setRobotpolicy( "noindex,follow" );
903
904 $sk = $wgUser->getSkin() ;
905 $link = $this->mTitle->getPrefixedText();
906
907 if($add)
908 $text = wfMsg( "addedwatchtext", $link );
909 else
910 $text = wfMsg( "removedwatchtext", $link );
911 $wgOut->addWikiText( $text );
912
913 $up = new UserUpdate();
914 array_push( $wgDeferredUpdateList, $up );
915
916 $wgOut->returnToMain( false );
917 }
918
919 function unwatch()
920 {
921 $this->watch( false );
922 }
923
924 function protect( $limit = "sysop" )
925 {
926 global $wgUser, $wgOut, $wgRequest;
927
928 if ( ! $wgUser->isSysop() ) {
929 $wgOut->sysopRequired();
930 return;
931 }
932 if ( wfReadOnly() ) {
933 $wgOut->readOnlyPage();
934 return;
935 }
936 $id = $this->mTitle->getArticleID();
937 if ( 0 == $id ) {
938 $wgOut->fatalError( wfMsg( "badarticleerror" ) );
939 return;
940 }
941
942 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
943 $reason = $wgRequest->getText( 'wpReasonProtect' );
944
945 if ( $confirm ) {
946
947 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
948 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
949 wfQuery( $sql, DB_WRITE, "Article::protect" );
950
951 $log = new LogPage( wfMsg( "protectlogpage" ), wfMsg( "protectlogtext" ) );
952 if ( $limit === "" ) {
953 $log->addEntry( wfMsg( "unprotectedarticle", $this->mTitle->getPrefixedText() ), $reason );
954 } else {
955 $log->addEntry( wfMsg( "protectedarticle", $this->mTitle->getPrefixedText() ), $reason );
956 }
957 $wgOut->redirect( $this->mTitle->getFullURL() );
958 return;
959 } else {
960 $reason = htmlspecialchars( wfMsg( "protectreason" ) );
961 return $this->confirmProtect( "", $reason, $limit );
962 }
963 }
964
965 # Output protection confirmation dialog
966 function confirmProtect( $par, $reason, $limit = "sysop" )
967 {
968 global $wgOut;
969
970 wfDebug( "Article::confirmProtect\n" );
971
972 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
973 $wgOut->setRobotpolicy( "noindex,nofollow" );
974
975 $check = "";
976 $protcom = "";
977
978 if ( $limit === "" ) {
979 $wgOut->setSubtitle( wfMsg( "unprotectsub", $sub ) );
980 $wgOut->addWikiText( wfMsg( "confirmunprotecttext" ) );
981 $check = htmlspecialchars( wfMsg( "confirmunprotect" ) );
982 $protcom = htmlspecialchars( wfMsg( "unprotectcomment" ) );
983 $formaction = $this->mTitle->escapeLocalURL( "action=unprotect" . $par );
984 } else {
985 $wgOut->setSubtitle( wfMsg( "protectsub", $sub ) );
986 $wgOut->addWikiText( wfMsg( "confirmprotecttext" ) );
987 $check = htmlspecialchars( wfMsg( "confirmprotect" ) );
988 $protcom = htmlspecialchars( wfMsg( "protectcomment" ) );
989 $formaction = $this->mTitle->escapeLocalURL( "action=protect" . $par );
990 }
991
992 $confirm = htmlspecialchars( wfMsg( "confirm" ) );
993
994 $wgOut->addHTML( "
995 <form id='protectconfirm' method='post' action=\"{$formaction}\">
996 <table border='0'>
997 <tr>
998 <td align='right'>
999 <label for='wpReasonProtect'>{$protcom}:</label>
1000 </td>
1001 <td align='left'>
1002 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1003 </td>
1004 </tr>
1005 <tr>
1006 <td>&nbsp;</td>
1007 </tr>
1008 <tr>
1009 <td align='right'>
1010 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1011 </td>
1012 <td>
1013 <label for='wpConfirmProtect'>{$check}</label>
1014 </td>
1015 </tr>
1016 <tr>
1017 <td>&nbsp;</td>
1018 <td>
1019 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1020 </td>
1021 </tr>
1022 </table>
1023 </form>\n" );
1024
1025 $wgOut->returnToMain( false );
1026 }
1027
1028 function unprotect()
1029 {
1030 return $this->protect( "" );
1031 }
1032
1033 # UI entry point for page deletion
1034 function delete()
1035 {
1036 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1037 $fname = "Article::delete";
1038 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1039 $reason = $wgRequest->getText( 'wpReason' );
1040
1041 # This code desperately needs to be totally rewritten
1042
1043 # Check permissions
1044 if ( ( ! $wgUser->isSysop() ) ) {
1045 $wgOut->sysopRequired();
1046 return;
1047 }
1048 if ( wfReadOnly() ) {
1049 $wgOut->readOnlyPage();
1050 return;
1051 }
1052
1053 # Better double-check that it hasn't been deleted yet!
1054 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
1055 if ( ( "" == trim( $this->mTitle->getText() ) )
1056 or ( $this->mTitle->getArticleId() == 0 ) ) {
1057 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1058 return;
1059 }
1060
1061 if ( $confirm ) {
1062 $this->doDelete( $reason );
1063 return;
1064 }
1065
1066 # determine whether this page has earlier revisions
1067 # and insert a warning if it does
1068 # we select the text because it might be useful below
1069 $ns = $this->mTitle->getNamespace();
1070 $title = $this->mTitle->getDBkey();
1071 $etitle = wfStrencode( $title );
1072 $sql = "SELECT old_text,old_flags FROM old WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
1073 $res = wfQuery( $sql, DB_READ, $fname );
1074 if( ($old=wfFetchObject($res)) && !$confirm ) {
1075 $skin=$wgUser->getSkin();
1076 $wgOut->addHTML("<b>".wfMsg("historywarning"));
1077 $wgOut->addHTML( $skin->historyLink() ."</b>");
1078 }
1079
1080 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
1081 $res=wfQuery($sql, DB_READ, $fname);
1082 if( ($s=wfFetchObject($res))) {
1083
1084 # if this is a mini-text, we can paste part of it into the deletion reason
1085
1086 #if this is empty, an earlier revision may contain "useful" text
1087 $blanked = false;
1088 if($s->cur_text!="") {
1089 $text=$s->cur_text;
1090 } else {
1091 if($old) {
1092 $text = Article::getRevisionText( $old );
1093 $blanked = true;
1094 }
1095
1096 }
1097
1098 $length=strlen($text);
1099
1100 # this should not happen, since it is not possible to store an empty, new
1101 # page. Let's insert a standard text in case it does, though
1102 if($length == 0 && $reason === "") {
1103 $reason = wfMsg("exblank");
1104 }
1105
1106 if($length < 500 && $reason === "") {
1107
1108 # comment field=255, let's grep the first 150 to have some user
1109 # space left
1110 $text=substr($text,0,150);
1111 # let's strip out newlines and HTML tags
1112 $text=preg_replace("/\"/","'",$text);
1113 $text=preg_replace("/\</","&lt;",$text);
1114 $text=preg_replace("/\>/","&gt;",$text);
1115 $text=preg_replace("/[\n\r]/","",$text);
1116 if(!$blanked) {
1117 $reason=wfMsg("excontent"). " '".$text;
1118 } else {
1119 $reason=wfMsg("exbeforeblank") . " '".$text;
1120 }
1121 if($length>150) { $reason .= "..."; } # we've only pasted part of the text
1122 $reason.="'";
1123 }
1124 }
1125
1126 return $this->confirmDelete( "", $reason );
1127 }
1128
1129 # Output deletion confirmation dialog
1130 function confirmDelete( $par, $reason )
1131 {
1132 global $wgOut;
1133
1134 wfDebug( "Article::confirmDelete\n" );
1135
1136 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1137 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
1138 $wgOut->setRobotpolicy( "noindex,nofollow" );
1139 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1140
1141 $formaction = $this->mTitle->escapeLocalURL( "action=delete" . $par );
1142
1143 $confirm = htmlspecialchars( wfMsg( "confirm" ) );
1144 $check = htmlspecialchars( wfMsg( "confirmcheck" ) );
1145 $delcom = htmlspecialchars( wfMsg( "deletecomment" ) );
1146
1147 $wgOut->addHTML( "
1148 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1149 <table border='0'>
1150 <tr>
1151 <td align='right'>
1152 <label for='wpReason'>{$delcom}:</label>
1153 </td>
1154 <td align='left'>
1155 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1156 </td>
1157 </tr>
1158 <tr>
1159 <td>&nbsp;</td>
1160 </tr>
1161 <tr>
1162 <td align='right'>
1163 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1164 </td>
1165 <td>
1166 <label for='wpConfirm'>{$check}</label>
1167 </td>
1168 </tr>
1169 <tr>
1170 <td>&nbsp;</td>
1171 <td>
1172 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1173 </td>
1174 </tr>
1175 </table>
1176 </form>\n" );
1177
1178 $wgOut->returnToMain( false );
1179 }
1180
1181 # Perform a deletion and output success or failure messages
1182 function doDelete( $reason )
1183 {
1184 global $wgOut, $wgUser, $wgLang;
1185 $fname = "Article::doDelete";
1186 wfDebug( "$fname\n" );
1187
1188 if ( $this->doDeleteArticle( $reason ) ) {
1189 $deleted = $this->mTitle->getPrefixedText();
1190
1191 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1192 $wgOut->setRobotpolicy( "noindex,nofollow" );
1193
1194 $sk = $wgUser->getSkin();
1195 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1196 Namespace::getWikipedia() ) .
1197 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1198
1199 $text = wfMsg( "deletedtext", $deleted, $loglink );
1200
1201 $wgOut->addHTML( "<p>" . $text . "</p>\n" );
1202 $wgOut->returnToMain( false );
1203 } else {
1204 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1205 }
1206 }
1207
1208 # Back-end article deletion
1209 # Deletes the article with database consistency, writes logs, purges caches
1210 # Returns success
1211 function doDeleteArticle( $reason )
1212 {
1213 global $wgUser, $wgLang;
1214 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1215
1216 $fname = "Article::doDeleteArticle";
1217 wfDebug( "$fname\n" );
1218
1219 $ns = $this->mTitle->getNamespace();
1220 $t = wfStrencode( $this->mTitle->getDBkey() );
1221 $id = $this->mTitle->getArticleID();
1222
1223 if ( "" == $t || $id == 0 ) {
1224 return false;
1225 }
1226
1227 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1228 array_push( $wgDeferredUpdateList, $u );
1229
1230 $linksTo = $this->mTitle->getLinksTo();
1231
1232 # Squid purging
1233 if ( $wgUseSquid ) {
1234 $urls = array(
1235 $this->mTitle->getInternalURL(),
1236 $this->mTitle->getInternalURL( "history" )
1237 );
1238 foreach ( $linksTo as $linkTo ) {
1239 $urls[] = $linkTo->getInternalURL();
1240 }
1241
1242 $u = new SquidUpdate( $urls );
1243 array_push( $wgDeferredUpdateList, $u );
1244
1245 }
1246
1247 # Client and file cache invalidation
1248 Title::touchArray( $linksTo );
1249
1250 # Move article and history to the "archive" table
1251 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1252 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1253 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1254 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1255 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1256 wfQuery( $sql, DB_WRITE, $fname );
1257
1258 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1259 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1260 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1261 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1262 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1263 wfQuery( $sql, DB_WRITE, $fname );
1264
1265 # Now that it's safely backed up, delete it
1266
1267 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1268 "cur_title='{$t}'";
1269 wfQuery( $sql, DB_WRITE, $fname );
1270
1271 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1272 "old_title='{$t}'";
1273 wfQuery( $sql, DB_WRITE, $fname );
1274
1275 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1276 "rc_title='{$t}'";
1277 wfQuery( $sql, DB_WRITE, $fname );
1278
1279 # Finally, clean up the link tables
1280 $t = wfStrencode( $this->mTitle->getPrefixedDBkey() );
1281
1282 Article::onArticleDelete( $this->mTitle );
1283
1284 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1285 $first = true;
1286
1287 foreach ( $linksTo as $titleObj ) {
1288 if ( ! $first ) { $sql .= ","; }
1289 $first = false;
1290 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1291 $linkID = $titleObj->getArticleID();
1292 $sql .= "({$linkID},'{$t}')";
1293 }
1294 if ( ! $first ) {
1295 wfQuery( $sql, DB_WRITE, $fname );
1296 }
1297
1298 $sql = "DELETE FROM links WHERE l_to={$id}";
1299 wfQuery( $sql, DB_WRITE, $fname );
1300
1301 $sql = "DELETE FROM links WHERE l_from={$id}";
1302 wfQuery( $sql, DB_WRITE, $fname );
1303
1304 $sql = "DELETE FROM imagelinks WHERE il_from={$id}";
1305 wfQuery( $sql, DB_WRITE, $fname );
1306
1307 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1308 wfQuery( $sql, DB_WRITE, $fname );
1309
1310 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1311 $art = $this->mTitle->getPrefixedText();
1312 $log->addEntry( wfMsg( "deletedarticle", $art ), $reason );
1313
1314 # Clear the cached article id so the interface doesn't act like we exist
1315 $this->mTitle->resetArticleID( 0 );
1316 $this->mTitle->mArticleID = 0;
1317 return true;
1318 }
1319
1320 function rollback()
1321 {
1322 global $wgUser, $wgLang, $wgOut, $wgRequest;
1323
1324 if ( ! $wgUser->isSysop() ) {
1325 $wgOut->sysopRequired();
1326 return;
1327 }
1328 if ( wfReadOnly() ) {
1329 $wgOut->readOnlyPage( $this->getContent( true ) );
1330 return;
1331 }
1332
1333 # Enhanced rollback, marks edits rc_bot=1
1334 $bot = $wgRequest->getBool( 'bot' );
1335
1336 # Replace all this user's current edits with the next one down
1337 $tt = wfStrencode( $this->mTitle->getDBKey() );
1338 $n = $this->mTitle->getNamespace();
1339
1340 # Get the last editor
1341 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1342 $res = wfQuery( $sql, DB_READ );
1343 if( ($x = wfNumRows( $res )) != 1 ) {
1344 # Something wrong
1345 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1346 return;
1347 }
1348 $s = wfFetchObject( $res );
1349 $ut = wfStrencode( $s->cur_user_text );
1350 $uid = $s->cur_user;
1351 $pid = $s->cur_id;
1352
1353 $from = str_replace( '_', ' ', $wgRequest->getVal( "from" ) );
1354 if( $from != $s->cur_user_text ) {
1355 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
1356 $wgOut->addWikiText( wfMsg( "alreadyrolled",
1357 htmlspecialchars( $this->mTitle->getPrefixedText()),
1358 htmlspecialchars( $from ),
1359 htmlspecialchars( $s->cur_user_text ) ) );
1360 if($s->cur_comment != "") {
1361 $wgOut->addHTML(
1362 wfMsg("editcomment",
1363 htmlspecialchars( $s->cur_comment ) ) );
1364 }
1365 return;
1366 }
1367
1368 # Get the last edit not by this guy
1369 $sql = "SELECT old_text,old_user,old_user_text,old_timestamp,old_flags
1370 FROM old USE INDEX (name_title_timestamp)
1371 WHERE old_namespace={$n} AND old_title='{$tt}'
1372 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1373 ORDER BY inverse_timestamp LIMIT 1";
1374 $res = wfQuery( $sql, DB_READ );
1375 if( wfNumRows( $res ) != 1 ) {
1376 # Something wrong
1377 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1378 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1379 return;
1380 }
1381 $s = wfFetchObject( $res );
1382
1383 if ( $bot ) {
1384 # Mark all reverted edits as bot
1385 $sql = "UPDATE recentchanges SET rc_bot=1 WHERE
1386 rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
1387 wfQuery( $sql, DB_WRITE, $fname );
1388 }
1389
1390 # Save it!
1391 $newcomment = wfMsg( "revertpage", $s->old_user_text, $from );
1392 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1393 $wgOut->setRobotpolicy( "noindex,nofollow" );
1394 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr />\n" );
1395 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1396 Article::onArticleEdit( $this->mTitle );
1397 $wgOut->returnToMain( false );
1398 }
1399
1400
1401 # Do standard deferred updates after page view
1402
1403 /* private */ function viewUpdates()
1404 {
1405 global $wgDeferredUpdateList;
1406 if ( 0 != $this->getID() ) {
1407 global $wgDisableCounters;
1408 if( !$wgDisableCounters ) {
1409 Article::incViewCount( $this->getID() );
1410 $u = new SiteStatsUpdate( 1, 0, 0 );
1411 array_push( $wgDeferredUpdateList, $u );
1412 }
1413 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1414 $this->mTitle->getDBkey() );
1415 array_push( $wgDeferredUpdateList, $u );
1416 }
1417 }
1418
1419 # Do standard deferred updates after page edit.
1420 # Every 1000th edit, prune the recent changes table.
1421
1422 /* private */ function editUpdates( $text )
1423 {
1424 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1425 global $wgMessageCache;
1426
1427 wfSeedRandom();
1428 if ( 0 == mt_rand( 0, 999 ) ) {
1429 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1430 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1431 wfQuery( $sql, DB_WRITE );
1432 }
1433 $id = $this->getID();
1434 $title = $this->mTitle->getPrefixedDBkey();
1435 $shortTitle = $this->mTitle->getDBkey();
1436
1437 $adj = $this->mCountAdjustment;
1438
1439 if ( 0 != $id ) {
1440 $u = new LinksUpdate( $id, $title );
1441 array_push( $wgDeferredUpdateList, $u );
1442 $u = new SiteStatsUpdate( 0, 1, $adj );
1443 array_push( $wgDeferredUpdateList, $u );
1444 $u = new SearchUpdate( $id, $title, $text );
1445 array_push( $wgDeferredUpdateList, $u );
1446
1447 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1448 array_push( $wgDeferredUpdateList, $u );
1449
1450 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1451 $wgMessageCache->replace( $shortTitle, $text );
1452 }
1453 }
1454 }
1455
1456 /* private */ function setOldSubtitle()
1457 {
1458 global $wgLang, $wgOut;
1459
1460 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1461 $r = wfMsg( "revisionasof", $td );
1462 $wgOut->setSubtitle( "({$r})" );
1463 }
1464
1465 # This function is called right before saving the wikitext,
1466 # so we can do things like signatures and links-in-context.
1467
1468 function preSaveTransform( $text )
1469 {
1470 global $wgParser, $wgUser;
1471 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1472 }
1473
1474 /* Caching functions */
1475
1476 # checkLastModified returns true if it has taken care of all
1477 # output to the client that is necessary for this request.
1478 # (that is, it has sent a cached version of the page)
1479 function tryFileCache() {
1480 static $called = false;
1481 if( $called ) {
1482 wfDebug( " tryFileCache() -- called twice!?\n" );
1483 return;
1484 }
1485 $called = true;
1486 if($this->isFileCacheable()) {
1487 $touched = $this->mTouched;
1488 if( $this->mTitle->getPrefixedDBkey() == wfMsg( "mainpage" ) ) {
1489 # Expire the main page quicker
1490 $expire = wfUnix2Timestamp( time() - 3600 );
1491 $touched = max( $expire, $touched );
1492 }
1493 $cache = new CacheManager( $this->mTitle );
1494 if($cache->isFileCacheGood( $touched )) {
1495 global $wgOut;
1496 wfDebug( " tryFileCache() - about to load\n" );
1497 $cache->loadFromFileCache();
1498 return true;
1499 } else {
1500 wfDebug( " tryFileCache() - starting buffer\n" );
1501 ob_start( array(&$cache, 'saveToFileCache' ) );
1502 }
1503 } else {
1504 wfDebug( " tryFileCache() - not cacheable\n" );
1505 }
1506 }
1507
1508 function isFileCacheable() {
1509 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1510 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1511
1512 return $wgUseFileCache
1513 and (!$wgShowIPinHeader)
1514 and ($this->getID() != 0)
1515 and ($wgUser->getId() == 0)
1516 and (!$wgUser->getNewtalk())
1517 and ($this->mTitle->getNamespace() != Namespace::getSpecial())
1518 and ($action == "view")
1519 and (!isset($oldid))
1520 and (!isset($diff))
1521 and (!isset($redirect))
1522 and (!isset($printable))
1523 and (!$this->mRedirectedFrom);
1524 }
1525
1526 function checkTouched() {
1527 $id = $this->getID();
1528 $sql = "SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id=$id";
1529 $res = wfQuery( $sql, DB_READ, "Article::checkTouched" );
1530 if( $s = wfFetchObject( $res ) ) {
1531 $this->mTouched = $s->cur_touched;
1532 return !$s->cur_is_redirect;
1533 } else {
1534 return false;
1535 }
1536 }
1537
1538 /* static */ function incViewCount( $id )
1539 {
1540 $id = intval( $id );
1541 global $wgHitcounterUpdateFreq;
1542
1543 if( $wgHitcounterUpdateFreq <= 1 ){ //
1544 wfQuery("UPDATE cur SET cur_counter = cur_counter + 1 " .
1545 "WHERE cur_id = $id", DB_WRITE);
1546 return;
1547 }
1548
1549 # Not important enough to warrant an error page in case of failure
1550 $oldignore = wfIgnoreSQLErrors( true );
1551
1552 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE);
1553
1554 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1555 if( (rand() % $checkfreq != 0) or (wfLastErrno() != 0) ){
1556 # Most of the time (or on SQL errors), skip row count check
1557 wfIgnoreSQLErrors( $oldignore );
1558 return;
1559 }
1560
1561 $res = wfQuery("SELECT COUNT(*) as n FROM hitcounter", DB_WRITE);
1562 $row = wfFetchObject( $res );
1563 $rown = intval( $row->n );
1564 if( $rown >= $wgHitcounterUpdateFreq ){
1565 wfProfileIn( "Article::incViewCount-collect" );
1566 $old_user_abort = ignore_user_abort( true );
1567
1568 wfQuery("LOCK TABLES hitcounter WRITE", DB_WRITE);
1569 wfQuery("CREATE TEMPORARY TABLE acchits TYPE=HEAP ".
1570 "SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter ".
1571 "GROUP BY hc_id", DB_WRITE);
1572 wfQuery("DELETE FROM hitcounter", DB_WRITE);
1573 wfQuery("UNLOCK TABLES", DB_WRITE);
1574 wfQuery("UPDATE cur,acchits SET cur_counter=cur_counter + hc_n ".
1575 "WHERE cur_id = hc_id", DB_WRITE);
1576 wfQuery("DROP TABLE acchits", DB_WRITE);
1577
1578 ignore_user_abort( $old_user_abort );
1579 wfProfileOut( "Article::incViewCount-collect" );
1580 }
1581 wfIgnoreSQLErrors( $oldignore );
1582 }
1583
1584 # The onArticle*() functions are supposed to be a kind of hooks
1585 # which should be called whenever any of the specified actions
1586 # are done.
1587 #
1588 # This is a good place to put code to clear caches, for instance.
1589
1590 # This is called on page move and undelete, as well as edit
1591 /* static */ function onArticleCreate($title_obj){
1592 global $wgEnablePersistentLC, $wgEnableParserCache, $wgUseSquid, $wgDeferredUpdateList;
1593
1594 $titles = $title_obj->getBrokenLinksTo();
1595
1596 # Purge squid
1597 if ( $wgUseSquid ) {
1598 $urls = $title_obj->getSquidURLs();
1599 foreach ( $titles as $linkTitle ) {
1600 $urls[] = $linkTitle->getInternalURL();
1601 }
1602 $u = new SquidUpdate( $urls );
1603 array_push( $wgDeferredUpdateList, $u );
1604 }
1605
1606 # Clear persistent link cache
1607 if ( $wgEnablePersistentLC ) {
1608 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1609 }
1610
1611 # Clear parser cache (not really used)
1612 if ( $wgEnableParserCache ) {
1613 OutputPage::parsercacheClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1614 }
1615 }
1616
1617 /* static */ function onArticleDelete($title_obj){
1618 global $wgEnablePersistentLC, $wgEnableParserCache;
1619 if ( $wgEnablePersistentLC ) {
1620 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
1621 }
1622 if ( $wgEnableParserCache ) {
1623 OutputPage::parsercacheClearLinksTo( $title_obj->getArticleID() );
1624 }
1625 }
1626
1627 /* static */ function onArticleEdit($title_obj){
1628 global $wgEnablePersistentLC, $wgEnableParserCache;
1629 if ( $wgEnablePersistentLC ) {
1630 LinkCache::linksccClearPage( $title_obj->getArticleID() );
1631 }
1632 if ( $wgEnableParserCache ) {
1633 OutputPage::parsercacheClearPage( $title_obj->getArticleID(), $title_obj->getNamespace() );
1634 }
1635 }
1636 }
1637
1638 ?>