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