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