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