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