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