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