Update Article::quickEdit() to use Revision::insertOn()
[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 wfProfileOut( $fname );
736 return $newid;
737 }
738
739 /**
740 * Update the page record to point to a newly saved revision.
741 *
742 * @param Database $dbw
743 * @param int $revId
744 * @param int $lastRevision
745 * @param bool $isRedirect
746 * @return bool true on success, false on failure
747 * @access private
748 */
749 function updateRevisionOn( &$dbw, $revId, $lastRevision = null, $isRedirect = false ) {
750 $fname = 'Article::updateToRevision';
751 wfProfileIn( $fname );
752
753 $conditions = array( 'page_id' => $this->getId() );
754 if( !is_null( $lastRevision ) ) {
755 # An extra check against threads stepping on each other
756 $conditions['page_latest'] = $lastRevision;
757 }
758 $dbw->update( 'page',
759 array( /* SET */
760 'page_latest' => $revId,
761 'page_touched' => $dbw->timestamp(),
762 'page_is_new' => ($lastRevision === 0) ? 0 : 1,
763 'page_is_redirect' => $isRedirect ? 1 : 0,
764 ),
765 $conditions,
766 $fname );
767
768 wfProfileOut( $fname );
769 return ( $dbw->affectedRows() != 0 );
770 }
771
772 /**
773 * Theoretically we could defer these whole insert and update
774 * functions for after display, but that's taking a big leap
775 * of faith, and we want to be able to report database
776 * errors at some point.
777 * @private
778 */
779 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
780 global $wgOut, $wgUser;
781 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
782
783 $fname = 'Article::insertNewArticle';
784
785 $this->mCountAdjustment = $this->isCountable( $text );
786
787 $ns = $this->mTitle->getNamespace();
788 $ttl = $this->mTitle->getDBkey();
789 $text = $this->preSaveTransform( $text );
790 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
791
792 $dbw =& wfGetDB( DB_MASTER );
793
794 # Add the page record; stake our claim on this title!
795 $newid = $this->insertOn( $dbw );
796
797 # Save the revision text...
798 $revision = new Revision( array(
799 'page' => $newid,
800 'comment' => $summary,
801 'minor_edit' => $isminor,
802 'text' => $text
803 ) );
804 $revisionId = $revision->insertOn( $dbw );
805
806 $this->mTitle->resetArticleID( $newid );
807
808 # Update the page record with revision data
809 $this->updateRevisionOn( $dbw, $revisionId, 0, $this->isRedirect( $text ) );
810
811 Article::onArticleCreate( $this->mTitle );
812 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
813
814 if ($watchthis) {
815 if(!$this->mTitle->userIsWatching()) $this->watch();
816 } else {
817 if ( $this->mTitle->userIsWatching() ) {
818 $this->unwatch();
819 }
820 }
821
822 # The talk page isn't in the regular link tables, so we need to update manually:
823 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
824 $dbw->update( 'page',
825 array( 'page_touched' => $dbw->timestamp($now) ),
826 array( 'page_namespace' => $talkns,
827 'page_title' => $ttl ),
828 $fname );
829
830 # standard deferred updates
831 $this->editUpdates( $text, $summary, $isminor, $now );
832
833 $oldid = 0; # new article
834 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
835 }
836
837 /**
838 * Fetch and uncompress the text for a given revision.
839 * Can ask by rev_id number or timestamp (set $field)
840 */
841 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
842 $fname = 'Article::fetchRevisionText';
843 $dbw =& wfGetDB( DB_MASTER );
844 if( $revId ) {
845 $rev = $dbw->addQuotes( $revId );
846 } else {
847 $rev = 'page_latest';
848 }
849 $result = $dbw->query(
850 sprintf( "SELECT old_text, old_flags
851 FROM %s,%s,%s
852 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
853 AND %s=%s",
854 $dbw->tableName( 'page' ),
855 $dbw->tableName( 'revision' ),
856 $dbw->tableName( 'text' ),
857 IntVal( $this->mTitle->getArticleId() ),
858 $field,
859 $rev ),
860 $fname );
861 $obj = $dbw->fetchObject( $result );
862 $dbw->freeResult( $result );
863 $oldtext = Revision::getRevisionText( $obj );
864 return $oldtext;
865 }
866
867 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
868 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
869 if( is_null( $edittime ) ) {
870 $oldtext = $this->fetchRevisionText();
871 } else {
872 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
873 }
874 if ($section != '') {
875 if($section=='new') {
876 if($summary) $subject="== {$summary} ==\n\n";
877 $text=$oldtext."\n\n".$subject.$text;
878 } else {
879
880 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
881 # comments to be stripped as well)
882 $striparray=array();
883 $parser=new Parser();
884 $parser->mOutputType=OT_WIKI;
885 $oldtext=$parser->strip($oldtext, $striparray, true);
886
887 # now that we can be sure that no pseudo-sections are in the source,
888 # split it up
889 # Unfortunately we can't simply do a preg_replace because that might
890 # replace the wrong section, so we have to use the section counter instead
891 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
892 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
893 $secs[$section*2]=$text."\n\n"; // replace with edited
894
895 # section 0 is top (intro) section
896 if($section!=0) {
897
898 # headline of old section - we need to go through this section
899 # to determine if there are any subsections that now need to
900 # be erased, as the mother section has been replaced with
901 # the text of all subsections.
902 $headline=$secs[$section*2-1];
903 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
904 $hlevel=$matches[1];
905
906 # determine headline level for wikimarkup headings
907 if(strpos($hlevel,'=')!==false) {
908 $hlevel=strlen($hlevel);
909 }
910
911 $secs[$section*2-1]=''; // erase old headline
912 $count=$section+1;
913 $break=false;
914 while(!empty($secs[$count*2-1]) && !$break) {
915
916 $subheadline=$secs[$count*2-1];
917 preg_match(
918 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
919 $subhlevel=$matches[1];
920 if(strpos($subhlevel,'=')!==false) {
921 $subhlevel=strlen($subhlevel);
922 }
923 if($subhlevel > $hlevel) {
924 // erase old subsections
925 $secs[$count*2-1]='';
926 $secs[$count*2]='';
927 }
928 if($subhlevel <= $hlevel) {
929 $break=true;
930 }
931 $count++;
932
933 }
934
935 }
936 $text=join('',$secs);
937 # reinsert the stuff that we stripped out earlier
938 $text=$parser->unstrip($text,$striparray);
939 $text=$parser->unstripNoWiki($text,$striparray);
940 }
941
942 }
943 return $text;
944 }
945
946 /**
947 * Change an existing article. Puts the previous version back into the old table, updates RC
948 * and all necessary caches, mostly via the deferred update array.
949 *
950 * It is possible to call this function from a command-line script, but note that you should
951 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
952 */
953 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
954 global $wgOut, $wgUser;
955 global $wgDBtransactions, $wgMwRedir;
956 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
957
958 $fname = 'Article::updateArticle';
959 $good = true;
960
961 $isminor = ( $minor && $wgUser->isLoggedIn() );
962 if ( $this->isRedirect( $text ) ) {
963 # Remove all content but redirect
964 # This could be done by reconstructing the redirect from a title given by
965 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
966 # wants to see
967 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
968 $redir = 1;
969 $text = $m[1] . "\n";
970 }
971 }
972 else { $redir = 0; }
973
974 $text = $this->preSaveTransform( $text );
975 $dbw =& wfGetDB( DB_MASTER );
976
977 # Update article, but only if changed.
978
979 # It's important that we either rollback or complete, otherwise an attacker could
980 # overwrite cur entries by sending precisely timed user aborts. Random bored users
981 # could conceivably have the same effect, especially if cur is locked for long periods.
982 if( $wgDBtransactions ) {
983 $dbw->query( 'BEGIN', $fname );
984 } else {
985 $userAbort = ignore_user_abort( true );
986 }
987
988 $oldtext = $this->getContent( true );
989
990 if ( 0 != strcmp( $text, $oldtext ) ) {
991 $this->mCountAdjustment = $this->isCountable( $text )
992 - $this->isCountable( $oldtext );
993 $now = wfTimestampNow();
994
995 $lastRevision = $dbw->selectField(
996 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
997
998 $revision = new Revision( array(
999 'page' => $this->getId(),
1000 'comment' => $summary,
1001 'minor_edit' => $isminor,
1002 'text' => $text
1003 ) );
1004 $revisionId = $revision->insertOn( $dbw );
1005
1006 # Update page
1007 $ok = $this->updateRevisionOn( $dbw, $revisionId, $lastRevision, $redir );
1008
1009 if( !$ok ) {
1010 /* Belated edit conflict! Run away!! */
1011 $good = false;
1012 } else {
1013 # Update recentchanges and purge cache and whatnot
1014 $bot = (int)($wgUser->isBot() || $forceBot);
1015 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
1016 $lastRevision, $this->getTimestamp(), $bot );
1017 Article::onArticleEdit( $this->mTitle );
1018 }
1019 }
1020
1021 if( $wgDBtransactions ) {
1022 $dbw->query( 'COMMIT', $fname );
1023 } else {
1024 ignore_user_abort( $userAbort );
1025 }
1026
1027 if ( $good ) {
1028 if ($watchthis) {
1029 if (!$this->mTitle->userIsWatching()) $this->watch();
1030 } else {
1031 if ( $this->mTitle->userIsWatching() ) {
1032 $this->unwatch();
1033 }
1034 }
1035 # standard deferred updates
1036 $this->editUpdates( $text, $summary, $minor, $now );
1037
1038
1039 $urls = array();
1040 # Template namespace
1041 # Purge all articles linking here
1042 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1043 $titles = $this->mTitle->getLinksTo();
1044 Title::touchArray( $titles );
1045 if ( $wgUseSquid ) {
1046 foreach ( $titles as $title ) {
1047 $urls[] = $title->getInternalURL();
1048 }
1049 }
1050 }
1051
1052 # Squid updates
1053 if ( $wgUseSquid ) {
1054 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1055 $u = new SquidUpdate( $urls );
1056 array_push( $wgPostCommitUpdateList, $u );
1057 }
1058
1059 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1060 }
1061 return $good;
1062 }
1063
1064 /**
1065 * After we've either updated or inserted the article, update
1066 * the link tables and redirect to the new page.
1067 */
1068 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1069 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1070
1071 $wgLinkCache = new LinkCache();
1072 # Select for update
1073 $wgLinkCache->forUpdate( true );
1074
1075 # Get old version of link table to allow incremental link updates
1076 $wgLinkCache->preFill( $this->mTitle );
1077 $wgLinkCache->clear();
1078
1079 # Parse the text and replace links with placeholders
1080 $wgOut = new OutputPage();
1081 $wgOut->addWikiText( $text );
1082
1083 # Look up the links in the DB and add them to the link cache
1084 $wgOut->transformBuffer( RLH_FOR_UPDATE );
1085
1086 if( $this->isRedirect( $text ) )
1087 $r = 'redirect=no';
1088 else
1089 $r = '';
1090 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1091
1092 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1093 # this will be improved later (to-do)
1094
1095 include_once( "UserMailer.php" );
1096 $wgEnotif = new EmailNotification ();
1097 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle->getDBkey(), $this->mTitle->getNamespace(),$now, $summary, $me2, $oldid );
1098 }
1099
1100 /**
1101 * Mark this particular edit as patrolled
1102 */
1103 function markpatrolled() {
1104 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1105 $wgOut->setRobotpolicy( 'noindex,follow' );
1106
1107 if ( !$wgUseRCPatrol )
1108 {
1109 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1110 return;
1111 }
1112 if ( $wgUser->isAnon() )
1113 {
1114 $wgOut->loginToUse();
1115 return;
1116 }
1117 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1118 {
1119 $wgOut->sysopRequired();
1120 return;
1121 }
1122 $rcid = $wgRequest->getVal( 'rcid' );
1123 if ( !is_null ( $rcid ) )
1124 {
1125 RecentChange::markPatrolled( $rcid );
1126 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1127 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1128
1129 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1130 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1131 }
1132 else
1133 {
1134 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1135 }
1136 }
1137
1138
1139 /**
1140 * Add this page to $wgUser's watchlist
1141 */
1142
1143 function watch() {
1144
1145 global $wgUser, $wgOut;
1146
1147 if ( $wgUser->isAnon() ) {
1148 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1149 return;
1150 }
1151 if ( wfReadOnly() ) {
1152 $wgOut->readOnlyPage();
1153 return;
1154 }
1155
1156 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1157
1158 $wgUser->addWatch( $this->mTitle );
1159 $wgUser->saveSettings();
1160
1161 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1162
1163 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1164 $wgOut->setRobotpolicy( 'noindex,follow' );
1165
1166 $link = $this->mTitle->getPrefixedText();
1167 $text = wfMsg( 'addedwatchtext', $link );
1168 $wgOut->addWikiText( $text );
1169 }
1170
1171 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1172 }
1173
1174 /**
1175 * Stop watching a page
1176 */
1177
1178 function unwatch() {
1179
1180 global $wgUser, $wgOut;
1181
1182 if ( $wgUser->isAnon() ) {
1183 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1184 return;
1185 }
1186 if ( wfReadOnly() ) {
1187 $wgOut->readOnlyPage();
1188 return;
1189 }
1190
1191 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1192
1193 $wgUser->removeWatch( $this->mTitle );
1194 $wgUser->saveSettings();
1195
1196 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1197
1198 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1199 $wgOut->setRobotpolicy( 'noindex,follow' );
1200
1201 $link = $this->mTitle->getPrefixedText();
1202 $text = wfMsg( 'removedwatchtext', $link );
1203 $wgOut->addWikiText( $text );
1204 }
1205
1206 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1207 }
1208
1209 /**
1210 * protect a page
1211 */
1212 function protect( $limit = 'sysop' ) {
1213 global $wgUser, $wgOut, $wgRequest;
1214
1215 if ( ! $wgUser->isAllowed('protect') ) {
1216 $wgOut->sysopRequired();
1217 return;
1218 }
1219 if ( wfReadOnly() ) {
1220 $wgOut->readOnlyPage();
1221 return;
1222 }
1223 $id = $this->mTitle->getArticleID();
1224 if ( 0 == $id ) {
1225 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1226 return;
1227 }
1228
1229 $confirm = $wgRequest->wasPosted() &&
1230 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1231 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1232 $reason = $wgRequest->getText( 'wpReasonProtect' );
1233
1234 if ( $confirm ) {
1235 $dbw =& wfGetDB( DB_MASTER );
1236 $dbw->update( 'page',
1237 array( /* SET */
1238 'page_touched' => $dbw->timestamp(),
1239 'page_restrictions' => (string)$limit
1240 ), array( /* WHERE */
1241 'page_id' => $id
1242 ), 'Article::protect'
1243 );
1244
1245 $restrictions = "move=" . $limit;
1246 if( !$moveonly ) {
1247 $restrictions .= ":edit=" . $limit;
1248 }
1249 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1250
1251 $dbw =& wfGetDB( DB_MASTER );
1252 $dbw->update( 'page',
1253 array( /* SET */
1254 'page_touched' => $dbw->timestamp(),
1255 'page_restrictions' => $restrictions
1256 ), array( /* WHERE */
1257 'page_id' => $id
1258 ), 'Article::protect'
1259 );
1260
1261 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1262
1263 $log = new LogPage( 'protect' );
1264 if ( $limit === '' ) {
1265 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1266 } else {
1267 $log->addEntry( 'protect', $this->mTitle, $reason );
1268 }
1269 $wgOut->redirect( $this->mTitle->getFullURL() );
1270 }
1271 return;
1272 } else {
1273 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1274 return $this->confirmProtect( '', $reason, $limit );
1275 }
1276 }
1277
1278 /**
1279 * Output protection confirmation dialog
1280 */
1281 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1282 global $wgOut, $wgUser;
1283
1284 wfDebug( "Article::confirmProtect\n" );
1285
1286 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1287 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1288
1289 $check = '';
1290 $protcom = '';
1291 $moveonly = '';
1292
1293 if ( $limit === '' ) {
1294 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1295 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1296 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1297 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1298 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1299 } else {
1300 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1301 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1302 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1303 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1304 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1305 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1306 }
1307
1308 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1309 $token = htmlspecialchars( $wgUser->editToken() );
1310
1311 $wgOut->addHTML( "
1312 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1313 <table border='0'>
1314 <tr>
1315 <td align='right'>
1316 <label for='wpReasonProtect'>{$protcom}:</label>
1317 </td>
1318 <td align='left'>
1319 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1320 </td>
1321 </tr>
1322 <tr>
1323 <td>&nbsp;</td>
1324 </tr>" );
1325 if($moveonly != '') {
1326 $wgOut->AddHTML( "
1327 <tr>
1328 <td align='right'>
1329 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1330 </td>
1331 <td>
1332 <label for='wpMoveOnly'>{$moveonly}</label>
1333 </td>
1334 </tr> " );
1335 }
1336 $wgOut->addHTML( "
1337 <tr>
1338 <td>&nbsp;</td>
1339 <td>
1340 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1341 </td>
1342 </tr>
1343 </table>
1344 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1345 </form>\n" );
1346
1347 $wgOut->returnToMain( false );
1348 }
1349
1350 /**
1351 * Unprotect the pages
1352 */
1353 function unprotect() {
1354 return $this->protect( '' );
1355 }
1356
1357 /*
1358 * UI entry point for page deletion
1359 */
1360 function delete() {
1361 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1362 $fname = 'Article::delete';
1363 $confirm = $wgRequest->wasPosted() &&
1364 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1365 $reason = $wgRequest->getText( 'wpReason' );
1366
1367 # This code desperately needs to be totally rewritten
1368
1369 # Check permissions
1370 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1371 $wgOut->sysopRequired();
1372 return;
1373 }
1374 if ( wfReadOnly() ) {
1375 $wgOut->readOnlyPage();
1376 return;
1377 }
1378
1379 # Better double-check that it hasn't been deleted yet!
1380 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1381 if ( ( '' == trim( $this->mTitle->getText() ) )
1382 or ( $this->mTitle->getArticleId() == 0 ) ) {
1383 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1384 return;
1385 }
1386
1387 if ( $confirm ) {
1388 $this->doDelete( $reason );
1389 return;
1390 }
1391
1392 # determine whether this page has earlier revisions
1393 # and insert a warning if it does
1394 # we select the text because it might be useful below
1395 $dbr =& $this->getDB();
1396 $ns = $this->mTitle->getNamespace();
1397 $title = $this->mTitle->getDBkey();
1398 $revisions = $dbr->select( array( 'page', 'revision' ),
1399 array( 'rev_id' ),
1400 array(
1401 'page_namespace' => $ns,
1402 'page_title' => $title,
1403 'rev_page = page_id'
1404 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1405 );
1406
1407 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1408 $skin=$wgUser->getSkin();
1409 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1410 $wgOut->addHTML( $skin->historyLink() .'</b>');
1411 }
1412
1413 # Fetch cur_text
1414 $s = $dbr->selectRow( array( 'page', 'text' ),
1415 array( 'old_text' ),
1416 array(
1417 'page_namespace' => $ns,
1418 'page_title' => $title,
1419 'page_latest = old_id'
1420 ), $fname, $this->getSelectOptions()
1421 );
1422
1423 if( $s !== false ) {
1424 # if this is a mini-text, we can paste part of it into the deletion reason
1425
1426 #if this is empty, an earlier revision may contain "useful" text
1427 $blanked = false;
1428 if($s->old_text != '') {
1429 $text=$s->old_text;
1430 } else {
1431 if($old) { # TODO
1432 $text = Revision::getRevisionText( $old );
1433 $blanked = true;
1434 }
1435
1436 }
1437
1438 $length=strlen($text);
1439
1440 # this should not happen, since it is not possible to store an empty, new
1441 # page. Let's insert a standard text in case it does, though
1442 if($length == 0 && $reason === '') {
1443 $reason = wfMsg('exblank');
1444 }
1445
1446 if($length < 500 && $reason === '') {
1447
1448 # comment field=255, let's grep the first 150 to have some user
1449 # space left
1450 $text=substr($text,0,150);
1451 # let's strip out newlines and HTML tags
1452 $text=preg_replace('/\"/',"'",$text);
1453 $text=preg_replace('/\</','&lt;',$text);
1454 $text=preg_replace('/\>/','&gt;',$text);
1455 $text=preg_replace("/[\n\r]/",'',$text);
1456 if(!$blanked) {
1457 $reason=wfMsg('excontent'). " '".$text;
1458 } else {
1459 $reason=wfMsg('exbeforeblank') . " '".$text;
1460 }
1461 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1462 $reason.="'";
1463 }
1464 }
1465
1466 return $this->confirmDelete( '', $reason );
1467 }
1468
1469 /**
1470 * Output deletion confirmation dialog
1471 */
1472 function confirmDelete( $par, $reason ) {
1473 global $wgOut, $wgUser;
1474
1475 wfDebug( "Article::confirmDelete\n" );
1476
1477 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1478 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1479 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1480 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1481
1482 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1483
1484 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1485 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1486 $token = htmlspecialchars( $wgUser->editToken() );
1487
1488 $wgOut->addHTML( "
1489 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1490 <table border='0'>
1491 <tr>
1492 <td align='right'>
1493 <label for='wpReason'>{$delcom}:</label>
1494 </td>
1495 <td align='left'>
1496 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1497 </td>
1498 </tr>
1499 <tr>
1500 <td>&nbsp;</td>
1501 </tr>
1502 <tr>
1503 <td>&nbsp;</td>
1504 <td>
1505 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1506 </td>
1507 </tr>
1508 </table>
1509 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1510 </form>\n" );
1511
1512 $wgOut->returnToMain( false );
1513 }
1514
1515
1516 /**
1517 * Perform a deletion and output success or failure messages
1518 */
1519 function doDelete( $reason ) {
1520 global $wgOut, $wgUser, $wgContLang;
1521 $fname = 'Article::doDelete';
1522 wfDebug( $fname."\n" );
1523
1524 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1525 if ( $this->doDeleteArticle( $reason ) ) {
1526 $deleted = $this->mTitle->getPrefixedText();
1527
1528 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1529 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1530
1531 $sk = $wgUser->getSkin();
1532 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT ) .
1533 ':' . wfMsgForContent( 'dellogpage' ),
1534 wfMsg( 'deletionlog' ) );
1535
1536 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1537
1538 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1539 $wgOut->returnToMain( false );
1540 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1541 } else {
1542 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1543 }
1544 }
1545 }
1546
1547 /**
1548 * Back-end article deletion
1549 * Deletes the article with database consistency, writes logs, purges caches
1550 * Returns success
1551 */
1552 function doDeleteArticle( $reason ) {
1553 global $wgUser;
1554 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1555
1556 $fname = 'Article::doDeleteArticle';
1557 wfDebug( $fname."\n" );
1558
1559 $dbw =& wfGetDB( DB_MASTER );
1560 $ns = $this->mTitle->getNamespace();
1561 $t = $this->mTitle->getDBkey();
1562 $id = $this->mTitle->getArticleID();
1563
1564 if ( $t == '' || $id == 0 ) {
1565 return false;
1566 }
1567
1568 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1569 array_push( $wgDeferredUpdateList, $u );
1570
1571 $linksTo = $this->mTitle->getLinksTo();
1572
1573 # Squid purging
1574 if ( $wgUseSquid ) {
1575 $urls = array(
1576 $this->mTitle->getInternalURL(),
1577 $this->mTitle->getInternalURL( 'history' )
1578 );
1579 foreach ( $linksTo as $linkTo ) {
1580 $urls[] = $linkTo->getInternalURL();
1581 }
1582
1583 $u = new SquidUpdate( $urls );
1584 array_push( $wgPostCommitUpdateList, $u );
1585
1586 }
1587
1588 # Client and file cache invalidation
1589 Title::touchArray( $linksTo );
1590
1591 # Move article and history to the "archive" table
1592
1593 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1594 array(
1595 'ar_namespace' => 'page_namespace',
1596 'ar_title' => 'page_title',
1597 'ar_text' => 'old_text',
1598 'ar_comment' => 'rev_comment',
1599 'ar_user' => 'rev_user',
1600 'ar_user_text' => 'rev_user_text',
1601 'ar_timestamp' => 'rev_timestamp',
1602 'ar_minor_edit' => 'rev_minor_edit',
1603 'ar_flags' => 'old_flags',
1604 'ar_rev_id' => 'rev_id',
1605 ), array(
1606 'page_namespace' => $ns,
1607 'page_title' => $t,
1608 'page_id = rev_page AND old_id = rev_id'
1609 ), $fname
1610 );
1611
1612 # Now that it's safely backed up, delete it
1613
1614 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1615 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1616 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1617
1618 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1619
1620 # Finally, clean up the link tables
1621 $t = $this->mTitle->getPrefixedDBkey();
1622
1623 Article::onArticleDelete( $this->mTitle );
1624
1625 # Insert broken links
1626 $brokenLinks = array();
1627 foreach ( $linksTo as $titleObj ) {
1628 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1629 $linkID = $titleObj->getArticleID();
1630 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1631 }
1632 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1633
1634 # Delete live links
1635 $dbw->delete( 'links', array( 'l_to' => $id ) );
1636 $dbw->delete( 'links', array( 'l_from' => $id ) );
1637 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1638 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1639 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1640
1641 # Log the deletion
1642 $log = new LogPage( 'delete' );
1643 $log->addEntry( 'delete', $this->mTitle, $reason );
1644
1645 # Clear the cached article id so the interface doesn't act like we exist
1646 $this->mTitle->resetArticleID( 0 );
1647 $this->mTitle->mArticleID = 0;
1648 return true;
1649 }
1650
1651 /**
1652 * Revert a modification
1653 */
1654 function rollback() {
1655 global $wgUser, $wgOut, $wgRequest;
1656 $fname = 'Article::rollback';
1657
1658 if ( ! $wgUser->isAllowed('rollback') ) {
1659 $wgOut->sysopRequired();
1660 return;
1661 }
1662 if ( wfReadOnly() ) {
1663 $wgOut->readOnlyPage( $this->getContent( true ) );
1664 return;
1665 }
1666 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1667 array( $this->mTitle->getPrefixedText(),
1668 $wgRequest->getVal( 'from' ) ) ) ) {
1669 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1670 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1671 return;
1672 }
1673 $dbw =& wfGetDB( DB_MASTER );
1674
1675 # Enhanced rollback, marks edits rc_bot=1
1676 $bot = $wgRequest->getBool( 'bot' );
1677
1678 # Replace all this user's current edits with the next one down
1679 $tt = $this->mTitle->getDBKey();
1680 $n = $this->mTitle->getNamespace();
1681
1682 # Get the last editor, lock table exclusively
1683 $s = $dbw->selectRow( array( 'page', 'revision' ),
1684 array( 'page_id','rev_user','rev_user_text','rev_comment' ),
1685 array( 'page_title' => $tt, 'page_namespace' => $n ),
1686 $fname, 'FOR UPDATE'
1687 );
1688 if( $s === false ) {
1689 # Something wrong
1690 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1691 return;
1692 }
1693 $ut = $dbw->strencode( $s->cur_user_text );
1694 $uid = $s->rev_user;
1695 $pid = $s->page_id;
1696
1697 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1698 if( $from != $s->rev_user_text ) {
1699 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1700 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1701 htmlspecialchars( $this->mTitle->getPrefixedText()),
1702 htmlspecialchars( $from ),
1703 htmlspecialchars( $s->rev_user_text ) ) );
1704 if($s->rev_comment != '') {
1705 $wgOut->addHTML(
1706 wfMsg('editcomment',
1707 htmlspecialchars( $s->rev_comment ) ) );
1708 }
1709 return;
1710 }
1711
1712 # Get the last edit not by this guy
1713 $s = $dbw->selectRow( 'old',
1714 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1715 array(
1716 'old_namespace' => $n,
1717 'old_title' => $tt,
1718 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1719 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1720 );
1721 if( $s === false ) {
1722 # Something wrong
1723 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1724 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1725 return;
1726 }
1727
1728 if ( $bot ) {
1729 # Mark all reverted edits as bot
1730 $dbw->update( 'recentchanges',
1731 array( /* SET */
1732 'rc_bot' => 1
1733 ), array( /* WHERE */
1734 'rc_user' => $uid,
1735 "rc_timestamp > '{$s->old_timestamp}'",
1736 ), $fname
1737 );
1738 }
1739
1740 # Save it!
1741 $newcomment = wfMsg( 'revertpage', $s->old_user_text, $from );
1742 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1743 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1744 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1745 $this->updateArticle( Revision::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1746 Article::onArticleEdit( $this->mTitle );
1747 $wgOut->returnToMain( false );
1748 }
1749
1750
1751 /**
1752 * Do standard deferred updates after page view
1753 * @private
1754 */
1755 function viewUpdates() {
1756 global $wgDeferredUpdateList;
1757
1758 if ( 0 != $this->getID() ) {
1759 global $wgDisableCounters;
1760 if( !$wgDisableCounters ) {
1761 Article::incViewCount( $this->getID() );
1762 $u = new SiteStatsUpdate( 1, 0, 0 );
1763 array_push( $wgDeferredUpdateList, $u );
1764 }
1765 }
1766
1767 # Update newtalk status if user is reading their own
1768 # talk page
1769
1770 global $wgUser;
1771 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1772 $this->mTitle->getText() == $wgUser->getName()) {
1773 require_once( 'UserTalkUpdate.php' );
1774 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
1775 }
1776 }
1777
1778 /**
1779 * Do standard deferred updates after page edit.
1780 * Every 1000th edit, prune the recent changes table.
1781 * @private
1782 * @param string $text
1783 */
1784 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1785 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1786 global $wgMessageCache, $wgUser;
1787
1788 wfSeedRandom();
1789 if ( 0 == mt_rand( 0, 999 ) ) {
1790 # Periodically flush old entries from the recentchanges table.
1791 global $wgRCMaxAge;
1792 $dbw =& wfGetDB( DB_MASTER );
1793 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1794 $recentchanges = $dbw->tableName( 'recentchanges' );
1795 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1796 $dbw->query( $sql );
1797 }
1798 $id = $this->getID();
1799 $title = $this->mTitle->getPrefixedDBkey();
1800 $shortTitle = $this->mTitle->getDBkey();
1801
1802 $adj = $this->mCountAdjustment;
1803
1804 if ( 0 != $id ) {
1805 $u = new LinksUpdate( $id, $title );
1806 array_push( $wgDeferredUpdateList, $u );
1807 $u = new SiteStatsUpdate( 0, 1, $adj );
1808 array_push( $wgDeferredUpdateList, $u );
1809 $u = new SearchUpdate( $id, $title, $text );
1810 array_push( $wgDeferredUpdateList, $u );
1811
1812 # If this is another user's talk page,
1813 # create a watchlist entry for this page
1814
1815 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1816 $shortTitle != $wgUser->getName()) {
1817 require_once( 'UserTalkUpdate.php' );
1818 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1819 }
1820
1821 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1822 $wgMessageCache->replace( $shortTitle, $text );
1823 }
1824 }
1825 }
1826
1827 /**
1828 * @todo document this function
1829 * @private
1830 * @param string $oldid Revision ID of this article revision
1831 */
1832 function setOldSubtitle( $oldid=0 ) {
1833 global $wgLang, $wgOut, $wgUser;
1834
1835 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1836 $sk = $wgUser->getSkin();
1837 $lnk = $sk->makeKnownLinkObj ( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
1838 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1839 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1840 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1841 $wgOut->setSubtitle( $r );
1842 }
1843
1844 /**
1845 * This function is called right before saving the wikitext,
1846 * so we can do things like signatures and links-in-context.
1847 *
1848 * @param string $text
1849 */
1850 function preSaveTransform( $text ) {
1851 global $wgParser, $wgUser;
1852 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1853 }
1854
1855 /* Caching functions */
1856
1857 /**
1858 * checkLastModified returns true if it has taken care of all
1859 * output to the client that is necessary for this request.
1860 * (that is, it has sent a cached version of the page)
1861 */
1862 function tryFileCache() {
1863 static $called = false;
1864 if( $called ) {
1865 wfDebug( " tryFileCache() -- called twice!?\n" );
1866 return;
1867 }
1868 $called = true;
1869 if($this->isFileCacheable()) {
1870 $touched = $this->mTouched;
1871 $cache = new CacheManager( $this->mTitle );
1872 if($cache->isFileCacheGood( $touched )) {
1873 global $wgOut;
1874 wfDebug( " tryFileCache() - about to load\n" );
1875 $cache->loadFromFileCache();
1876 return true;
1877 } else {
1878 wfDebug( " tryFileCache() - starting buffer\n" );
1879 ob_start( array(&$cache, 'saveToFileCache' ) );
1880 }
1881 } else {
1882 wfDebug( " tryFileCache() - not cacheable\n" );
1883 }
1884 }
1885
1886 /**
1887 * Check if the page can be cached
1888 * @return bool
1889 */
1890 function isFileCacheable() {
1891 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1892 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1893
1894 return $wgUseFileCache
1895 and (!$wgShowIPinHeader)
1896 and ($this->getID() != 0)
1897 and ($wgUser->isAnon())
1898 and (!$wgUser->getNewtalk())
1899 and ($this->mTitle->getNamespace() != NS_SPECIAL )
1900 and (empty( $action ) || $action == 'view')
1901 and (!isset($oldid))
1902 and (!isset($diff))
1903 and (!isset($redirect))
1904 and (!isset($printable))
1905 and (!$this->mRedirectedFrom);
1906 }
1907
1908 /**
1909 * Loads cur_touched and returns a value indicating if it should be used
1910 *
1911 */
1912 function checkTouched() {
1913 $fname = 'Article::checkTouched';
1914 $id = $this->getID();
1915 $dbr =& $this->getDB();
1916 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1917 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1918 if( $s !== false ) {
1919 $this->mTouched = wfTimestamp( TS_MW, $s->page_touched );
1920 return !$s->page_is_redirect;
1921 } else {
1922 return false;
1923 }
1924 }
1925
1926 /**
1927 * Edit an article without doing all that other stuff
1928 * The article must already exist; link tables etc
1929 * are not updated, caches are not flushed.
1930 *
1931 * @param string $text text submitted
1932 * @param string $comment comment submitted
1933 * @param bool $minor whereas it's a minor modification
1934 */
1935 function quickEdit( $text, $comment = '', $minor = 0 ) {
1936 $fname = 'Article::quickEdit';
1937 wfProfileIn( $fname );
1938
1939 $dbw =& wfGetDB( DB_MASTER );
1940 $dbw->begin();
1941 $revision = new Revision( array(
1942 'page' => $this->getId(),
1943 'text' => $text,
1944 'comment' => $comment,
1945 'minor_edit' => $minor ? 1 : 0,
1946 ) );
1947 $revisionId = $revision->insertOn( $dbw );
1948 $this->updateRevisionOn( $dbw, $revisionId, null,
1949 Article::isRedirect( $text ) );
1950 $dbw->commit();
1951
1952 wfProfileOut( $fname );
1953 }
1954
1955 /**
1956 * Used to increment the view counter
1957 *
1958 * @static
1959 * @param integer $id article id
1960 */
1961 function incViewCount( $id ) {
1962 $id = intval( $id );
1963 global $wgHitcounterUpdateFreq;
1964
1965 $dbw =& wfGetDB( DB_MASTER );
1966 $pageTable = $dbw->tableName( 'page' );
1967 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1968 $acchitsTable = $dbw->tableName( 'acchits' );
1969
1970 if( $wgHitcounterUpdateFreq <= 1 ){ //
1971 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
1972 return;
1973 }
1974
1975 # Not important enough to warrant an error page in case of failure
1976 $oldignore = $dbw->ignoreErrors( true );
1977
1978 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1979
1980 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1981 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1982 # Most of the time (or on SQL errors), skip row count check
1983 $dbw->ignoreErrors( $oldignore );
1984 return;
1985 }
1986
1987 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
1988 $row = $dbw->fetchObject( $res );
1989 $rown = intval( $row->n );
1990 if( $rown >= $wgHitcounterUpdateFreq ){
1991 wfProfileIn( 'Article::incViewCount-collect' );
1992 $old_user_abort = ignore_user_abort( true );
1993
1994 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
1995 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
1996 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
1997 'GROUP BY hc_id');
1998 $dbw->query("DELETE FROM $hitcounterTable");
1999 $dbw->query('UNLOCK TABLES');
2000 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2001 'WHERE cur_id = hc_id');
2002 $dbw->query("DROP TABLE $acchitsTable");
2003
2004 ignore_user_abort( $old_user_abort );
2005 wfProfileOut( 'Article::incViewCount-collect' );
2006 }
2007 $dbw->ignoreErrors( $oldignore );
2008 }
2009
2010 /**#@+
2011 * The onArticle*() functions are supposed to be a kind of hooks
2012 * which should be called whenever any of the specified actions
2013 * are done.
2014 *
2015 * This is a good place to put code to clear caches, for instance.
2016 *
2017 * This is called on page move and undelete, as well as edit
2018 * @static
2019 * @param $title_obj a title object
2020 */
2021
2022 function onArticleCreate($title_obj) {
2023 global $wgUseSquid, $wgPostCommitUpdateList;
2024
2025 $titles = $title_obj->getBrokenLinksTo();
2026
2027 # Purge squid
2028 if ( $wgUseSquid ) {
2029 $urls = $title_obj->getSquidURLs();
2030 foreach ( $titles as $linkTitle ) {
2031 $urls[] = $linkTitle->getInternalURL();
2032 }
2033 $u = new SquidUpdate( $urls );
2034 array_push( $wgPostCommitUpdateList, $u );
2035 }
2036
2037 # Clear persistent link cache
2038 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2039 }
2040
2041 function onArticleDelete($title_obj) {
2042 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
2043 }
2044 function onArticleEdit($title_obj) {
2045 LinkCache::linksccClearPage( $title_obj->getArticleID() );
2046 }
2047 /**#@-*/
2048
2049 /**
2050 * Info about this page
2051 * Called for ?action=info when $wgAllowPageInfo is on.
2052 *
2053 * @access public
2054 */
2055 function info() {
2056 global $wgLang, $wgOut, $wgAllowPageInfo;
2057 $fname = 'Article::info';
2058
2059 if ( !$wgAllowPageInfo ) {
2060 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2061 return;
2062 }
2063
2064 $page = $this->mTitle->getSubjectPage();
2065
2066 $wgOut->setPagetitle( $page->getPrefixedText() );
2067 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2068
2069 # first, see if the page exists at all.
2070 $exists = $page->getArticleId() != 0;
2071 if( !$exists ) {
2072 $wgOut->addHTML( wfMsg('noarticletext') );
2073 } else {
2074 $dbr =& $this->getDB( DB_SLAVE );
2075 $wl_clause = array(
2076 'wl_title' => $page->getDBkey(),
2077 'wl_namespace' => $page->getNamespace() );
2078 $numwatchers = $dbr->selectField(
2079 'watchlist',
2080 'COUNT(*)',
2081 $wl_clause,
2082 $fname,
2083 $this->getSelectOptions() );
2084
2085 $pageInfo = $this->pageCountInfo( $page );
2086 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2087
2088 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2089 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2090 if( $talkInfo ) {
2091 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2092 }
2093 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2094 if( $talkInfo ) {
2095 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2096 }
2097 $wgOut->addHTML( '</ul>' );
2098
2099 }
2100 }
2101
2102 /**
2103 * Return the total number of edits and number of unique editors
2104 * on a given page. If page does not exist, returns false.
2105 *
2106 * @param Title $title
2107 * @return array
2108 * @access private
2109 */
2110 function pageCountInfo( $title ) {
2111 $id = $title->getArticleId();
2112 if( $id == 0 ) {
2113 return false;
2114 }
2115
2116 $dbr =& $this->getDB( DB_SLAVE );
2117
2118 $rev_clause = array( 'rev_page' => $id );
2119 $fname = 'Article::pageCountInfo';
2120
2121 $edits = $dbr->selectField(
2122 'revision',
2123 'COUNT(rev_page)',
2124 $rev_clause,
2125 $fname,
2126 $this->getSelectOptions() );
2127
2128 $authors = $dbr->selectField(
2129 'revision',
2130 'COUNT(DISTINCT rev_user_text)',
2131 $rev_clause,
2132 $fname,
2133 $this->getSelectOptions() );
2134
2135 return array( 'edits' => $edits, 'authors' => $authors );
2136 }
2137 }
2138
2139 /**
2140 * Check whether an article is a stub
2141 *
2142 * @public
2143 * @param integer $articleID ID of the article that is to be checked
2144 */
2145 function wfArticleIsStub( $articleID ) {
2146 global $wgUser;
2147 $fname = 'wfArticleIsStub';
2148
2149 wfDebugDieBacktrace( 'This function seems to be unused. Pending removal.' );
2150
2151 $threshold = $wgUser->getOption('stubthreshold') ;
2152 if ( $threshold > 0 ) {
2153 $dbr =& wfGetDB( DB_SLAVE );
2154 $s = $dbr->selectRow( array('page', 'text'),
2155 array( 'LENGTH(old_text) AS len', 'page_namespace', 'page_is_redirect' ),
2156 array( 'page_id' => $articleID, "page.page_latest=text.old_id" ),
2157 $fname ) ;
2158 if ( $s == false OR $s->page_is_redirect OR $s->page_namespace != NS_MAIN ) {
2159 return false;
2160 }
2161 $size = $s->len;
2162 return ( $size < $threshold );
2163 }
2164 return false;
2165 }
2166
2167 ?>