Since updates are no longer truly deferred, replaced code for adding
[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
1220 if ( 0 == $wgUser->getID() ) {
1221 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1222 return;
1223 }
1224 if ( wfReadOnly() ) {
1225 $wgOut->readOnlyPage();
1226 return;
1227 }
1228 if( $add )
1229 $wgUser->addWatch( $this->mTitle );
1230 else
1231 $wgUser->removeWatch( $this->mTitle );
1232
1233 $wgOut->setPagetitle( wfMsg( $add ? 'addedwatch' : 'removedwatch' ) );
1234 $wgOut->setRobotpolicy( 'noindex,follow' );
1235
1236 $sk = $wgUser->getSkin() ;
1237 $link = $this->mTitle->getPrefixedText();
1238
1239 if($add)
1240 $text = wfMsg( 'addedwatchtext', $link );
1241 else
1242 $text = wfMsg( 'removedwatchtext', $link );
1243 $wgOut->addWikiText( $text );
1244
1245 $wgUser->saveSettings();
1246
1247 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1248 }
1249
1250 /**
1251 * Stop watching a page, it act just like a call to watch(false)
1252 */
1253 function unwatch() {
1254 $this->watch( false );
1255 }
1256
1257 /**
1258 * protect a page
1259 */
1260 function protect( $limit = 'sysop' ) {
1261 global $wgUser, $wgOut, $wgRequest;
1262
1263 if ( ! $wgUser->isAllowed('protect') ) {
1264 $wgOut->sysopRequired();
1265 return;
1266 }
1267 if ( wfReadOnly() ) {
1268 $wgOut->readOnlyPage();
1269 return;
1270 }
1271 $id = $this->mTitle->getArticleID();
1272 if ( 0 == $id ) {
1273 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1274 return;
1275 }
1276
1277 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1278 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1279 $reason = $wgRequest->getText( 'wpReasonProtect' );
1280
1281 if ( $confirm ) {
1282
1283 $restrictions = "move=" . $limit;
1284 if( !$moveonly ) {
1285 $restrictions .= ":edit=" . $limit;
1286 }
1287 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
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 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1300
1301 $log = new LogPage( 'protect' );
1302 if ( $limit === '' ) {
1303 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1304 } else {
1305 $log->addEntry( 'protect', $this->mTitle, $reason );
1306 }
1307 $wgOut->redirect( $this->mTitle->getFullURL() );
1308 }
1309 return;
1310 } else {
1311 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1312 return $this->confirmProtect( '', $reason, $limit );
1313 }
1314 }
1315
1316 /**
1317 * Output protection confirmation dialog
1318 */
1319 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1320 global $wgOut;
1321
1322 wfDebug( "Article::confirmProtect\n" );
1323
1324 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1325 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1326
1327 $check = '';
1328 $protcom = '';
1329 $moveonly = '';
1330
1331 if ( $limit === '' ) {
1332 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1333 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1334 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1335 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1336 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1337 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1338 } else {
1339 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1340 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1341 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1342 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1343 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1344 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1345 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1346 }
1347
1348 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1349
1350 $wgOut->addHTML( "
1351 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1352 <table border='0'>
1353 <tr>
1354 <td align='right'>
1355 <label for='wpReasonProtect'>{$protcom}:</label>
1356 </td>
1357 <td align='left'>
1358 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1359 </td>
1360 </tr>
1361 <tr>
1362 <td>&nbsp;</td>
1363 </tr>
1364 <tr>
1365 <td align='right'>
1366 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1367 </td>
1368 <td>
1369 <label for='wpConfirmProtect'>{$check}</label>
1370 </td>
1371 </tr> " );
1372 if($moveonly != '') {
1373 $wgOut->AddHTML( "
1374 <tr>
1375 <td align='right'>
1376 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1377 </td>
1378 <td>
1379 <label for='wpMoveOnly'>{$moveonly}</label>
1380 </td>
1381 </tr> " );
1382 }
1383 $wgOut->addHTML( "
1384 <tr>
1385 <td>&nbsp;</td>
1386 <td>
1387 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1388 </td>
1389 </tr>
1390 </table>
1391 </form>\n" );
1392
1393 $wgOut->returnToMain( false );
1394 }
1395
1396 /**
1397 * Unprotect the pages
1398 */
1399 function unprotect() {
1400 return $this->protect( '' );
1401 }
1402
1403 /*
1404 * UI entry point for page deletion
1405 */
1406 function delete() {
1407 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1408 $fname = 'Article::delete';
1409 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1410 $reason = $wgRequest->getText( 'wpReason' );
1411
1412 # This code desperately needs to be totally rewritten
1413
1414 # Check permissions
1415 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1416 $wgOut->sysopRequired();
1417 return;
1418 }
1419 if ( wfReadOnly() ) {
1420 $wgOut->readOnlyPage();
1421 return;
1422 }
1423
1424 # Better double-check that it hasn't been deleted yet!
1425 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1426 if ( ( '' == trim( $this->mTitle->getText() ) )
1427 or ( $this->mTitle->getArticleId() == 0 ) ) {
1428 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1429 return;
1430 }
1431
1432 if ( $confirm ) {
1433 $this->doDelete( $reason );
1434 return;
1435 }
1436
1437 # determine whether this page has earlier revisions
1438 # and insert a warning if it does
1439 # we select the text because it might be useful below
1440 $dbr =& $this->getDB();
1441 $ns = $this->mTitle->getNamespace();
1442 $title = $this->mTitle->getDBkey();
1443 $old = $dbr->selectRow( 'old',
1444 array( 'old_text', 'old_flags' ),
1445 array(
1446 'old_namespace' => $ns,
1447 'old_title' => $title,
1448 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1449 );
1450
1451 if( $old !== false && !$confirm ) {
1452 $skin=$wgUser->getSkin();
1453 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1454 $wgOut->addHTML( $skin->historyLink() .'</b>');
1455 }
1456
1457 # Fetch cur_text
1458 $s = $dbr->selectRow( 'cur',
1459 array( 'cur_text' ),
1460 array(
1461 'cur_namespace' => $ns,
1462 'cur_title' => $title,
1463 ), $fname, $this->getSelectOptions()
1464 );
1465
1466 if( $s !== false ) {
1467 # if this is a mini-text, we can paste part of it into the deletion reason
1468
1469 #if this is empty, an earlier revision may contain "useful" text
1470 $blanked = false;
1471 if($s->cur_text != '') {
1472 $text=$s->cur_text;
1473 } else {
1474 if($old) {
1475 $text = Article::getRevisionText( $old );
1476 $blanked = true;
1477 }
1478
1479 }
1480
1481 $length=strlen($text);
1482
1483 # this should not happen, since it is not possible to store an empty, new
1484 # page. Let's insert a standard text in case it does, though
1485 if($length == 0 && $reason === '') {
1486 $reason = wfMsg('exblank');
1487 }
1488
1489 if($length < 500 && $reason === '') {
1490
1491 # comment field=255, let's grep the first 150 to have some user
1492 # space left
1493 $text=substr($text,0,150);
1494 # let's strip out newlines and HTML tags
1495 $text=preg_replace('/\"/',"'",$text);
1496 $text=preg_replace('/\</','&lt;',$text);
1497 $text=preg_replace('/\>/','&gt;',$text);
1498 $text=preg_replace("/[\n\r]/",'',$text);
1499 if(!$blanked) {
1500 $reason=wfMsg('excontent'). " '".$text;
1501 } else {
1502 $reason=wfMsg('exbeforeblank') . " '".$text;
1503 }
1504 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1505 $reason.="'";
1506 }
1507 }
1508
1509 return $this->confirmDelete( '', $reason );
1510 }
1511
1512 /**
1513 * Output deletion confirmation dialog
1514 */
1515 function confirmDelete( $par, $reason ) {
1516 global $wgOut;
1517
1518 wfDebug( "Article::confirmDelete\n" );
1519
1520 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1521 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1522 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1523 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1524
1525 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1526
1527 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1528 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1529 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1530
1531 $wgOut->addHTML( "
1532 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1533 <table border='0'>
1534 <tr>
1535 <td align='right'>
1536 <label for='wpReason'>{$delcom}:</label>
1537 </td>
1538 <td align='left'>
1539 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1540 </td>
1541 </tr>
1542 <tr>
1543 <td>&nbsp;</td>
1544 </tr>
1545 <tr>
1546 <td align='right'>
1547 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1548 </td>
1549 <td>
1550 <label for='wpConfirm'>{$check}</label>
1551 </td>
1552 </tr>
1553 <tr>
1554 <td>&nbsp;</td>
1555 <td>
1556 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1557 </td>
1558 </tr>
1559 </table>
1560 </form>\n" );
1561
1562 $wgOut->returnToMain( false );
1563 }
1564
1565
1566 /**
1567 * Perform a deletion and output success or failure messages
1568 */
1569 function doDelete( $reason ) {
1570 global $wgOut, $wgUser, $wgContLang;
1571 $fname = 'Article::doDelete';
1572 wfDebug( $fname."\n" );
1573
1574 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1575 if ( $this->doDeleteArticle( $reason ) ) {
1576 $deleted = $this->mTitle->getPrefixedText();
1577
1578 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1579 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1580
1581 $sk = $wgUser->getSkin();
1582 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT ) .
1583 ':' . wfMsgForContent( 'dellogpage' ),
1584 wfMsg( 'deletionlog' ) );
1585
1586 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1587
1588 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1589 $wgOut->returnToMain( false );
1590 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1591 } else {
1592 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1593 }
1594 }
1595 }
1596
1597 /**
1598 * Back-end article deletion
1599 * Deletes the article with database consistency, writes logs, purges caches
1600 * Returns success
1601 */
1602 function doDeleteArticle( $reason ) {
1603 global $wgUser;
1604 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1605
1606 $fname = 'Article::doDeleteArticle';
1607 wfDebug( $fname."\n" );
1608
1609 $dbw =& wfGetDB( DB_MASTER );
1610 $ns = $this->mTitle->getNamespace();
1611 $t = $this->mTitle->getDBkey();
1612 $id = $this->mTitle->getArticleID();
1613
1614 if ( $t == '' || $id == 0 ) {
1615 return false;
1616 }
1617
1618 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1619 array_push( $wgDeferredUpdateList, $u );
1620
1621 $linksTo = $this->mTitle->getLinksTo();
1622
1623 # Squid purging
1624 if ( $wgUseSquid ) {
1625 $urls = array(
1626 $this->mTitle->getInternalURL(),
1627 $this->mTitle->getInternalURL( 'history' )
1628 );
1629 foreach ( $linksTo as $linkTo ) {
1630 $urls[] = $linkTo->getInternalURL();
1631 }
1632
1633 $u = new SquidUpdate( $urls );
1634 array_push( $wgDeferredUpdateList, $u );
1635
1636 }
1637
1638 # Client and file cache invalidation
1639 Title::touchArray( $linksTo );
1640
1641 # Move article and history to the "archive" table
1642 $archiveTable = $dbw->tableName( 'archive' );
1643 $oldTable = $dbw->tableName( 'old' );
1644 $curTable = $dbw->tableName( 'cur' );
1645 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1646 $linksTable = $dbw->tableName( 'links' );
1647 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1648
1649 $dbw->insertSelect( 'archive', 'cur',
1650 array(
1651 'ar_namespace' => 'cur_namespace',
1652 'ar_title' => 'cur_title',
1653 'ar_text' => 'cur_text',
1654 'ar_comment' => 'cur_comment',
1655 'ar_user' => 'cur_user',
1656 'ar_user_text' => 'cur_user_text',
1657 'ar_timestamp' => 'cur_timestamp',
1658 'ar_minor_edit' => 'cur_minor_edit',
1659 'ar_flags' => 0,
1660 ), array(
1661 'cur_namespace' => $ns,
1662 'cur_title' => $t,
1663 ), $fname
1664 );
1665
1666 $dbw->insertSelect( 'archive', 'old',
1667 array(
1668 'ar_namespace' => 'old_namespace',
1669 'ar_title' => 'old_title',
1670 'ar_text' => 'old_text',
1671 'ar_comment' => 'old_comment',
1672 'ar_user' => 'old_user',
1673 'ar_user_text' => 'old_user_text',
1674 'ar_timestamp' => 'old_timestamp',
1675 'ar_minor_edit' => 'old_minor_edit',
1676 'ar_flags' => 'old_flags'
1677 ), array(
1678 'old_namespace' => $ns,
1679 'old_title' => $t,
1680 ), $fname
1681 );
1682
1683 # Now that it's safely backed up, delete it
1684
1685 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1686 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1687 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1688
1689 # Finally, clean up the link tables
1690 $t = $this->mTitle->getPrefixedDBkey();
1691
1692 Article::onArticleDelete( $this->mTitle );
1693
1694 # Insert broken links
1695 $brokenLinks = array();
1696 foreach ( $linksTo as $titleObj ) {
1697 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1698 $linkID = $titleObj->getArticleID();
1699 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1700 }
1701 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1702
1703 # Delete live links
1704 $dbw->delete( 'links', array( 'l_to' => $id ) );
1705 $dbw->delete( 'links', array( 'l_from' => $id ) );
1706 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1707 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1708 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1709
1710 # Log the deletion
1711 $log = new LogPage( 'delete' );
1712 $log->addEntry( 'delete', $this->mTitle, $reason );
1713
1714 # Clear the cached article id so the interface doesn't act like we exist
1715 $this->mTitle->resetArticleID( 0 );
1716 $this->mTitle->mArticleID = 0;
1717 return true;
1718 }
1719
1720 /**
1721 * Revert a modification
1722 */
1723 function rollback() {
1724 global $wgUser, $wgOut, $wgRequest;
1725 $fname = 'Article::rollback';
1726
1727 if ( ! $wgUser->isAllowed('rollback') ) {
1728 $wgOut->sysopRequired();
1729 return;
1730 }
1731 if ( wfReadOnly() ) {
1732 $wgOut->readOnlyPage( $this->getContent( true ) );
1733 return;
1734 }
1735 $dbw =& wfGetDB( DB_MASTER );
1736
1737 # Enhanced rollback, marks edits rc_bot=1
1738 $bot = $wgRequest->getBool( 'bot' );
1739
1740 # Replace all this user's current edits with the next one down
1741 $tt = $this->mTitle->getDBKey();
1742 $n = $this->mTitle->getNamespace();
1743
1744 # Get the last editor, lock table exclusively
1745 $s = $dbw->selectRow( 'cur',
1746 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1747 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1748 $fname, 'FOR UPDATE'
1749 );
1750 if( $s === false ) {
1751 # Something wrong
1752 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1753 return;
1754 }
1755 $ut = $dbw->strencode( $s->cur_user_text );
1756 $uid = $s->cur_user;
1757 $pid = $s->cur_id;
1758
1759 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1760 if( $from != $s->cur_user_text ) {
1761 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1762 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1763 htmlspecialchars( $this->mTitle->getPrefixedText()),
1764 htmlspecialchars( $from ),
1765 htmlspecialchars( $s->cur_user_text ) ) );
1766 if($s->cur_comment != '') {
1767 $wgOut->addHTML(
1768 wfMsg('editcomment',
1769 htmlspecialchars( $s->cur_comment ) ) );
1770 }
1771 return;
1772 }
1773
1774 # Get the last edit not by this guy
1775 $s = $dbw->selectRow( 'old',
1776 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1777 array(
1778 'old_namespace' => $n,
1779 'old_title' => $tt,
1780 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1781 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1782 );
1783 if( $s === false ) {
1784 # Something wrong
1785 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1786 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1787 return;
1788 }
1789
1790 if ( $bot ) {
1791 # Mark all reverted edits as bot
1792 $dbw->update( 'recentchanges',
1793 array( /* SET */
1794 'rc_bot' => 1
1795 ), array( /* WHERE */
1796 'rc_user' => $uid,
1797 "rc_timestamp > '{$s->old_timestamp}'",
1798 ), $fname
1799 );
1800 }
1801
1802 # Save it!
1803 $newcomment = wfMsg( 'revertpage', $s->old_user_text, $from );
1804 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1805 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1806 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1807 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1808 Article::onArticleEdit( $this->mTitle );
1809 $wgOut->returnToMain( false );
1810 }
1811
1812
1813 /**
1814 * Do standard deferred updates after page view
1815 * @private
1816 */
1817 function viewUpdates() {
1818 global $wgDeferredUpdateList;
1819 if ( 0 != $this->getID() ) {
1820 global $wgDisableCounters;
1821 if( !$wgDisableCounters ) {
1822 Article::incViewCount( $this->getID() );
1823 $u = new SiteStatsUpdate( 1, 0, 0 );
1824 array_push( $wgDeferredUpdateList, $u );
1825 }
1826 }
1827 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1828 $this->mTitle->getDBkey() );
1829 array_push( $wgDeferredUpdateList, $u );
1830 }
1831
1832 /**
1833 * Do standard deferred updates after page edit.
1834 * Every 1000th edit, prune the recent changes table.
1835 * @private
1836 * @param string $text
1837 */
1838 function editUpdates( $text ) {
1839 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1840 global $wgMessageCache;
1841
1842 wfSeedRandom();
1843 if ( 0 == mt_rand( 0, 999 ) ) {
1844 $dbw =& wfGetDB( DB_MASTER );
1845 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1846 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1847 $dbw->query( $sql );
1848 }
1849 $id = $this->getID();
1850 $title = $this->mTitle->getPrefixedDBkey();
1851 $shortTitle = $this->mTitle->getDBkey();
1852
1853 $adj = $this->mCountAdjustment;
1854
1855 if ( 0 != $id ) {
1856 $u = new LinksUpdate( $id, $title );
1857 array_push( $wgDeferredUpdateList, $u );
1858 $u = new SiteStatsUpdate( 0, 1, $adj );
1859 array_push( $wgDeferredUpdateList, $u );
1860 $u = new SearchUpdate( $id, $title, $text );
1861 array_push( $wgDeferredUpdateList, $u );
1862
1863 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1864 array_push( $wgDeferredUpdateList, $u );
1865
1866 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1867 $wgMessageCache->replace( $shortTitle, $text );
1868 }
1869 }
1870 }
1871
1872 /**
1873 * @todo document this function
1874 * @private
1875 * @param string $oldid Revision ID of this article revision
1876 */
1877 function setOldSubtitle( $oldid=0 ) {
1878 global $wgLang, $wgOut, $wgUser;
1879
1880 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1881 $sk = $wgUser->getSkin();
1882 $lnk = $sk->makeKnownLinkObj ( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
1883 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1884 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1885 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1886 $wgOut->setSubtitle( $r );
1887 }
1888
1889 /**
1890 * This function is called right before saving the wikitext,
1891 * so we can do things like signatures and links-in-context.
1892 *
1893 * @param string $text
1894 */
1895 function preSaveTransform( $text ) {
1896 global $wgParser, $wgUser;
1897 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1898 }
1899
1900 /* Caching functions */
1901
1902 /**
1903 * checkLastModified returns true if it has taken care of all
1904 * output to the client that is necessary for this request.
1905 * (that is, it has sent a cached version of the page)
1906 */
1907 function tryFileCache() {
1908 static $called = false;
1909 if( $called ) {
1910 wfDebug( " tryFileCache() -- called twice!?\n" );
1911 return;
1912 }
1913 $called = true;
1914 if($this->isFileCacheable()) {
1915 $touched = $this->mTouched;
1916 if( $this->mTitle->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1917 # Expire the main page quicker
1918 $expire = wfUnix2Timestamp( time() - 3600 );
1919 $touched = max( $expire, $touched );
1920 }
1921 $cache = new CacheManager( $this->mTitle );
1922 if($cache->isFileCacheGood( $touched )) {
1923 global $wgOut;
1924 wfDebug( " tryFileCache() - about to load\n" );
1925 $cache->loadFromFileCache();
1926 return true;
1927 } else {
1928 wfDebug( " tryFileCache() - starting buffer\n" );
1929 ob_start( array(&$cache, 'saveToFileCache' ) );
1930 }
1931 } else {
1932 wfDebug( " tryFileCache() - not cacheable\n" );
1933 }
1934 }
1935
1936 /**
1937 * Check if the page can be cached
1938 * @return bool
1939 */
1940 function isFileCacheable() {
1941 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1942 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1943
1944 return $wgUseFileCache
1945 and (!$wgShowIPinHeader)
1946 and ($this->getID() != 0)
1947 and ($wgUser->getId() == 0)
1948 and (!$wgUser->getNewtalk())
1949 and ($this->mTitle->getNamespace() != NS_SPECIAL )
1950 and (empty( $action ) || $action == 'view')
1951 and (!isset($oldid))
1952 and (!isset($diff))
1953 and (!isset($redirect))
1954 and (!isset($printable))
1955 and (!$this->mRedirectedFrom);
1956 }
1957
1958 /**
1959 * Loads cur_touched and returns a value indicating if it should be used
1960 *
1961 */
1962 function checkTouched() {
1963 $fname = 'Article::checkTouched';
1964 $id = $this->getID();
1965 $dbr =& $this->getDB();
1966 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1967 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1968 if( $s !== false ) {
1969 $this->mTouched = wfTimestamp(TS_MW,$s->cur_touched);
1970 return !$s->cur_is_redirect;
1971 } else {
1972 return false;
1973 }
1974 }
1975
1976 /**
1977 * Edit an article without doing all that other stuff
1978 *
1979 * @param string $text text submitted
1980 * @param string $comment comment submitted
1981 * @param integer $minor whereas it's a minor modification
1982 */
1983 function quickEdit( $text, $comment = '', $minor = 0 ) {
1984 global $wgUser;
1985 $fname = 'Article::quickEdit';
1986 wfProfileIn( $fname );
1987
1988 $dbw =& wfGetDB( DB_MASTER );
1989 $ns = $this->mTitle->getNamespace();
1990 $dbkey = $this->mTitle->getDBkey();
1991 $encDbKey = $dbw->strencode( $dbkey );
1992 $timestamp = wfTimestampNow();
1993
1994 # Save to history
1995 $dbw->insertSelect( 'old', 'cur',
1996 array(
1997 'old_namespace' => 'cur_namespace',
1998 'old_title' => 'cur_title',
1999 'old_text' => 'cur_text',
2000 'old_comment' => 'cur_comment',
2001 'old_user' => 'cur_user',
2002 'old_user_text' => 'cur_user_text',
2003 'old_timestamp' => 'cur_timestamp',
2004 'inverse_timestamp' => '99999999999999-cur_timestamp',
2005 ), array(
2006 'cur_namespace' => $ns,
2007 'cur_title' => $dbkey,
2008 ), $fname
2009 );
2010
2011 # Use the affected row count to determine if the article is new
2012 $numRows = $dbw->affectedRows();
2013
2014 # Make an array of fields to be inserted
2015 $fields = array(
2016 'cur_text' => $text,
2017 'cur_timestamp' => $timestamp,
2018 'cur_user' => $wgUser->getID(),
2019 'cur_user_text' => $wgUser->getName(),
2020 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2021 'cur_comment' => $comment,
2022 'cur_is_redirect' => $this->isRedirect( $text ) ? 1 : 0,
2023 'cur_minor_edit' => intval($minor),
2024 'cur_touched' => $dbw->timestamp($timestamp),
2025 );
2026
2027 if ( $numRows ) {
2028 # Update article
2029 $fields['cur_is_new'] = 0;
2030 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2031 } else {
2032 # Insert new article
2033 $fields['cur_is_new'] = 1;
2034 $fields['cur_namespace'] = $ns;
2035 $fields['cur_title'] = $dbkey;
2036 $fields['cur_random'] = $rand = wfRandom();
2037 $dbw->insert( 'cur', $fields, $fname );
2038 }
2039 wfProfileOut( $fname );
2040 }
2041
2042 /**
2043 * Used to increment the view counter
2044 *
2045 * @static
2046 * @param integer $id article id
2047 */
2048 function incViewCount( $id ) {
2049 $id = intval( $id );
2050 global $wgHitcounterUpdateFreq;
2051
2052 $dbw =& wfGetDB( DB_MASTER );
2053 $curTable = $dbw->tableName( 'cur' );
2054 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2055 $acchitsTable = $dbw->tableName( 'acchits' );
2056
2057 if( $wgHitcounterUpdateFreq <= 1 ){ //
2058 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2059 return;
2060 }
2061
2062 # Not important enough to warrant an error page in case of failure
2063 $oldignore = $dbw->ignoreErrors( true );
2064
2065 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2066
2067 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2068 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2069 # Most of the time (or on SQL errors), skip row count check
2070 $dbw->ignoreErrors( $oldignore );
2071 return;
2072 }
2073
2074 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2075 $row = $dbw->fetchObject( $res );
2076 $rown = intval( $row->n );
2077 if( $rown >= $wgHitcounterUpdateFreq ){
2078 wfProfileIn( 'Article::incViewCount-collect' );
2079 $old_user_abort = ignore_user_abort( true );
2080
2081 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2082 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2083 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2084 'GROUP BY hc_id');
2085 $dbw->query("DELETE FROM $hitcounterTable");
2086 $dbw->query('UNLOCK TABLES');
2087 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2088 'WHERE cur_id = hc_id');
2089 $dbw->query("DROP TABLE $acchitsTable");
2090
2091 ignore_user_abort( $old_user_abort );
2092 wfProfileOut( 'Article::incViewCount-collect' );
2093 }
2094 $dbw->ignoreErrors( $oldignore );
2095 }
2096
2097 /**#@+
2098 * The onArticle*() functions are supposed to be a kind of hooks
2099 * which should be called whenever any of the specified actions
2100 * are done.
2101 *
2102 * This is a good place to put code to clear caches, for instance.
2103 *
2104 * This is called on page move and undelete, as well as edit
2105 * @static
2106 * @param $title_obj a title object
2107 */
2108
2109 function onArticleCreate($title_obj) {
2110 global $wgUseSquid, $wgDeferredUpdateList;
2111
2112 $titles = $title_obj->getBrokenLinksTo();
2113
2114 # Purge squid
2115 if ( $wgUseSquid ) {
2116 $urls = $title_obj->getSquidURLs();
2117 foreach ( $titles as $linkTitle ) {
2118 $urls[] = $linkTitle->getInternalURL();
2119 }
2120 $u = new SquidUpdate( $urls );
2121 array_push( $wgDeferredUpdateList, $u );
2122 }
2123
2124 # Clear persistent link cache
2125 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2126 }
2127
2128 function onArticleDelete($title_obj) {
2129 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
2130 }
2131 function onArticleEdit($title_obj) {
2132 LinkCache::linksccClearPage( $title_obj->getArticleID() );
2133 }
2134 /**#@-*/
2135
2136 /**
2137 * Info about this page
2138 */
2139 function info() {
2140 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2141 $fname = 'Article::info';
2142
2143 if ( !$wgAllowPageInfo ) {
2144 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2145 return;
2146 }
2147
2148 $dbr =& $this->getDB();
2149
2150 $basenamespace = $wgTitle->getNamespace() & (~1);
2151 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2152 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2153 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2154 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2155 $wgOut->setPagetitle( $fullTitle );
2156 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2157
2158 # first, see if the page exists at all.
2159 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2160 if ($exists < 1) {
2161 $wgOut->addHTML( wfMsg('noarticletext') );
2162 } else {
2163 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2164 $this->getSelectOptions() );
2165 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2166 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2167 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old + 1) . '</li>');
2168
2169 # to find number of distinct authors, we need to do some
2170 # funny stuff because of the cur/old table split:
2171 # - first, find the name of the 'cur' author
2172 # - then, find the number of *other* authors in 'old'
2173
2174 # find 'cur' author
2175 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2176 $this->getSelectOptions() );
2177
2178 # find number of 'old' authors excluding 'cur' author
2179 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2180 $old_clause + array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2181 $this->getSelectOptions() ) + 1;
2182
2183 # now for the Talk page ...
2184 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+1 );
2185 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+1 );
2186
2187 # does it exist?
2188 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2189
2190 # number of edits
2191 if ($exists > 0) {
2192 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2193 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old + 1) . '</li>');
2194 }
2195 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2196
2197 # number of authors
2198 if ($exists > 0) {
2199 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2200 $this->getSelectOptions() );
2201 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2202 $old_clause + array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2203 $fname, $this->getSelectOptions() );
2204
2205 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2206 }
2207 }
2208 }
2209 }
2210
2211 ?>