Backporting concatenated gzip history compression from SCHEMA_WORK. Also made a few...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @version $Id$
5 * @package MediaWiki
6 */
7
8 /**
9 * Need the CacheManager to be loaded
10 */
11 require_once ( 'CacheManager.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a Wikipedia article and history.
18 *
19 * See design.doc for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @version $Id$
24 * @package MediaWiki
25 */
26 class Article {
27 /**#@+
28 * @access private
29 */
30 var $mContent, $mContentLoaded;
31 var $mUser, $mTimestamp, $mUserText;
32 var $mCounter, $mComment, $mCountAdjustment;
33 var $mMinorEdit, $mRedirectedFrom;
34 var $mTouched, $mFileCache, $mTitle;
35 var $mId, $mTable;
36 var $mForUpdate;
37 /**#@-*/
38
39 /**
40 * Constructor and clear the article
41 * @param mixed &$title
42 */
43 function Article( &$title ) {
44 $this->mTitle =& $title;
45 $this->clear();
46 }
47
48 /**
49 * Clear the object
50 * @private
51 */
52 function clear() {
53 $this->mContentLoaded = false;
54 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
55 $this->mRedirectedFrom = $this->mUserText =
56 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
57 $this->mCountAdjustment = 0;
58 $this->mTouched = '19700101000000';
59 $this->mForUpdate = false;
60 }
61
62 /**
63 * Get revision text associated with an old or archive row
64 * $row is usually an object from wfFetchRow(), both the flags and the text
65 * field must be included
66 * @static
67 * @param integer $row Id of a row
68 * @param string $prefix table prefix (default 'old_')
69 * @return string $text|false the text requested
70 */
71 function getRevisionText( $row, $prefix = 'old_' ) {
72 # Get data
73 $textField = $prefix . 'text';
74 $flagsField = $prefix . 'flags';
75
76 if( isset( $row->$flagsField ) ) {
77 $flags = explode( ',', $row->$flagsField );
78 } else {
79 $flags = array();
80 }
81
82 if( isset( $row->$textField ) ) {
83 $text = $row->$textField;
84 } else {
85 return false;
86 }
87
88 if( in_array( 'gzip', $flags ) ) {
89 # Deal with optional compression of archived pages.
90 # This can be done periodically via maintenance/compressOld.php, and
91 # as pages are saved if $wgCompressRevisions is set.
92 $text = gzinflate( $text );
93 }
94
95 if( in_array( 'object', $flags ) ) {
96 # Generic compressed storage
97 $obj = unserialize( $text );
98
99 # Bugger, corrupted my test database by double-serializing
100 if ( !is_object( $obj ) ) {
101 $obj = unserialize( $obj );
102 }
103
104 $text = $obj->getText();
105 }
106
107 global $wgLegacyEncoding;
108 if( $wgLegacyEncoding && !in_array( 'utf-8', $flags ) ) {
109 # Old revisions kept around in a legacy encoding?
110 # Upconvert on demand.
111 global $wgInputEncoding, $wgContLang;
112 $text = $wgContLang->iconv( $wgLegacyEncoding, $wgInputEncoding, $text );
113 }
114 return $text;
115 }
116
117 /**
118 * If $wgCompressRevisions is enabled, we will compress data.
119 * The input string is modified in place.
120 * Return value is the flags field: contains 'gzip' if the
121 * data is compressed, and 'utf-8' if we're saving in UTF-8
122 * mode.
123 *
124 * @static
125 * @param mixed $text reference to a text
126 * @return string
127 */
128 function compressRevisionText( &$text ) {
129 global $wgCompressRevisions, $wgUseLatin1;
130 $flags = array();
131 if( !$wgUseLatin1 ) {
132 # Revisions not marked this way will be converted
133 # on load if $wgLegacyCharset is set in the future.
134 $flags[] = 'utf-8';
135 }
136 if( $wgCompressRevisions ) {
137 if( function_exists( 'gzdeflate' ) ) {
138 $text = gzdeflate( $text );
139 $flags[] = 'gzip';
140 } else {
141 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
142 }
143 }
144 return implode( ',', $flags );
145 }
146
147 /**
148 * Note that getContent/loadContent may follow redirects if
149 * not told otherwise, and so may cause a change to mTitle.
150 *
151 * @param $noredir
152 * @return Return the text of this revision
153 */
154 function getContent( $noredir ) {
155 global $wgRequest;
156
157 # Get variables from query string :P
158 $action = $wgRequest->getText( 'action', 'view' );
159 $section = $wgRequest->getText( 'section' );
160
161 $fname = 'Article::getContent';
162 wfProfileIn( $fname );
163
164 if ( 0 == $this->getID() ) {
165 if ( 'edit' == $action ) {
166 wfProfileOut( $fname );
167 return ''; # was "newarticletext", now moved above the box)
168 }
169 wfProfileOut( $fname );
170 return wfMsg( 'noarticletext' );
171 } else {
172 $this->loadContent( $noredir );
173 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
174 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
175 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle->getText()) &&
176 $action=='view'
177 ) {
178 wfProfileOut( $fname );
179 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
180 } else {
181 if($action=='edit') {
182 if($section!='') {
183 if($section=='new') {
184 wfProfileOut( $fname );
185 return '';
186 }
187
188 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
189 # comments to be stripped as well)
190 $rv=$this->getSection($this->mContent,$section);
191 wfProfileOut( $fname );
192 return $rv;
193 }
194 }
195 wfProfileOut( $fname );
196 return $this->mContent;
197 }
198 }
199 }
200
201 /**
202 * This function returns the text of a section, specified by a number ($section).
203 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
204 * the first section before any such heading (section 0).
205 *
206 * If a section contains subsections, these are also returned.
207 *
208 * @param string $text text to look in
209 * @param integer $section section number
210 * @return string text of the requested section
211 */
212 function getSection($text,$section) {
213
214 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
215 # comments to be stripped as well)
216 $striparray=array();
217 $parser=new Parser();
218 $parser->mOutputType=OT_WIKI;
219 $striptext=$parser->strip($text, $striparray, true);
220
221 # now that we can be sure that no pseudo-sections are in the source,
222 # split it up by section
223 $secs =
224 preg_split(
225 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
226 $striptext, -1,
227 PREG_SPLIT_DELIM_CAPTURE);
228 if($section==0) {
229 $rv=$secs[0];
230 } else {
231 $headline=$secs[$section*2-1];
232 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
233 $hlevel=$matches[1];
234
235 # translate wiki heading into level
236 if(strpos($hlevel,'=')!==false) {
237 $hlevel=strlen($hlevel);
238 }
239
240 $rv=$headline. $secs[$section*2];
241 $count=$section+1;
242
243 $break=false;
244 while(!empty($secs[$count*2-1]) && !$break) {
245
246 $subheadline=$secs[$count*2-1];
247 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
248 $subhlevel=$matches[1];
249 if(strpos($subhlevel,'=')!==false) {
250 $subhlevel=strlen($subhlevel);
251 }
252 if($subhlevel > $hlevel) {
253 $rv.=$subheadline.$secs[$count*2];
254 }
255 if($subhlevel <= $hlevel) {
256 $break=true;
257 }
258 $count++;
259
260 }
261 }
262 # reinsert stripped tags
263 $rv=$parser->unstrip($rv,$striparray);
264 $rv=$parser->unstripNoWiki($rv,$striparray);
265 $rv=trim($rv);
266 return $rv;
267
268 }
269
270 /**
271 * Return an array of the columns of the "cur"-table
272 */
273 function &getCurContentFields() {
274 global $wgArticleCurContentFields;
275 if ( !$wgArticleCurContentFields ) {
276 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
277 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
278 }
279 return $wgArticleCurContentFields;
280 }
281
282 /**
283 * Return an array of the columns of the "old"-table
284 */
285 function &getOldContentFields() {
286 global $wgArticleOldContentFields;
287 if ( !$wgArticleOldContentFields ) {
288 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
289 'old_user','old_user_text','old_comment','old_flags' );
290 }
291 return $wgArticleOldContentFields;
292 }
293
294 /**
295 * Load the revision (including cur_text) into this object
296 */
297 function loadContent( $noredir = false ) {
298 global $wgOut, $wgRequest;
299
300 if ( $this->mContentLoaded ) return;
301
302 $dbr =& $this->getDB();
303 # Query variables :P
304 $oldid = $wgRequest->getVal( 'oldid' );
305 $redirect = $wgRequest->getVal( 'redirect' );
306
307 $fname = 'Article::loadContent';
308
309 # Pre-fill content with error message so that if something
310 # fails we'll have something telling us what we intended.
311
312 $t = $this->mTitle->getPrefixedText();
313 if ( isset( $oldid ) ) {
314 $oldid = IntVal( $oldid );
315 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
316 $nextid = $this->mTitle->getNextRevisionID( $oldid );
317 if ( $nextid ) {
318 $oldid = $nextid;
319 } else {
320 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
321 }
322 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
323 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
324 if ( $previd ) {
325 $oldid = $previd;
326 } else {
327 # TODO
328 }
329 }
330 }
331 if ( isset( $oldid ) ) {
332 $t .= ',oldid='.$oldid;
333 }
334 if ( isset( $redirect ) ) {
335 $redirect = ($redirect == 'no') ? 'no' : 'yes';
336 $t .= ',redirect='.$redirect;
337 }
338 $this->mContent = wfMsg( 'missingarticle', $t );
339
340 if ( ! $oldid ) { # Retrieve current version
341 $id = $this->getID();
342 if ( 0 == $id ) return;
343
344 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
345 $this->getSelectOptions() );
346 if ( $s === false ) {
347 return;
348 }
349
350 # If we got a redirect, follow it (unless we've been told
351 # not to by either the function parameter or the query
352 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
353 $rt = Title::newFromRedirect( $s->cur_text );
354 # process if title object is valid and not special:userlogout
355 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
356 # Gotta hand redirects to special pages differently:
357 # Fill the HTTP response "Location" header and ignore
358 # the rest of the page we're on.
359
360 if ( $rt->getInterwiki() != '' ) {
361 $wgOut->redirect( $rt->getFullURL() ) ;
362 return;
363 }
364 if ( $rt->getNamespace() == NS_SPECIAL ) {
365 $wgOut->redirect( $rt->getFullURL() );
366 return;
367 }
368 $rid = $rt->getArticleID();
369 if ( 0 != $rid ) {
370 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
371 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
372
373 if ( $redirRow !== false ) {
374 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
375 $this->mTitle = $rt;
376 $s = $redirRow;
377 }
378 }
379 }
380 }
381
382 $this->mContent = $s->cur_text;
383 $this->mUser = $s->cur_user;
384 $this->mUserText = $s->cur_user_text;
385 $this->mComment = $s->cur_comment;
386 $this->mCounter = $s->cur_counter;
387 $this->mTimestamp = wfTimestamp(TS_MW,$s->cur_timestamp);
388 $this->mTouched = wfTimestamp(TS_MW,$s->cur_touched);
389 $this->mTitle->mRestrictions = explode( ',', trim( $s->cur_restrictions ) );
390 $this->mTitle->mRestrictionsLoaded = true;
391 } else { # oldid set, retrieve historical version
392 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
393 $fname, $this->getSelectOptions() );
394 if ( $s === false ) {
395 return;
396 }
397
398 if( $this->mTitle->getNamespace() != $s->old_namespace ||
399 $this->mTitle->getDBkey() != $s->old_title ) {
400 $oldTitle = Title::makeTitle( $s->old_namesapce, $s->old_title );
401 $this->mTitle = $oldTitle;
402 $wgTitle = $oldTitle;
403 }
404 $this->mContent = Article::getRevisionText( $s );
405 $this->mUser = $s->old_user;
406 $this->mUserText = $s->old_user_text;
407 $this->mComment = $s->old_comment;
408 $this->mCounter = 0;
409 $this->mTimestamp = wfTimestamp(TS_MW,$s->old_timestamp);
410 }
411 $this->mContentLoaded = true;
412 return $this->mContent;
413 }
414
415 /**
416 * Gets the article text without using so many damn globals
417 * Returns false on error
418 *
419 * @param integer $oldid
420 */
421 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
422 if ( $this->mContentLoaded ) {
423 return $this->mContent;
424 }
425 $this->mContent = false;
426
427 $fname = 'Article::getContentWithout';
428 $dbr =& $this->getDB();
429
430 if ( ! $oldid ) { # Retrieve current version
431 $id = $this->getID();
432 if ( 0 == $id ) {
433 return false;
434 }
435
436 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
437 $fname, $this->getSelectOptions() );
438 if ( $s === false ) {
439 return false;
440 }
441
442 # If we got a redirect, follow it (unless we've been told
443 # not to by either the function parameter or the query
444 if ( !$noredir ) {
445 $rt = Title::newFromRedirect( $s->cur_text );
446 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL ) {
447 $rid = $rt->getArticleID();
448 if ( 0 != $rid ) {
449 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
450 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
451
452 if ( $redirRow !== false ) {
453 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
454 $this->mTitle = $rt;
455 $s = $redirRow;
456 }
457 }
458 }
459 }
460
461 $this->mContent = $s->cur_text;
462 $this->mUser = $s->cur_user;
463 $this->mUserText = $s->cur_user_text;
464 $this->mComment = $s->cur_comment;
465 $this->mCounter = $s->cur_counter;
466 $this->mTimestamp = wfTimestamp(TS_MW,$s->cur_timestamp);
467 $this->mTouched = wfTimestamp(TS_MW,$s->cur_touched);
468 $this->mTitle->mRestrictions = explode( ',', trim( $s->cur_restrictions ) );
469 $this->mTitle->mRestrictionsLoaded = true;
470 } else { # oldid set, retrieve historical version
471 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
472 $fname, $this->getSelectOptions() );
473 if ( $s === false ) {
474 return false;
475 }
476 $this->mContent = Article::getRevisionText( $s );
477 $this->mUser = $s->old_user;
478 $this->mUserText = $s->old_user_text;
479 $this->mComment = $s->old_comment;
480 $this->mCounter = 0;
481 $this->mTimestamp = wfTimestamp(TS_MW,$s->old_timestamp);
482 }
483 $this->mContentLoaded = true;
484 return $this->mContent;
485 }
486
487 /**
488 * Read/write accessor to select FOR UPDATE
489 */
490 function forUpdate( $x = NULL ) {
491 return wfSetVar( $this->mForUpdate, $x );
492 }
493
494 /**
495 * Get the database which should be used for reads
496 */
497 function &getDB() {
498 if ( $this->mForUpdate ) {
499 return wfGetDB( DB_MASTER );
500 } else {
501 return wfGetDB( DB_SLAVE );
502 }
503 }
504
505 /**
506 * Get options for all SELECT statements
507 * Can pass an option array, to which the class-wide options will be appended
508 */
509 function getSelectOptions( $options = '' ) {
510 if ( $this->mForUpdate ) {
511 if ( $options ) {
512 $options[] = 'FOR UPDATE';
513 } else {
514 $options = 'FOR UPDATE';
515 }
516 }
517 return $options;
518 }
519
520 /**
521 * Return the Article ID
522 */
523 function getID() {
524 if( $this->mTitle ) {
525 return $this->mTitle->getArticleID();
526 } else {
527 return 0;
528 }
529 }
530
531 /**
532 * Get the view count for this article
533 */
534 function getCount() {
535 if ( -1 == $this->mCounter ) {
536 $id = $this->getID();
537 $dbr =& $this->getDB();
538 $this->mCounter = $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
539 'Article::getCount', $this->getSelectOptions() );
540 }
541 return $this->mCounter;
542 }
543
544 /**
545 * Would the given text make this article a "good" article (i.e.,
546 * suitable for including in the article count)?
547 */
548 function isCountable( $text ) {
549 global $wgUseCommaCount;
550
551 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
552 if ( $this->isRedirect( $text ) ) { return 0; }
553 $token = ($wgUseCommaCount ? ',' : '[[' );
554 if ( false === strstr( $text, $token ) ) { return 0; }
555 return 1;
556 }
557
558 /**
559 * Tests if the article text represents a redirect
560 */
561 function isRedirect( $text = false ) {
562 if ( $text === false ) {
563 $this->loadContent();
564 $titleObj = Title::newFromRedirect( $this->mText );
565 } else {
566 $titleObj = Title::newFromRedirect( $text );
567 }
568 return $titleObj !== NULL;
569 }
570
571 /**
572 * Loads everything from cur except cur_text
573 * This isn't necessary for all uses, so it's only done if needed.
574 * @private
575 */
576 function loadLastEdit() {
577 global $wgOut;
578 if ( -1 != $this->mUser ) return;
579
580 $fname = 'Article::loadLastEdit';
581
582 $dbr =& $this->getDB();
583 $s = $dbr->selectRow( 'cur',
584 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
585 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
586
587 if ( $s !== false ) {
588 $this->mUser = $s->cur_user;
589 $this->mUserText = $s->cur_user_text;
590 $this->mTimestamp = wfTimestamp(TS_MW,$s->cur_timestamp);
591 $this->mComment = $s->cur_comment;
592 $this->mMinorEdit = $s->cur_minor_edit;
593 }
594 }
595
596 function getTimestamp() {
597 $this->loadLastEdit();
598 return $this->mTimestamp;
599 }
600
601 function getUser() {
602 $this->loadLastEdit();
603 return $this->mUser;
604 }
605
606 function getUserText() {
607 $this->loadLastEdit();
608 return $this->mUserText;
609 }
610
611 function getComment() {
612 $this->loadLastEdit();
613 return $this->mComment;
614 }
615
616 function getMinorEdit() {
617 $this->loadLastEdit();
618 return $this->mMinorEdit;
619 }
620
621 function getContributors($limit = 0, $offset = 0) {
622 $fname = 'Article::getContributors';
623
624 # XXX: this is expensive; cache this info somewhere.
625
626 $title = $this->mTitle;
627 $contribs = array();
628 $dbr =& $this->getDB();
629 $oldTable = $dbr->tableName( 'old' );
630 $userTable = $dbr->tableName( 'user' );
631 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
632 $ns = $title->getNamespace();
633 $user = $this->getUser();
634
635 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
636 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
637 WHERE old_namespace = $user
638 AND old_title = $encDBkey
639 AND old_user != $user
640 GROUP BY old_user, old_user_text, user_real_name
641 ORDER BY timestamp DESC";
642
643 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
644 $sql .= ' '. $this->getSelectOptions();
645
646 $res = $dbr->query($sql, $fname);
647
648 while ( $line = $dbr->fetchObject( $res ) ) {
649 $contribs[] = array($line->old_user, $line->old_user_text, $line->user_real_name);
650 }
651
652 $dbr->freeResult($res);
653 return $contribs;
654 }
655
656 /**
657 * This is the default action of the script: just view the page of
658 * the given title.
659 */
660 function view() {
661 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol;
662 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
663 $sk = $wgUser->getSkin();
664
665 $fname = 'Article::view';
666 wfProfileIn( $fname );
667 # Get variables from query string
668 $oldid = $wgRequest->getVal( 'oldid' );
669 $diff = $wgRequest->getVal( 'diff' );
670 $rcid = $wgRequest->getVal( 'rcid' );
671
672 $wgOut->setArticleFlag( true );
673 $wgOut->setRobotpolicy( 'index,follow' );
674 # If we got diff and oldid in the query, we want to see a
675 # diff page instead of the article.
676
677 if ( !is_null( $diff ) ) {
678 require_once( 'DifferenceEngine.php' );
679 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
680 $de = new DifferenceEngine( $oldid, $diff, $rcid );
681 $de->showDiffPage();
682 if( $diff == 0 ) {
683 # Run view updates for current revision only
684 $this->viewUpdates();
685 }
686 wfProfileOut( $fname );
687 return;
688 }
689 if ( empty( $oldid ) && $this->checkTouched() ) {
690 if( $wgOut->checkLastModified( $this->mTouched ) ){
691 wfProfileOut( $fname );
692 return;
693 } else if ( $this->tryFileCache() ) {
694 # tell wgOut that output is taken care of
695 $wgOut->disable();
696 $this->viewUpdates();
697 wfProfileOut( $fname );
698 return;
699 }
700 }
701 # Should the parser cache be used?
702 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
703 $pcache = true;
704 } else {
705 $pcache = false;
706 }
707
708 $outputDone = false;
709 if ( $pcache ) {
710 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
711 $outputDone = true;
712 }
713 }
714 if ( !$outputDone ) {
715 $text = $this->getContent( false ); # May change mTitle by following a redirect
716
717 # Another whitelist check in case oldid or redirects are altering the title
718 if ( !$this->mTitle->userCanRead() ) {
719 $wgOut->loginToUse();
720 $wgOut->output();
721 exit;
722 }
723
724
725 # We're looking at an old revision
726
727 if ( !empty( $oldid ) ) {
728 $this->setOldSubtitle( $oldid );
729 $wgOut->setRobotpolicy( 'noindex,follow' );
730 }
731 if ( '' != $this->mRedirectedFrom ) {
732 $sk = $wgUser->getSkin();
733 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
734 'redirect=no' );
735 $s = wfMsg( 'redirectedfrom', $redir );
736 $wgOut->setSubtitle( $s );
737
738 # Can't cache redirects
739 $pcache = false;
740 }
741
742 # wrap user css and user js in pre and don't parse
743 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
744 if (
745 $this->mTitle->getNamespace() == NS_USER &&
746 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
747 ) {
748 $wgOut->addWikiText( wfMsg('clearyourcache'));
749 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
750 } else if ( $rt = Title::newFromRedirect( $text ) ) {
751 # Display redirect
752 $imageUrl = $wgStylePath.'/common/images/redirect.png';
753 $targetUrl = $rt->escapeLocalURL();
754 $titleText = htmlspecialchars( $rt->getPrefixedText() );
755 $link = $sk->makeLinkObj( $rt );
756 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" />' .
757 '<span class="redirectText">'.$link.'</span>' );
758 } else if ( $pcache ) {
759 # Display content and save to parser cache
760 $wgOut->addPrimaryWikiText( $text, $this );
761 } else {
762 # Display content, don't attempt to save to parser cache
763 $wgOut->addWikiText( $text );
764 }
765 }
766 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
767 # If we have been passed an &rcid= parameter, we want to give the user a
768 # chance to mark this new article as patrolled.
769 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
770 ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
771 {
772 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
773 $sk->makeKnownLinkObj ( $this->mTitle, wfMsg ( 'markaspatrolledtext' ),
774 'action=markpatrolled&rcid='.$rcid )
775 ) );
776 }
777
778 # Put link titles into the link cache
779 $wgOut->transformBuffer();
780
781 # Add link titles as META keywords
782 $wgOut->addMetaTags() ;
783
784 $this->viewUpdates();
785 wfProfileOut( $fname );
786 }
787
788 /**
789 * Theoretically we could defer these whole insert and update
790 * functions for after display, but that's taking a big leap
791 * of faith, and we want to be able to report database
792 * errors at some point.
793 * @private
794 */
795 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
796 global $wgOut, $wgUser;
797 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
798
799 $fname = 'Article::insertNewArticle';
800
801 $this->mCountAdjustment = $this->isCountable( $text );
802
803 $ns = $this->mTitle->getNamespace();
804 $ttl = $this->mTitle->getDBkey();
805 $text = $this->preSaveTransform( $text );
806 if ( $this->isRedirect( $text ) ) { $redir = 1; }
807 else { $redir = 0; }
808
809 $now = wfTimestampNow();
810 $won = wfInvertTimestamp( $now );
811 wfSeedRandom();
812 $rand = wfRandom();
813 $dbw =& wfGetDB( DB_MASTER );
814
815 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
816
817 $isminor = ( $isminor && $wgUser->getID() ) ? 1 : 0;
818
819 $dbw->insert( 'cur', array(
820 'cur_id' => $cur_id,
821 'cur_namespace' => $ns,
822 'cur_title' => $ttl,
823 'cur_text' => $text,
824 'cur_comment' => $summary,
825 'cur_user' => $wgUser->getID(),
826 'cur_timestamp' => $dbw->timestamp($now),
827 'cur_minor_edit' => $isminor,
828 'cur_counter' => 0,
829 'cur_restrictions' => '',
830 'cur_user_text' => $wgUser->getName(),
831 'cur_is_redirect' => $redir,
832 'cur_is_new' => 1,
833 'cur_random' => $rand,
834 'cur_touched' => $dbw->timestamp($now),
835 'inverse_timestamp' => $won,
836 ), $fname );
837
838 $newid = $dbw->insertId();
839 $this->mTitle->resetArticleID( $newid );
840
841 Article::onArticleCreate( $this->mTitle );
842 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
843
844 if ($watchthis) {
845 if(!$this->mTitle->userIsWatching()) $this->watch();
846 } else {
847 if ( $this->mTitle->userIsWatching() ) {
848 $this->unwatch();
849 }
850 }
851
852 # The talk page isn't in the regular link tables, so we need to update manually:
853 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
854 $dbw->update( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
855 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
856
857 # standard deferred updates
858 $this->editUpdates( $text );
859
860 $this->showArticle( $text, wfMsg( 'newarticle' ) );
861 }
862
863
864 /**
865 * Side effects: loads last edit if $edittime is NULL
866 */
867 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
868 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
869 if(is_null($edittime)) {
870 $this->loadLastEdit();
871 $oldtext = $this->getContent( true );
872 } else {
873 $dbw =& wfGetDB( DB_MASTER );
874 $ns = $this->mTitle->getNamespace();
875 $title = $this->mTitle->getDBkey();
876 $obj = $dbw->selectRow( 'old',
877 array( 'old_text','old_flags'),
878 array( 'old_namespace' => $ns, 'old_title' => $title,
879 'old_timestamp' => $dbw->timestamp($edittime)),
880 $fname );
881 $oldtext = Article::getRevisionText( $obj );
882 }
883 if ($section != '') {
884 if($section=='new') {
885 if($summary) $subject="== {$summary} ==\n\n";
886 $text=$oldtext."\n\n".$subject.$text;
887 } else {
888
889 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
890 # comments to be stripped as well)
891 $striparray=array();
892 $parser=new Parser();
893 $parser->mOutputType=OT_WIKI;
894 $oldtext=$parser->strip($oldtext, $striparray, true);
895
896 # now that we can be sure that no pseudo-sections are in the source,
897 # split it up
898 # Unfortunately we can't simply do a preg_replace because that might
899 # replace the wrong section, so we have to use the section counter instead
900 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
901 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
902 $secs[$section*2]=$text."\n\n"; // replace with edited
903
904 # section 0 is top (intro) section
905 if($section!=0) {
906
907 # headline of old section - we need to go through this section
908 # to determine if there are any subsections that now need to
909 # be erased, as the mother section has been replaced with
910 # the text of all subsections.
911 $headline=$secs[$section*2-1];
912 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
913 $hlevel=$matches[1];
914
915 # determine headline level for wikimarkup headings
916 if(strpos($hlevel,'=')!==false) {
917 $hlevel=strlen($hlevel);
918 }
919
920 $secs[$section*2-1]=''; // erase old headline
921 $count=$section+1;
922 $break=false;
923 while(!empty($secs[$count*2-1]) && !$break) {
924
925 $subheadline=$secs[$count*2-1];
926 preg_match(
927 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
928 $subhlevel=$matches[1];
929 if(strpos($subhlevel,'=')!==false) {
930 $subhlevel=strlen($subhlevel);
931 }
932 if($subhlevel > $hlevel) {
933 // erase old subsections
934 $secs[$count*2-1]='';
935 $secs[$count*2]='';
936 }
937 if($subhlevel <= $hlevel) {
938 $break=true;
939 }
940 $count++;
941
942 }
943
944 }
945 $text=join('',$secs);
946 # reinsert the stuff that we stripped out earlier
947 $text=$parser->unstrip($text,$striparray);
948 $text=$parser->unstripNoWiki($text,$striparray);
949 }
950
951 }
952 return $text;
953 }
954
955 /**
956 * Change an existing article. Puts the previous version back into the old table, updates RC
957 * and all necessary caches, mostly via the deferred update array.
958 *
959 * It is possible to call this function from a command-line script, but note that you should
960 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
961 */
962 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
963 global $wgOut, $wgUser;
964 global $wgDBtransactions, $wgMwRedir;
965 global $wgUseSquid, $wgInternalServer;
966
967 $fname = 'Article::updateArticle';
968 $good = true;
969
970 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
971 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
972 if ( $this->isRedirect( $text ) ) {
973 # Remove all content but redirect
974 # This could be done by reconstructing the redirect from a title given by
975 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
976 # wants to see
977 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
978 $redir = 1;
979 $text = $m[1] . "\n";
980 }
981 }
982 else { $redir = 0; }
983
984 $text = $this->preSaveTransform( $text );
985 $dbw =& wfGetDB( DB_MASTER );
986
987 # Update article, but only if changed.
988
989 # It's important that we either rollback or complete, otherwise an attacker could
990 # overwrite cur entries by sending precisely timed user aborts. Random bored users
991 # could conceivably have the same effect, especially if cur is locked for long periods.
992 if( $wgDBtransactions ) {
993 $dbw->query( 'BEGIN', $fname );
994 } else {
995 $userAbort = ignore_user_abort( true );
996 }
997
998 $oldtext = $this->getContent( true );
999
1000 if ( 0 != strcmp( $text, $oldtext ) ) {
1001 $this->mCountAdjustment = $this->isCountable( $text )
1002 - $this->isCountable( $oldtext );
1003 $now = wfTimestampNow();
1004 $won = wfInvertTimestamp( $now );
1005
1006 # First update the cur row
1007 $dbw->update( 'cur',
1008 array( /* SET */
1009 'cur_text' => $text,
1010 'cur_comment' => $summary,
1011 'cur_minor_edit' => $me2,
1012 'cur_user' => $wgUser->getID(),
1013 'cur_timestamp' => $dbw->timestamp($now),
1014 'cur_user_text' => $wgUser->getName(),
1015 'cur_is_redirect' => $redir,
1016 'cur_is_new' => 0,
1017 'cur_touched' => $dbw->timestamp($now),
1018 'inverse_timestamp' => $won
1019 ), array( /* WHERE */
1020 'cur_id' => $this->getID(),
1021 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1022 ), $fname
1023 );
1024
1025 if( $dbw->affectedRows() == 0 ) {
1026 /* Belated edit conflict! Run away!! */
1027 $good = false;
1028 } else {
1029 # Now insert the previous revision into old
1030
1031 # This overwrites $oldtext if revision compression is on
1032 $flags = Article::compressRevisionText( $oldtext );
1033
1034 $dbw->insert( 'old',
1035 array(
1036 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1037 'old_namespace' => $this->mTitle->getNamespace(),
1038 'old_title' => $this->mTitle->getDBkey(),
1039 'old_text' => $oldtext,
1040 'old_comment' => $this->getComment(),
1041 'old_user' => $this->getUser(),
1042 'old_user_text' => $this->getUserText(),
1043 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1044 'old_minor_edit' => $me1,
1045 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1046 'old_flags' => $flags,
1047 ), $fname
1048 );
1049
1050 $oldid = $dbw->insertId();
1051
1052 $bot = (int)($wgUser->isBot() || $forceBot);
1053 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
1054 $oldid, $this->getTimestamp(), $bot );
1055 Article::onArticleEdit( $this->mTitle );
1056 }
1057 }
1058
1059 if( $wgDBtransactions ) {
1060 $dbw->query( 'COMMIT', $fname );
1061 } else {
1062 ignore_user_abort( $userAbort );
1063 }
1064
1065 if ( $good ) {
1066 if ($watchthis) {
1067 if (!$this->mTitle->userIsWatching()) $this->watch();
1068 } else {
1069 if ( $this->mTitle->userIsWatching() ) {
1070 $this->unwatch();
1071 }
1072 }
1073 # standard deferred updates
1074 $this->editUpdates( $text );
1075
1076
1077 $urls = array();
1078 # Template namespace
1079 # Purge all articles linking here
1080 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1081 $titles = $this->mTitle->getLinksTo();
1082 Title::touchArray( $titles );
1083 if ( $wgUseSquid ) {
1084 foreach ( $titles as $title ) {
1085 $urls[] = $title->getInternalURL();
1086 }
1087 }
1088 }
1089
1090 # Squid updates
1091 if ( $wgUseSquid ) {
1092 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1093 $u = new SquidUpdate( $urls );
1094 $u->doUpdate();
1095 }
1096
1097 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1098 }
1099 return $good;
1100 }
1101
1102 /**
1103 * After we've either updated or inserted the article, update
1104 * the link tables and redirect to the new page.
1105 */
1106 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1107 global $wgOut, $wgUser, $wgLinkCache;
1108
1109 $wgLinkCache = new LinkCache();
1110 # Select for update
1111 $wgLinkCache->forUpdate( true );
1112
1113 # Get old version of link table to allow incremental link updates
1114 $wgLinkCache->preFill( $this->mTitle );
1115 $wgLinkCache->clear();
1116
1117 # Parse the text and replace links with placeholders
1118 $wgOut = new OutputPage();
1119 $wgOut->addWikiText( $text );
1120
1121 # Look up the links in the DB and add them to the link cache
1122 $wgOut->transformBuffer( RLH_FOR_UPDATE );
1123
1124 if( $this->isRedirect( $text ) )
1125 $r = 'redirect=no';
1126 else
1127 $r = '';
1128 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1129 }
1130
1131 /**
1132 * Validate article
1133 * @todo document this function a bit more
1134 */
1135 function validate () {
1136 global $wgOut, $wgUseValidation;
1137 if( $wgUseValidation ) {
1138 require_once ( 'SpecialValidate.php' ) ;
1139 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle->getPrefixedText() );
1140 $wgOut->setRobotpolicy( 'noindex,follow' );
1141 if( $this->mTitle->getNamespace() != 0 ) {
1142 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1143 return;
1144 }
1145 $v = new Validation;
1146 $v->validate_form( $this->mTitle->getDBkey() );
1147 } else {
1148 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1149 }
1150 }
1151
1152 /**
1153 * Mark this particular edit as patrolled
1154 */
1155 function markpatrolled() {
1156 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1157 $wgOut->setRobotpolicy( 'noindex,follow' );
1158
1159 if ( !$wgUseRCPatrol )
1160 {
1161 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1162 return;
1163 }
1164 if ( $wgUser->getID() == 0 )
1165 {
1166 $wgOut->loginToUse();
1167 return;
1168 }
1169 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1170 {
1171 $wgOut->sysopRequired();
1172 return;
1173 }
1174 $rcid = $wgRequest->getVal( 'rcid' );
1175 if ( !is_null ( $rcid ) )
1176 {
1177 RecentChange::markPatrolled( $rcid );
1178 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1179 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1180 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1181 }
1182 else
1183 {
1184 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1185 }
1186 }
1187
1188
1189 /**
1190 * Add or remove this page to my watchlist based on value of $add
1191 */
1192 function watch( $add = true ) {
1193 global $wgUser, $wgOut;
1194 global $wgDeferredUpdateList;
1195
1196 if ( 0 == $wgUser->getID() ) {
1197 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1198 return;
1199 }
1200 if ( wfReadOnly() ) {
1201 $wgOut->readOnlyPage();
1202 return;
1203 }
1204 if( $add )
1205 $wgUser->addWatch( $this->mTitle );
1206 else
1207 $wgUser->removeWatch( $this->mTitle );
1208
1209 $wgOut->setPagetitle( wfMsg( $add ? 'addedwatch' : 'removedwatch' ) );
1210 $wgOut->setRobotpolicy( 'noindex,follow' );
1211
1212 $sk = $wgUser->getSkin() ;
1213 $link = $this->mTitle->getPrefixedText();
1214
1215 if($add)
1216 $text = wfMsg( 'addedwatchtext', $link );
1217 else
1218 $text = wfMsg( 'removedwatchtext', $link );
1219 $wgOut->addWikiText( $text );
1220
1221 $up = new UserUpdate();
1222 array_push( $wgDeferredUpdateList, $up );
1223
1224 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1225 }
1226
1227 /**
1228 * Stop watching a page, it act just like a call to watch(false)
1229 */
1230 function unwatch() {
1231 $this->watch( false );
1232 }
1233
1234 /**
1235 * protect a page
1236 */
1237 function protect( $limit = 'sysop' ) {
1238 global $wgUser, $wgOut, $wgRequest;
1239
1240 if ( ! $wgUser->isAllowed('protect') ) {
1241 $wgOut->sysopRequired();
1242 return;
1243 }
1244 if ( wfReadOnly() ) {
1245 $wgOut->readOnlyPage();
1246 return;
1247 }
1248 $id = $this->mTitle->getArticleID();
1249 if ( 0 == $id ) {
1250 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1251 return;
1252 }
1253
1254 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1255 $reason = $wgRequest->getText( 'wpReasonProtect' );
1256
1257 if ( $confirm ) {
1258 $dbw =& wfGetDB( DB_MASTER );
1259 $dbw->update( 'cur',
1260 array( /* SET */
1261 'cur_touched' => $dbw->timestamp(),
1262 'cur_restrictions' => (string)$limit
1263 ), array( /* WHERE */
1264 'cur_id' => $id
1265 ), 'Article::protect'
1266 );
1267
1268 $log = new LogPage( 'protect' );
1269 if ( $limit === '' ) {
1270 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1271 } else {
1272 $log->addEntry( 'protect', $this->mTitle, $reason );
1273 }
1274 $wgOut->redirect( $this->mTitle->getFullURL() );
1275 return;
1276 } else {
1277 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1278 return $this->confirmProtect( '', $reason, $limit );
1279 }
1280 }
1281
1282 /**
1283 * Output protection confirmation dialog
1284 */
1285 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1286 global $wgOut;
1287
1288 wfDebug( "Article::confirmProtect\n" );
1289
1290 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1291 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1292
1293 $check = '';
1294 $protcom = '';
1295
1296 if ( $limit === '' ) {
1297 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1298 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1299 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1300 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1301 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1302 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1303 } else {
1304 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1305 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1306 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1307 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1308 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1309 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1310 }
1311
1312 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1313
1314 $wgOut->addHTML( "
1315 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1316 <table border='0'>
1317 <tr>
1318 <td align='right'>
1319 <label for='wpReasonProtect'>{$protcom}:</label>
1320 </td>
1321 <td align='left'>
1322 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1323 </td>
1324 </tr>
1325 <tr>
1326 <td>&nbsp;</td>
1327 </tr>
1328 <tr>
1329 <td align='right'>
1330 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1331 </td>
1332 <td>
1333 <label for='wpConfirmProtect'>{$check}</label>
1334 </td>
1335 </tr>
1336 <tr>
1337 <td>&nbsp;</td>
1338 <td>
1339 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1340 </td>
1341 </tr>
1342 </table>
1343 </form>\n" );
1344
1345 $wgOut->returnToMain( false );
1346 }
1347
1348 /**
1349 * Unprotect the pages
1350 */
1351 function unprotect() {
1352 return $this->protect( '' );
1353 }
1354
1355 /*
1356 * UI entry point for page deletion
1357 */
1358 function delete() {
1359 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1360 $fname = 'Article::delete';
1361 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1362 $reason = $wgRequest->getText( 'wpReason' );
1363
1364 # This code desperately needs to be totally rewritten
1365
1366 # Check permissions
1367 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1368 $wgOut->sysopRequired();
1369 return;
1370 }
1371 if ( wfReadOnly() ) {
1372 $wgOut->readOnlyPage();
1373 return;
1374 }
1375
1376 # Better double-check that it hasn't been deleted yet!
1377 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1378 if ( ( '' == trim( $this->mTitle->getText() ) )
1379 or ( $this->mTitle->getArticleId() == 0 ) ) {
1380 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1381 return;
1382 }
1383
1384 if ( $confirm ) {
1385 $this->doDelete( $reason );
1386 return;
1387 }
1388
1389 # determine whether this page has earlier revisions
1390 # and insert a warning if it does
1391 # we select the text because it might be useful below
1392 $dbr =& $this->getDB();
1393 $ns = $this->mTitle->getNamespace();
1394 $title = $this->mTitle->getDBkey();
1395 $old = $dbr->selectRow( 'old',
1396 array( 'old_text', 'old_flags' ),
1397 array(
1398 'old_namespace' => $ns,
1399 'old_title' => $title,
1400 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1401 );
1402
1403 if( $old !== false && !$confirm ) {
1404 $skin=$wgUser->getSkin();
1405 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1406 $wgOut->addHTML( $skin->historyLink() .'</b>');
1407 }
1408
1409 # Fetch cur_text
1410 $s = $dbr->selectRow( 'cur',
1411 array( 'cur_text' ),
1412 array(
1413 'cur_namespace' => $ns,
1414 'cur_title' => $title,
1415 ), $fname, $this->getSelectOptions()
1416 );
1417
1418 if( $s !== false ) {
1419 # if this is a mini-text, we can paste part of it into the deletion reason
1420
1421 #if this is empty, an earlier revision may contain "useful" text
1422 $blanked = false;
1423 if($s->cur_text != '') {
1424 $text=$s->cur_text;
1425 } else {
1426 if($old) {
1427 $text = Article::getRevisionText( $old );
1428 $blanked = true;
1429 }
1430
1431 }
1432
1433 $length=strlen($text);
1434
1435 # this should not happen, since it is not possible to store an empty, new
1436 # page. Let's insert a standard text in case it does, though
1437 if($length == 0 && $reason === '') {
1438 $reason = wfMsg('exblank');
1439 }
1440
1441 if($length < 500 && $reason === '') {
1442
1443 # comment field=255, let's grep the first 150 to have some user
1444 # space left
1445 $text=substr($text,0,150);
1446 # let's strip out newlines and HTML tags
1447 $text=preg_replace('/\"/',"'",$text);
1448 $text=preg_replace('/\</','&lt;',$text);
1449 $text=preg_replace('/\>/','&gt;',$text);
1450 $text=preg_replace("/[\n\r]/",'',$text);
1451 if(!$blanked) {
1452 $reason=wfMsg('excontent'). " '".$text;
1453 } else {
1454 $reason=wfMsg('exbeforeblank') . " '".$text;
1455 }
1456 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1457 $reason.="'";
1458 }
1459 }
1460
1461 return $this->confirmDelete( '', $reason );
1462 }
1463
1464 /**
1465 * Output deletion confirmation dialog
1466 */
1467 function confirmDelete( $par, $reason ) {
1468 global $wgOut;
1469
1470 wfDebug( "Article::confirmDelete\n" );
1471
1472 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1473 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1474 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1475 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1476
1477 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1478
1479 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1480 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1481 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1482
1483 $wgOut->addHTML( "
1484 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1485 <table border='0'>
1486 <tr>
1487 <td align='right'>
1488 <label for='wpReason'>{$delcom}:</label>
1489 </td>
1490 <td align='left'>
1491 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1492 </td>
1493 </tr>
1494 <tr>
1495 <td>&nbsp;</td>
1496 </tr>
1497 <tr>
1498 <td align='right'>
1499 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1500 </td>
1501 <td>
1502 <label for='wpConfirm'>{$check}</label>
1503 </td>
1504 </tr>
1505 <tr>
1506 <td>&nbsp;</td>
1507 <td>
1508 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1509 </td>
1510 </tr>
1511 </table>
1512 </form>\n" );
1513
1514 $wgOut->returnToMain( false );
1515 }
1516
1517
1518 /**
1519 * Perform a deletion and output success or failure messages
1520 */
1521 function doDelete( $reason ) {
1522 global $wgOut, $wgUser, $wgContLang;
1523 $fname = 'Article::doDelete';
1524 wfDebug( $fname."\n" );
1525
1526 if ( $this->doDeleteArticle( $reason ) ) {
1527 $deleted = $this->mTitle->getPrefixedText();
1528
1529 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1530 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1531
1532 $sk = $wgUser->getSkin();
1533 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT ) .
1534 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1535
1536 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1537
1538 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1539 $wgOut->returnToMain( false );
1540 } else {
1541 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1542 }
1543 }
1544
1545 /**
1546 * Back-end article deletion
1547 * Deletes the article with database consistency, writes logs, purges caches
1548 * Returns success
1549 */
1550 function doDeleteArticle( $reason ) {
1551 global $wgUser;
1552 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1553
1554 $fname = 'Article::doDeleteArticle';
1555 wfDebug( $fname."\n" );
1556
1557 $dbw =& wfGetDB( DB_MASTER );
1558 $ns = $this->mTitle->getNamespace();
1559 $t = $this->mTitle->getDBkey();
1560 $id = $this->mTitle->getArticleID();
1561
1562 if ( $t == '' || $id == 0 ) {
1563 return false;
1564 }
1565
1566 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1567 array_push( $wgDeferredUpdateList, $u );
1568
1569 $linksTo = $this->mTitle->getLinksTo();
1570
1571 # Squid purging
1572 if ( $wgUseSquid ) {
1573 $urls = array(
1574 $this->mTitle->getInternalURL(),
1575 $this->mTitle->getInternalURL( 'history' )
1576 );
1577 foreach ( $linksTo as $linkTo ) {
1578 $urls[] = $linkTo->getInternalURL();
1579 }
1580
1581 $u = new SquidUpdate( $urls );
1582 array_push( $wgDeferredUpdateList, $u );
1583
1584 }
1585
1586 # Client and file cache invalidation
1587 Title::touchArray( $linksTo );
1588
1589 # Move article and history to the "archive" table
1590 $archiveTable = $dbw->tableName( 'archive' );
1591 $oldTable = $dbw->tableName( 'old' );
1592 $curTable = $dbw->tableName( 'cur' );
1593 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1594 $linksTable = $dbw->tableName( 'links' );
1595 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1596
1597 $dbw->insertSelect( 'archive', 'cur',
1598 array(
1599 'ar_namespace' => 'cur_namespace',
1600 'ar_title' => 'cur_title',
1601 'ar_text' => 'cur_text',
1602 'ar_comment' => 'cur_comment',
1603 'ar_user' => 'cur_user',
1604 'ar_user_text' => 'cur_user_text',
1605 'ar_timestamp' => 'cur_timestamp',
1606 'ar_minor_edit' => 'cur_minor_edit',
1607 'ar_flags' => 0,
1608 ), array(
1609 'cur_namespace' => $ns,
1610 'cur_title' => $t,
1611 ), $fname
1612 );
1613
1614 $dbw->insertSelect( 'archive', 'old',
1615 array(
1616 'ar_namespace' => 'old_namespace',
1617 'ar_title' => 'old_title',
1618 'ar_text' => 'old_text',
1619 'ar_comment' => 'old_comment',
1620 'ar_user' => 'old_user',
1621 'ar_user_text' => 'old_user_text',
1622 'ar_timestamp' => 'old_timestamp',
1623 'ar_minor_edit' => 'old_minor_edit',
1624 'ar_flags' => 'old_flags'
1625 ), array(
1626 'old_namespace' => $ns,
1627 'old_title' => $t,
1628 ), $fname
1629 );
1630
1631 # Now that it's safely backed up, delete it
1632
1633 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1634 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1635 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1636
1637 # Finally, clean up the link tables
1638 $t = $this->mTitle->getPrefixedDBkey();
1639
1640 Article::onArticleDelete( $this->mTitle );
1641
1642 # Insert broken links
1643 $brokenLinks = array();
1644 foreach ( $linksTo as $titleObj ) {
1645 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1646 $linkID = $titleObj->getArticleID();
1647 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1648 }
1649 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1650
1651 # Delete live links
1652 $dbw->delete( 'links', array( 'l_to' => $id ) );
1653 $dbw->delete( 'links', array( 'l_from' => $id ) );
1654 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1655 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1656 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1657
1658 # Log the deletion
1659 $log = new LogPage( 'delete' );
1660 $log->addEntry( 'delete', $this->mTitle, $reason );
1661
1662 # Clear the cached article id so the interface doesn't act like we exist
1663 $this->mTitle->resetArticleID( 0 );
1664 $this->mTitle->mArticleID = 0;
1665 return true;
1666 }
1667
1668 /**
1669 * Revert a modification
1670 */
1671 function rollback() {
1672 global $wgUser, $wgOut, $wgRequest;
1673 $fname = 'Article::rollback';
1674
1675 if ( ! $wgUser->isAllowed('rollback') ) {
1676 $wgOut->sysopRequired();
1677 return;
1678 }
1679 if ( wfReadOnly() ) {
1680 $wgOut->readOnlyPage( $this->getContent( true ) );
1681 return;
1682 }
1683 $dbw =& wfGetDB( DB_MASTER );
1684
1685 # Enhanced rollback, marks edits rc_bot=1
1686 $bot = $wgRequest->getBool( 'bot' );
1687
1688 # Replace all this user's current edits with the next one down
1689 $tt = $this->mTitle->getDBKey();
1690 $n = $this->mTitle->getNamespace();
1691
1692 # Get the last editor, lock table exclusively
1693 $s = $dbw->selectRow( 'cur',
1694 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1695 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1696 $fname, 'FOR UPDATE'
1697 );
1698 if( $s === false ) {
1699 # Something wrong
1700 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1701 return;
1702 }
1703 $ut = $dbw->strencode( $s->cur_user_text );
1704 $uid = $s->cur_user;
1705 $pid = $s->cur_id;
1706
1707 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1708 if( $from != $s->cur_user_text ) {
1709 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1710 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1711 htmlspecialchars( $this->mTitle->getPrefixedText()),
1712 htmlspecialchars( $from ),
1713 htmlspecialchars( $s->cur_user_text ) ) );
1714 if($s->cur_comment != '') {
1715 $wgOut->addHTML(
1716 wfMsg('editcomment',
1717 htmlspecialchars( $s->cur_comment ) ) );
1718 }
1719 return;
1720 }
1721
1722 # Get the last edit not by this guy
1723 $s = $dbw->selectRow( 'old',
1724 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1725 array(
1726 'old_namespace' => $n,
1727 'old_title' => $tt,
1728 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1729 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1730 );
1731 if( $s === false ) {
1732 # Something wrong
1733 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1734 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1735 return;
1736 }
1737
1738 if ( $bot ) {
1739 # Mark all reverted edits as bot
1740 $dbw->update( 'recentchanges',
1741 array( /* SET */
1742 'rc_bot' => 1
1743 ), array( /* WHERE */
1744 'rc_user' => $uid,
1745 "rc_timestamp > '{$s->old_timestamp}'",
1746 ), $fname
1747 );
1748 }
1749
1750 # Save it!
1751 $newcomment = wfMsg( 'revertpage', $s->old_user_text, $from );
1752 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1753 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1754 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1755 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1756 Article::onArticleEdit( $this->mTitle );
1757 $wgOut->returnToMain( false );
1758 }
1759
1760
1761 /**
1762 * Do standard deferred updates after page view
1763 * @private
1764 */
1765 function viewUpdates() {
1766 global $wgDeferredUpdateList;
1767 if ( 0 != $this->getID() ) {
1768 global $wgDisableCounters;
1769 if( !$wgDisableCounters ) {
1770 Article::incViewCount( $this->getID() );
1771 $u = new SiteStatsUpdate( 1, 0, 0 );
1772 array_push( $wgDeferredUpdateList, $u );
1773 }
1774 }
1775 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1776 $this->mTitle->getDBkey() );
1777 array_push( $wgDeferredUpdateList, $u );
1778 }
1779
1780 /**
1781 * Do standard deferred updates after page edit.
1782 * Every 1000th edit, prune the recent changes table.
1783 * @private
1784 * @param string $text
1785 */
1786 function editUpdates( $text ) {
1787 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1788 global $wgMessageCache;
1789
1790 wfSeedRandom();
1791 if ( 0 == mt_rand( 0, 999 ) ) {
1792 $dbw =& wfGetDB( DB_MASTER );
1793 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1794 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1795 $dbw->query( $sql );
1796 }
1797 $id = $this->getID();
1798 $title = $this->mTitle->getPrefixedDBkey();
1799 $shortTitle = $this->mTitle->getDBkey();
1800
1801 $adj = $this->mCountAdjustment;
1802
1803 if ( 0 != $id ) {
1804 $u = new LinksUpdate( $id, $title );
1805 array_push( $wgDeferredUpdateList, $u );
1806 $u = new SiteStatsUpdate( 0, 1, $adj );
1807 array_push( $wgDeferredUpdateList, $u );
1808 $u = new SearchUpdate( $id, $title, $text );
1809 array_push( $wgDeferredUpdateList, $u );
1810
1811 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1812 array_push( $wgDeferredUpdateList, $u );
1813
1814 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1815 $wgMessageCache->replace( $shortTitle, $text );
1816 }
1817 }
1818 }
1819
1820 /**
1821 * @todo document this function
1822 * @private
1823 * @param string $oldid Revision ID of this article revision
1824 */
1825 function setOldSubtitle( $oldid=0 ) {
1826 global $wgLang, $wgOut, $wgUser;
1827
1828 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1829 $sk = $wgUser->getSkin();
1830 $lnk = $sk->makeKnownLinkObj ( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
1831 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1832 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1833 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1834 $wgOut->setSubtitle( $r );
1835 }
1836
1837 /**
1838 * This function is called right before saving the wikitext,
1839 * so we can do things like signatures and links-in-context.
1840 *
1841 * @param string $text
1842 */
1843 function preSaveTransform( $text ) {
1844 global $wgParser, $wgUser;
1845 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1846 }
1847
1848 /* Caching functions */
1849
1850 /**
1851 * checkLastModified returns true if it has taken care of all
1852 * output to the client that is necessary for this request.
1853 * (that is, it has sent a cached version of the page)
1854 */
1855 function tryFileCache() {
1856 static $called = false;
1857 if( $called ) {
1858 wfDebug( " tryFileCache() -- called twice!?\n" );
1859 return;
1860 }
1861 $called = true;
1862 if($this->isFileCacheable()) {
1863 $touched = $this->mTouched;
1864 if( $this->mTitle->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1865 # Expire the main page quicker
1866 $expire = wfUnix2Timestamp( time() - 3600 );
1867 $touched = max( $expire, $touched );
1868 }
1869 $cache = new CacheManager( $this->mTitle );
1870 if($cache->isFileCacheGood( $touched )) {
1871 global $wgOut;
1872 wfDebug( " tryFileCache() - about to load\n" );
1873 $cache->loadFromFileCache();
1874 return true;
1875 } else {
1876 wfDebug( " tryFileCache() - starting buffer\n" );
1877 ob_start( array(&$cache, 'saveToFileCache' ) );
1878 }
1879 } else {
1880 wfDebug( " tryFileCache() - not cacheable\n" );
1881 }
1882 }
1883
1884 /**
1885 * Check if the page can be cached
1886 * @return bool
1887 */
1888 function isFileCacheable() {
1889 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1890 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1891
1892 return $wgUseFileCache
1893 and (!$wgShowIPinHeader)
1894 and ($this->getID() != 0)
1895 and ($wgUser->getId() == 0)
1896 and (!$wgUser->getNewtalk())
1897 and ($this->mTitle->getNamespace() != NS_SPECIAL )
1898 and (empty( $action ) || $action == 'view')
1899 and (!isset($oldid))
1900 and (!isset($diff))
1901 and (!isset($redirect))
1902 and (!isset($printable))
1903 and (!$this->mRedirectedFrom);
1904 }
1905
1906 /**
1907 * Loads cur_touched and returns a value indicating if it should be used
1908 *
1909 */
1910 function checkTouched() {
1911 $fname = 'Article::checkTouched';
1912 $id = $this->getID();
1913 $dbr =& $this->getDB();
1914 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1915 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1916 if( $s !== false ) {
1917 $this->mTouched = wfTimestamp(TS_MW,$s->cur_touched);
1918 return !$s->cur_is_redirect;
1919 } else {
1920 return false;
1921 }
1922 }
1923
1924 /**
1925 * Edit an article without doing all that other stuff
1926 *
1927 * @param string $text text submitted
1928 * @param string $comment comment submitted
1929 * @param integer $minor whereas it's a minor modification
1930 */
1931 function quickEdit( $text, $comment = '', $minor = 0 ) {
1932 global $wgUser;
1933 $fname = 'Article::quickEdit';
1934 wfProfileIn( $fname );
1935
1936 $dbw =& wfGetDB( DB_MASTER );
1937 $ns = $this->mTitle->getNamespace();
1938 $dbkey = $this->mTitle->getDBkey();
1939 $encDbKey = $dbw->strencode( $dbkey );
1940 $timestamp = wfTimestampNow();
1941
1942 # Save to history
1943 $dbw->insertSelect( 'old', 'cur',
1944 array(
1945 'old_namespace' => 'cur_namespace',
1946 'old_title' => 'cur_title',
1947 'old_text' => 'cur_text',
1948 'old_comment' => 'cur_comment',
1949 'old_user' => 'cur_user',
1950 'old_user_text' => 'cur_user_text',
1951 'old_timestamp' => 'cur_timestamp',
1952 'inverse_timestamp' => '99999999999999-cur_timestamp',
1953 ), array(
1954 'cur_namespace' => $ns,
1955 'cur_title' => $dbkey,
1956 ), $fname
1957 );
1958
1959 # Use the affected row count to determine if the article is new
1960 $numRows = $dbw->affectedRows();
1961
1962 # Make an array of fields to be inserted
1963 $fields = array(
1964 'cur_text' => $text,
1965 'cur_timestamp' => $timestamp,
1966 'cur_user' => $wgUser->getID(),
1967 'cur_user_text' => $wgUser->getName(),
1968 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1969 'cur_comment' => $comment,
1970 'cur_is_redirect' => $this->isRedirect( $text ) ? 1 : 0,
1971 'cur_minor_edit' => intval($minor),
1972 'cur_touched' => $dbw->timestamp($timestamp),
1973 );
1974
1975 if ( $numRows ) {
1976 # Update article
1977 $fields['cur_is_new'] = 0;
1978 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1979 } else {
1980 # Insert new article
1981 $fields['cur_is_new'] = 1;
1982 $fields['cur_namespace'] = $ns;
1983 $fields['cur_title'] = $dbkey;
1984 $fields['cur_random'] = $rand = wfRandom();
1985 $dbw->insert( 'cur', $fields, $fname );
1986 }
1987 wfProfileOut( $fname );
1988 }
1989
1990 /**
1991 * Used to increment the view counter
1992 *
1993 * @static
1994 * @param integer $id article id
1995 */
1996 function incViewCount( $id ) {
1997 $id = intval( $id );
1998 global $wgHitcounterUpdateFreq;
1999
2000 $dbw =& wfGetDB( DB_MASTER );
2001 $curTable = $dbw->tableName( 'cur' );
2002 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2003 $acchitsTable = $dbw->tableName( 'acchits' );
2004
2005 if( $wgHitcounterUpdateFreq <= 1 ){ //
2006 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2007 return;
2008 }
2009
2010 # Not important enough to warrant an error page in case of failure
2011 $oldignore = $dbw->ignoreErrors( true );
2012
2013 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2014
2015 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2016 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2017 # Most of the time (or on SQL errors), skip row count check
2018 $dbw->ignoreErrors( $oldignore );
2019 return;
2020 }
2021
2022 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2023 $row = $dbw->fetchObject( $res );
2024 $rown = intval( $row->n );
2025 if( $rown >= $wgHitcounterUpdateFreq ){
2026 wfProfileIn( 'Article::incViewCount-collect' );
2027 $old_user_abort = ignore_user_abort( true );
2028
2029 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2030 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2031 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2032 'GROUP BY hc_id');
2033 $dbw->query("DELETE FROM $hitcounterTable");
2034 $dbw->query('UNLOCK TABLES');
2035 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2036 'WHERE cur_id = hc_id');
2037 $dbw->query("DROP TABLE $acchitsTable");
2038
2039 ignore_user_abort( $old_user_abort );
2040 wfProfileOut( 'Article::incViewCount-collect' );
2041 }
2042 $dbw->ignoreErrors( $oldignore );
2043 }
2044
2045 /**#@+
2046 * The onArticle*() functions are supposed to be a kind of hooks
2047 * which should be called whenever any of the specified actions
2048 * are done.
2049 *
2050 * This is a good place to put code to clear caches, for instance.
2051 *
2052 * This is called on page move and undelete, as well as edit
2053 * @static
2054 * @param $title_obj a title object
2055 */
2056
2057 function onArticleCreate($title_obj) {
2058 global $wgUseSquid, $wgDeferredUpdateList;
2059
2060 $titles = $title_obj->getBrokenLinksTo();
2061
2062 # Purge squid
2063 if ( $wgUseSquid ) {
2064 $urls = $title_obj->getSquidURLs();
2065 foreach ( $titles as $linkTitle ) {
2066 $urls[] = $linkTitle->getInternalURL();
2067 }
2068 $u = new SquidUpdate( $urls );
2069 array_push( $wgDeferredUpdateList, $u );
2070 }
2071
2072 # Clear persistent link cache
2073 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2074 }
2075
2076 function onArticleDelete($title_obj) {
2077 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
2078 }
2079 function onArticleEdit($title_obj) {
2080 LinkCache::linksccClearPage( $title_obj->getArticleID() );
2081 }
2082 /**#@-*/
2083
2084 /**
2085 * Info about this page
2086 */
2087 function info() {
2088 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2089 $fname = 'Article::info';
2090
2091 if ( !$wgAllowPageInfo ) {
2092 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2093 return;
2094 }
2095
2096 $dbr =& $this->getDB();
2097
2098 $basenamespace = $wgTitle->getNamespace() & (~1);
2099 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2100 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2101 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2102 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2103 $wgOut->setPagetitle( $fullTitle );
2104 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2105
2106 # first, see if the page exists at all.
2107 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2108 if ($exists < 1) {
2109 $wgOut->addHTML( wfMsg('noarticletext') );
2110 } else {
2111 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2112 $this->getSelectOptions() );
2113 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2114 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2115 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old + 1) . '</li>');
2116
2117 # to find number of distinct authors, we need to do some
2118 # funny stuff because of the cur/old table split:
2119 # - first, find the name of the 'cur' author
2120 # - then, find the number of *other* authors in 'old'
2121
2122 # find 'cur' author
2123 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2124 $this->getSelectOptions() );
2125
2126 # find number of 'old' authors excluding 'cur' author
2127 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2128 $old_clause + array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2129 $this->getSelectOptions() ) + 1;
2130
2131 # now for the Talk page ...
2132 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+1 );
2133 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+1 );
2134
2135 # does it exist?
2136 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2137
2138 # number of edits
2139 if ($exists > 0) {
2140 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2141 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old + 1) . '</li>');
2142 }
2143 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2144
2145 # number of authors
2146 if ($exists > 0) {
2147 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2148 $this->getSelectOptions() );
2149 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2150 $old_clause + array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2151 $fname, $this->getSelectOptions() );
2152
2153 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2154 }
2155 }
2156 }
2157 }
2158
2159 ?>