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