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