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