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