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