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