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