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