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