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