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