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