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