* Fixed some phpdoc errors, see http://wikipedia.sf.net/doc/errors.html
[mediawiki.git] / includes / Article.php
blob35b1ed525f1612e2ee2416168c585e734d89c8b2
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
16 /**
17 * Class representing a MediaWiki article and history.
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
23 * @package MediaWiki
25 class Article {
26 /**#@+
27 * @access private
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 var $mRevIdFetched;
38 /**#@-*/
40 /**
41 * Constructor and clear the article
42 * @param mixed &$title
44 function Article( &$title ) {
45 $this->mTitle =& $title;
46 $this->clear();
49 /**
50 * get the title object of the article
51 * @public
53 function getTitle() {
54 return $this->mTitle;
57 /**
58 * Clear the object
59 * @private
61 function clear() {
62 $this->mDataLoaded = false;
63 $this->mContentLoaded = false;
65 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
66 $this->mRedirectedFrom = $this->mUserText =
67 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
68 $this->mCountAdjustment = 0;
69 $this->mTouched = '19700101000000';
70 $this->mForUpdate = false;
71 $this->mIsRedirect = false;
72 $this->mRevIdFetched = 0;
75 /**
76 * Note that getContent/loadContent may follow redirects if
77 * not told otherwise, and so may cause a change to mTitle.
79 * @param $noredir
80 * @return Return the text of this revision
82 function getContent( $noredir ) {
83 global $wgRequest, $wgUser;
85 # Get variables from query string :P
86 $action = $wgRequest->getText( 'action', 'view' );
87 $section = $wgRequest->getText( 'section' );
89 $fname = 'Article::getContent';
90 wfProfileIn( $fname );
92 if ( 0 == $this->getID() ) {
93 if ( 'edit' == $action ) {
94 wfProfileOut( $fname );
95 return ''; # was "newarticletext", now moved above the box)
97 wfProfileOut( $fname );
98 return wfMsg( 'noarticletext' );
99 } else {
100 $this->loadContent( $noredir );
101 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
102 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
103 $wgUser->isIP($this->mTitle->getText()) &&
104 $action=='view'
106 wfProfileOut( $fname );
107 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
108 } else {
109 if($action=='edit') {
110 if($section!='') {
111 if($section=='new') {
112 wfProfileOut( $fname );
113 return '';
116 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
117 # comments to be stripped as well)
118 $rv=$this->getSection($this->mContent,$section);
119 wfProfileOut( $fname );
120 return $rv;
123 wfProfileOut( $fname );
124 return $this->mContent;
130 * This function returns the text of a section, specified by a number ($section).
131 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
132 * the first section before any such heading (section 0).
134 * If a section contains subsections, these are also returned.
136 * @param string $text text to look in
137 * @param integer $section section number
138 * @return string text of the requested section
140 function getSection($text,$section) {
142 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
143 # comments to be stripped as well)
144 $striparray=array();
145 $parser=new Parser();
146 $parser->mOutputType=OT_WIKI;
147 $striptext=$parser->strip($text, $striparray, true);
149 # now that we can be sure that no pseudo-sections are in the source,
150 # split it up by section
151 $secs =
152 preg_split(
153 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
154 $striptext, -1,
155 PREG_SPLIT_DELIM_CAPTURE);
156 if($section==0) {
157 $rv=$secs[0];
158 } else {
159 $headline=$secs[$section*2-1];
160 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
161 $hlevel=$matches[1];
163 # translate wiki heading into level
164 if(strpos($hlevel,'=')!==false) {
165 $hlevel=strlen($hlevel);
168 $rv=$headline. $secs[$section*2];
169 $count=$section+1;
171 $break=false;
172 while(!empty($secs[$count*2-1]) && !$break) {
174 $subheadline=$secs[$count*2-1];
175 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
176 $subhlevel=$matches[1];
177 if(strpos($subhlevel,'=')!==false) {
178 $subhlevel=strlen($subhlevel);
180 if($subhlevel > $hlevel) {
181 $rv.=$subheadline.$secs[$count*2];
183 if($subhlevel <= $hlevel) {
184 $break=true;
186 $count++;
190 # reinsert stripped tags
191 $rv=$parser->unstrip($rv,$striparray);
192 $rv=$parser->unstripNoWiki($rv,$striparray);
193 $rv=trim($rv);
194 return $rv;
199 * Return an array of the columns of the "cur"-table
201 function getContentFields() {
202 return $wgArticleContentFields = array(
203 'old_text','old_flags',
204 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
205 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
209 * Return the oldid of the article that is to be shown.
210 * For requests with a "direction", this is not the oldid of the
211 * query
213 function getOldID() {
214 global $wgRequest, $wgOut;
215 static $lastid;
217 if ( isset( $lastid ) ) {
218 return $lastid;
220 # Query variables :P
221 $oldid = $wgRequest->getVal( 'oldid' );
222 if ( isset( $oldid ) ) {
223 $oldid = IntVal( $oldid );
224 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
225 $nextid = $this->mTitle->getNextRevisionID( $oldid );
226 if ( $nextid ) {
227 $oldid = $nextid;
228 } else {
229 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
231 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
232 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
233 if ( $previd ) {
234 $oldid = $previd;
235 } else {
236 # TODO
239 $lastid = $oldid;
241 return @$oldid; # "@" to be able to return "unset" without PHP complaining
246 * Load the revision (including cur_text) into this object
248 function loadContent( $noredir = false ) {
249 global $wgOut, $wgRequest;
251 if ( $this->mContentLoaded ) return;
253 # Query variables :P
254 $oldid = $this->getOldID();
255 $redirect = $wgRequest->getVal( 'redirect' );
257 $fname = 'Article::loadContent';
259 # Pre-fill content with error message so that if something
260 # fails we'll have something telling us what we intended.
262 $t = $this->mTitle->getPrefixedText();
264 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
265 || $wgRequest->getCheck( 'rdfrom' );
266 $this->mOldId = $oldid;
267 $this->fetchContent( $oldid, $noredir, true );
272 * Fetch a page record with the given conditions
273 * @param Database $dbr
274 * @param array $conditions
275 * @access private
277 function pageData( &$dbr, $conditions ) {
278 return $dbr->selectRow( 'page',
279 array(
280 'page_id',
281 'page_namespace',
282 'page_title',
283 'page_restrictions',
284 'page_counter',
285 'page_is_redirect',
286 'page_is_new',
287 'page_random',
288 'page_touched',
289 'page_latest',
290 'page_len' ),
291 $conditions,
292 'Article::pageData' );
295 function pageDataFromTitle( &$dbr, $title ) {
296 return $this->pageData( $dbr, array(
297 'page_namespace' => $title->getNamespace(),
298 'page_title' => $title->getDBkey() ) );
301 function pageDataFromId( &$dbr, $id ) {
302 return $this->pageData( $dbr, array(
303 'page_id' => IntVal( $id ) ) );
307 * Set the general counter, title etc data loaded from
308 * some source.
310 * @param object $data
311 * @access private
313 function loadPageData( $data ) {
314 $this->mTitle->mRestrictions = explode( ',', trim( $data->page_restrictions ) );
315 $this->mTitle->mRestrictionsLoaded = true;
317 $this->mCounter = $data->page_counter;
318 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
319 $this->mIsRedirect = $data->page_is_redirect;
320 $this->mLatest = $data->page_latest;
322 $this->mDataLoaded = true;
326 * Get text of an article from database
327 * @param int $oldid 0 for whatever the latest revision is
328 * @param bool $noredir Set to true to avoid following redirects
329 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
330 * @return string
332 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
333 if ( $this->mContentLoaded ) {
334 return $this->mContent;
336 $dbr =& $this->getDB();
337 $fname = 'Article::fetchContent';
339 # Pre-fill content with error message so that if something
340 # fails we'll have something telling us what we intended.
341 $t = $this->mTitle->getPrefixedText();
342 if( $oldid ) {
343 $t .= ',oldid='.$oldid;
345 if( isset( $redirect ) ) {
346 $redirect = ($redirect == 'no') ? 'no' : 'yes';
347 $t .= ',redirect='.$redirect;
349 $this->mContent = wfMsg( 'missingarticle', $t );
351 if( $oldid ) {
352 $revision = Revision::newFromId( $oldid );
353 if( is_null( $revision ) ) {
354 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
355 return false;
357 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
358 if( !$data ) {
359 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
360 return false;
362 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
363 $this->loadPageData( $data );
364 } else {
365 if( !$this->mDataLoaded ) {
366 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
367 if( !$data ) {
368 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
369 return false;
371 $this->loadPageData( $data );
373 $revision = Revision::newFromId( $this->mLatest );
374 if( is_null( $revision ) ) {
375 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
376 return false;
380 # If we got a redirect, follow it (unless we've been told
381 # not to by either the function parameter or the query
382 if ( !$oldid && !$noredir ) {
383 $rt = Title::newFromRedirect( $revision->getText() );
384 # process if title object is valid and not special:userlogout
385 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
386 # Gotta hand redirects to special pages differently:
387 # Fill the HTTP response "Location" header and ignore
388 # the rest of the page we're on.
389 if( $globalTitle ) {
390 global $wgOut;
391 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
392 $source = $this->mTitle->getFullURL( 'redirect=no' );
393 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
394 return false;
396 if ( $rt->getNamespace() == NS_SPECIAL ) {
397 $wgOut->redirect( $rt->getFullURL() );
398 return false;
401 $redirData = $this->pageDataFromTitle( $dbr, $rt );
402 if( $redirData ) {
403 $redirRev = Revision::newFromId( $redirData->page_latest );
404 if( !is_null( $redirRev ) ) {
405 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
406 $this->mTitle = $rt;
407 $data = $redirData;
408 $this->loadPageData( $data );
409 $revision = $redirRev;
415 # if the title's different from expected, update...
416 if( $globalTitle ) {
417 global $wgTitle;
418 if( !$this->mTitle->equals( $wgTitle ) ) {
419 $wgTitle = $this->mTitle;
423 # Back to the business at hand...
424 $this->mContent = $revision->getText();
426 $this->mUser = $revision->getUser();
427 $this->mUserText = $revision->getUserText();
428 $this->mComment = $revision->getComment();
429 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
431 $this->mRevIdFetched = $revision->getID();
432 $this->mContentLoaded = true;
434 return $this->mContent;
438 * Gets the article text without using so many damn globals
439 * Returns false on error
441 * @param integer $oldid
443 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
444 return $this->fetchContent( $oldid, $noredir, false );
448 * Read/write accessor to select FOR UPDATE
450 function forUpdate( $x = NULL ) {
451 return wfSetVar( $this->mForUpdate, $x );
455 * Get the database which should be used for reads
457 function &getDB() {
458 #if ( $this->mForUpdate ) {
459 return wfGetDB( DB_MASTER );
460 #} else {
461 # return wfGetDB( DB_SLAVE );
466 * Get options for all SELECT statements
467 * Can pass an option array, to which the class-wide options will be appended
469 function getSelectOptions( $options = '' ) {
470 if ( $this->mForUpdate ) {
471 if ( is_array( $options ) ) {
472 $options[] = 'FOR UPDATE';
473 } else {
474 $options = 'FOR UPDATE';
477 return $options;
481 * Return the Article ID
483 function getID() {
484 if( $this->mTitle ) {
485 return $this->mTitle->getArticleID();
486 } else {
487 return 0;
492 * Get the view count for this article
494 function getCount() {
495 if ( -1 == $this->mCounter ) {
496 $id = $this->getID();
497 $dbr =& $this->getDB();
498 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
499 'Article::getCount', $this->getSelectOptions() );
501 return $this->mCounter;
505 * Would the given text make this article a "good" article (i.e.,
506 * suitable for including in the article count)?
507 * @param string $text Text to analyze
508 * @return integer 1 if it can be counted else 0
510 function isCountable( $text ) {
511 global $wgUseCommaCount;
513 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
514 if ( $this->isRedirect( $text ) ) { return 0; }
515 $token = ($wgUseCommaCount ? ',' : '[[' );
516 if ( false === strstr( $text, $token ) ) { return 0; }
517 return 1;
520 /**
521 * Tests if the article text represents a redirect
523 function isRedirect( $text = false ) {
524 if ( $text === false ) {
525 $this->loadContent();
526 $titleObj = Title::newFromRedirect( $this->fetchRevisionText() );
527 } else {
528 $titleObj = Title::newFromRedirect( $text );
530 return $titleObj !== NULL;
534 * Loads everything except the text
535 * This isn't necessary for all uses, so it's only done if needed.
536 * @private
538 function loadLastEdit() {
539 global $wgOut;
541 if ( -1 != $this->mUser )
542 return;
544 # New or non-existent articles have no user information
545 $id = $this->getID();
546 if ( 0 == $id ) return;
548 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
549 if( !is_null( $this->mLastRevision ) ) {
550 $this->mUser = $this->mLastRevision->getUser();
551 $this->mUserText = $this->mLastRevision->getUserText();
552 $this->mTimestamp = $this->mLastRevision->getTimestamp();
553 $this->mComment = $this->mLastRevision->getComment();
554 $this->mMinorEdit = $this->mLastRevision->isMinor();
558 function getTimestamp() {
559 $this->loadLastEdit();
560 return $this->mTimestamp;
563 function getUser() {
564 $this->loadLastEdit();
565 return $this->mUser;
568 function getUserText() {
569 $this->loadLastEdit();
570 return $this->mUserText;
573 function getComment() {
574 $this->loadLastEdit();
575 return $this->mComment;
578 function getMinorEdit() {
579 $this->loadLastEdit();
580 return $this->mMinorEdit;
583 function getRevIdFetched() {
584 $this->loadLastEdit();
585 return $this->mRevIdFetched;
588 function getContributors($limit = 0, $offset = 0) {
589 $fname = 'Article::getContributors';
591 # XXX: this is expensive; cache this info somewhere.
593 $title = $this->mTitle;
594 $contribs = array();
595 $dbr =& $this->getDB();
596 $revTable = $dbr->tableName( 'revision' );
597 $userTable = $dbr->tableName( 'user' );
598 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
599 $ns = $title->getNamespace();
600 $user = $this->getUser();
601 $pageId = $this->getId();
603 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
604 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
605 WHERE rev_page = $pageId
606 AND rev_user != $user
607 GROUP BY rev_user, rev_user_text, user_real_name
608 ORDER BY timestamp DESC";
610 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
611 $sql .= ' '. $this->getSelectOptions();
613 $res = $dbr->query($sql, $fname);
615 while ( $line = $dbr->fetchObject( $res ) ) {
616 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
619 $dbr->freeResult($res);
620 return $contribs;
624 * This is the default action of the script: just view the page of
625 * the given title.
627 function view() {
628 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
629 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
630 global $wgEnotif, $wgParser;
631 $sk = $wgUser->getSkin();
633 $fname = 'Article::view';
634 wfProfileIn( $fname );
635 # Get variables from query string
636 $oldid = $this->getOldID();
637 $diff = $wgRequest->getVal( 'diff' );
638 $rcid = $wgRequest->getVal( 'rcid' );
639 $rdfrom = $wgRequest->getVal( 'rdfrom' );
641 $wgOut->setArticleFlag( true );
642 $wgOut->setRobotpolicy( 'index,follow' );
643 # If we got diff and oldid in the query, we want to see a
644 # diff page instead of the article.
646 if ( !is_null( $diff ) ) {
647 require_once( 'DifferenceEngine.php' );
648 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
650 $de = new DifferenceEngine( $oldid, $diff, $rcid );
651 // DifferenceEngine directly fetched the revision:
652 $this->mRevIdFetched = $de->mNewid;
653 $de->showDiffPage();
655 if( $diff == 0 ) {
656 # Run view updates for current revision only
657 $this->viewUpdates();
659 wfProfileOut( $fname );
660 return;
662 if ( empty( $oldid ) && $this->checkTouched() ) {
663 if( $wgOut->checkLastModified( $this->mTouched ) ){
664 wfProfileOut( $fname );
665 return;
666 } else if ( $this->tryFileCache() ) {
667 # tell wgOut that output is taken care of
668 $wgOut->disable();
669 $this->viewUpdates();
670 wfProfileOut( $fname );
671 return;
674 # Should the parser cache be used?
675 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) && $this->getID() ) {
676 $pcache = true;
677 } else {
678 $pcache = false;
681 $outputDone = false;
682 if ( $pcache ) {
683 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
684 $outputDone = true;
687 if ( !$outputDone ) {
688 $text = $this->getContent( false ); # May change mTitle by following a redirect
690 # Another whitelist check in case oldid or redirects are altering the title
691 if ( !$this->mTitle->userCanRead() ) {
692 $wgOut->loginToUse();
693 $wgOut->output();
694 exit;
698 # We're looking at an old revision
700 if ( !empty( $oldid ) ) {
701 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
702 $wgOut->setRobotpolicy( 'noindex,follow' );
704 if ( '' != $this->mRedirectedFrom ) {
705 $sk = $wgUser->getSkin();
706 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
707 'redirect=no' );
708 $s = wfMsg( 'redirectedfrom', $redir );
709 $wgOut->setSubtitle( $s );
711 # Can't cache redirects
712 $pcache = false;
713 } elseif ( !empty( $rdfrom ) ) {
714 global $wgRedirectSources;
715 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
716 $sk = $wgUser->getSkin();
717 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
718 $s = wfMsg( 'redirectedfrom', $redir );
719 $wgOut->setSubtitle( $s );
723 # wrap user css and user js in pre and don't parse
724 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
725 if (
726 $this->mTitle->getNamespace() == NS_USER &&
727 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
729 $wgOut->addWikiText( wfMsg('clearyourcache'));
730 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
731 } else if ( $rt = Title::newFromRedirect( $text ) ) {
732 # Display redirect
733 $imageUrl = $wgStylePath.'/common/images/redirect.png';
734 $targetUrl = $rt->escapeLocalURL();
735 $titleText = htmlspecialchars( $rt->getPrefixedText() );
736 $link = $sk->makeLinkObj( $rt );
738 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
739 '<span class="redirectText">'.$link.'</span>' );
741 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
742 $catlinks = $parseout->getCategoryLinks();
743 $wgOut->addCategoryLinks($catlinks);
744 $skin = $wgUser->getSkin();
745 } else if ( $pcache ) {
746 # Display content and save to parser cache
747 $wgOut->addPrimaryWikiText( $text, $this );
748 } else {
749 # Display content, don't attempt to save to parser cache
750 $wgOut->addWikiText( $text );
753 /* title may have been set from the cache */
754 $t = $wgOut->getPageTitle();
755 if( empty( $t ) ) {
756 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
759 # If we have been passed an &rcid= parameter, we want to give the user a
760 # chance to mark this new article as patrolled.
761 if ( $wgUseRCPatrol
762 && !is_null($rcid)
763 && $rcid != 0
764 && $wgUser->isLoggedIn()
765 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
767 $wgOut->addHTML(
768 "<div class='patrollink'>" .
769 wfMsg ( 'markaspatrolledlink',
770 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
772 '</div>'
776 # Put link titles into the link cache
777 $wgOut->transformBuffer();
779 # Add link titles as META keywords
780 $wgOut->addMetaTags() ;
782 $this->viewUpdates();
783 wfProfileOut( $fname );
787 * Insert a new empty page record for this article.
788 * This *must* be followed up by creating a revision
789 * and running $this->updateToLatest( $rev_id );
790 * or else the record will be left in a funky state.
791 * Best if all done inside a transaction.
793 * @param Database $dbw
794 * @param string $restrictions
795 * @return int The newly created page_id key
796 * @access private
798 function insertOn( &$dbw, $restrictions = '' ) {
799 $fname = 'Article::insertOn';
800 wfProfileIn( $fname );
802 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
803 $dbw->insert( 'page', array(
804 'page_id' => $page_id,
805 'page_namespace' => $this->mTitle->getNamespace(),
806 'page_title' => $this->mTitle->getDBkey(),
807 'page_counter' => 0,
808 'page_restrictions' => $restrictions,
809 'page_is_redirect' => 0, # Will set this shortly...
810 'page_is_new' => 1,
811 'page_random' => wfRandom(),
812 'page_touched' => $dbw->timestamp(),
813 'page_latest' => 0, # Fill this in shortly...
814 ), $fname );
815 $newid = $dbw->insertId();
817 $this->mTitle->resetArticleId( $newid );
819 wfProfileOut( $fname );
820 return $newid;
824 * Update the page record to point to a newly saved revision.
826 * @param Database $dbw
827 * @param Revision $revision -- for ID number, and text used to set
828 length and redirect status fields
829 * @param int $lastRevision -- if given, will not overwrite the page field
830 * when different from the currently set value.
831 * Giving 0 indicates the new page flag should
832 * be set on.
833 * @return bool true on success, false on failure
834 * @access private
836 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
837 $fname = 'Article::updateToRevision';
838 wfProfileIn( $fname );
840 $conditions = array( 'page_id' => $this->getId() );
841 if( !is_null( $lastRevision ) ) {
842 # An extra check against threads stepping on each other
843 $conditions['page_latest'] = $lastRevision;
845 $text = $revision->getText();
846 $dbw->update( 'page',
847 array( /* SET */
848 'page_latest' => $revision->getId(),
849 'page_touched' => $dbw->timestamp(),
850 'page_is_new' => ($lastRevision === 0) ? 0 : 1,
851 'page_is_redirect' => Article::isRedirect( $text ),
852 'page_len' => strlen( $text ),
854 $conditions,
855 $fname );
857 wfProfileOut( $fname );
858 return ( $dbw->affectedRows() != 0 );
862 * If the given revision is newer than the currently set page_latest,
863 * update the page record. Otherwise, do nothing.
865 * @param Database $dbw
866 * @param Revision $revision
868 function updateIfNewerOn( &$dbw, $revision ) {
869 $fname = 'Article::updateIfNewerOn';
870 wfProfileIn( $fname );
872 $row = $dbw->selectRow(
873 array( 'revision', 'page' ),
874 array( 'rev_id', 'rev_timestamp' ),
875 array(
876 'page_id' => $this->getId(),
877 'page_latest=rev_id' ),
878 $fname );
879 if( $row ) {
880 if( $row->rev_timestamp >= $revision->getTimestamp() ) {
881 wfProfileOut( $fname );
882 return false;
884 $prev = $row->rev_id;
885 } else {
886 # No or missing previous revision; mark the page as new
887 $prev = 0;
890 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
891 wfProfileOut( $fname );
892 return $ret;
896 * Theoretically we could defer these whole insert and update
897 * functions for after display, but that's taking a big leap
898 * of faith, and we want to be able to report database
899 * errors at some point.
900 * @private
902 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false ) {
903 global $wgOut, $wgUser;
904 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
906 $fname = 'Article::insertNewArticle';
908 $this->mCountAdjustment = $this->isCountable( $text );
910 $ns = $this->mTitle->getNamespace();
911 $ttl = $this->mTitle->getDBkey();
912 $text = $this->preSaveTransform( $text );
913 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
914 $now = wfTimestampNow();
916 $dbw =& wfGetDB( DB_MASTER );
918 # Add the page record; stake our claim on this title!
919 $newid = $this->insertOn( $dbw );
921 # Save the revision text...
922 $revision = new Revision( array(
923 'page' => $newid,
924 'comment' => $summary,
925 'minor_edit' => $isminor,
926 'text' => $text
927 ) );
928 $revisionId = $revision->insertOn( $dbw );
930 $this->mTitle->resetArticleID( $newid );
932 # Update the page record with revision data
933 $this->updateRevisionOn( $dbw, $revision, 0 );
935 Article::onArticleCreate( $this->mTitle );
936 if(!$suppressRC) {
937 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
940 if ($watchthis) {
941 if(!$this->mTitle->userIsWatching()) $this->watch();
942 } else {
943 if ( $this->mTitle->userIsWatching() ) {
944 $this->unwatch();
948 # The talk page isn't in the regular link tables, so we need to update manually:
949 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
950 $dbw->update( 'page',
951 array( 'page_touched' => $dbw->timestamp($now) ),
952 array( 'page_namespace' => $talkns,
953 'page_title' => $ttl ),
954 $fname );
956 # standard deferred updates
957 $this->editUpdates( $text, $summary, $isminor, $now );
959 $oldid = 0; # new article
960 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
964 * Fetch and uncompress the text for a given revision.
965 * Can ask by rev_id number or timestamp (set $field)
966 * FIXME: This function is broken. Eliminate all uses and remove.
967 * Use Revision class in place.
969 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
970 $fname = 'Article::fetchRevisionText';
971 $dbw =& wfGetDB( DB_MASTER );
972 if( $revId ) {
973 $rev = $dbw->addQuotes( $revId );
974 } else {
975 $rev = 'page_latest';
977 $result = $dbw->query(
978 sprintf( "SELECT old_text, old_flags
979 FROM %s,%s,%s
980 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
981 AND %s=%s",
982 $dbw->tableName( 'page' ),
983 $dbw->tableName( 'revision' ),
984 $dbw->tableName( 'text' ),
985 IntVal( $this->mTitle->getArticleId() ),
986 $field,
987 $rev ),
988 $fname );
989 $obj = $dbw->fetchObject( $result );
990 $dbw->freeResult( $result );
991 $oldtext = Revision::getRevisionText( $obj );
992 return $oldtext;
995 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
996 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
997 if ($section != '') {
998 if( is_null( $edittime ) ) {
999 $rev = Revision::newFromTitle( $this->mTitle );
1000 } else {
1001 $dbw =& wfGetDB( DB_MASTER );
1002 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1004 $oldtext = $rev->getText();
1006 if($section=='new') {
1007 if($summary) $subject="== {$summary} ==\n\n";
1008 $text=$oldtext."\n\n".$subject.$text;
1009 } else {
1011 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1012 # comments to be stripped as well)
1013 $striparray=array();
1014 $parser=new Parser();
1015 $parser->mOutputType=OT_WIKI;
1016 $oldtext=$parser->strip($oldtext, $striparray, true);
1018 # now that we can be sure that no pseudo-sections are in the source,
1019 # split it up
1020 # Unfortunately we can't simply do a preg_replace because that might
1021 # replace the wrong section, so we have to use the section counter instead
1022 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1023 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1024 $secs[$section*2]=$text."\n\n"; // replace with edited
1026 # section 0 is top (intro) section
1027 if($section!=0) {
1029 # headline of old section - we need to go through this section
1030 # to determine if there are any subsections that now need to
1031 # be erased, as the mother section has been replaced with
1032 # the text of all subsections.
1033 $headline=$secs[$section*2-1];
1034 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1035 $hlevel=$matches[1];
1037 # determine headline level for wikimarkup headings
1038 if(strpos($hlevel,'=')!==false) {
1039 $hlevel=strlen($hlevel);
1042 $secs[$section*2-1]=''; // erase old headline
1043 $count=$section+1;
1044 $break=false;
1045 while(!empty($secs[$count*2-1]) && !$break) {
1047 $subheadline=$secs[$count*2-1];
1048 preg_match(
1049 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1050 $subhlevel=$matches[1];
1051 if(strpos($subhlevel,'=')!==false) {
1052 $subhlevel=strlen($subhlevel);
1054 if($subhlevel > $hlevel) {
1055 // erase old subsections
1056 $secs[$count*2-1]='';
1057 $secs[$count*2]='';
1059 if($subhlevel <= $hlevel) {
1060 $break=true;
1062 $count++;
1067 $text=join('',$secs);
1068 # reinsert the stuff that we stripped out earlier
1069 $text=$parser->unstrip($text,$striparray);
1070 $text=$parser->unstripNoWiki($text,$striparray);
1074 return $text;
1078 * Change an existing article. Puts the previous version back into the old table, updates RC
1079 * and all necessary caches, mostly via the deferred update array.
1081 * It is possible to call this function from a command-line script, but note that you should
1082 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1084 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1085 global $wgOut, $wgUser;
1086 global $wgDBtransactions, $wgMwRedir;
1087 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1089 $fname = 'Article::updateArticle';
1090 $good = true;
1092 $isminor = ( $minor && $wgUser->isLoggedIn() );
1093 if ( $this->isRedirect( $text ) ) {
1094 # Remove all content but redirect
1095 # This could be done by reconstructing the redirect from a title given by
1096 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1097 # wants to see
1098 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1099 $redir = 1;
1100 $text = $m[1] . "\n";
1103 else { $redir = 0; }
1105 $text = $this->preSaveTransform( $text );
1106 $dbw =& wfGetDB( DB_MASTER );
1107 $now = wfTimestampNow();
1109 # Update article, but only if changed.
1111 # It's important that we either rollback or complete, otherwise an attacker could
1112 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1113 # could conceivably have the same effect, especially if cur is locked for long periods.
1114 if( !$wgDBtransactions ) {
1115 $userAbort = ignore_user_abort( true );
1118 $oldtext = $this->getContent( true );
1119 $lastRevision = 0;
1121 if ( 0 != strcmp( $text, $oldtext ) ) {
1122 $this->mCountAdjustment = $this->isCountable( $text )
1123 - $this->isCountable( $oldtext );
1124 $now = wfTimestampNow();
1126 $lastRevision = $dbw->selectField(
1127 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1129 $revision = new Revision( array(
1130 'page' => $this->getId(),
1131 'comment' => $summary,
1132 'minor_edit' => $isminor,
1133 'text' => $text
1134 ) );
1135 $revisionId = $revision->insertOn( $dbw );
1137 # Update page
1138 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1140 if( !$ok ) {
1141 /* Belated edit conflict! Run away!! */
1142 $good = false;
1143 } else {
1144 # Update recentchanges and purge cache and whatnot
1145 $bot = (int)($wgUser->isBot() || $forceBot);
1146 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1147 $lastRevision, $this->getTimestamp(), $bot );
1148 Article::onArticleEdit( $this->mTitle );
1152 if( !$wgDBtransactions ) {
1153 ignore_user_abort( $userAbort );
1156 if ( $good ) {
1157 if ($watchthis) {
1158 if (!$this->mTitle->userIsWatching()) $this->watch();
1159 } else {
1160 if ( $this->mTitle->userIsWatching() ) {
1161 $this->unwatch();
1164 # standard deferred updates
1165 $this->editUpdates( $text, $summary, $minor, $now );
1168 $urls = array();
1169 # Template namespace
1170 # Purge all articles linking here
1171 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1172 $titles = $this->mTitle->getLinksTo();
1173 Title::touchArray( $titles );
1174 if ( $wgUseSquid ) {
1175 foreach ( $titles as $title ) {
1176 $urls[] = $title->getInternalURL();
1181 # Squid updates
1182 if ( $wgUseSquid ) {
1183 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1184 $u = new SquidUpdate( $urls );
1185 array_push( $wgPostCommitUpdateList, $u );
1188 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1190 return $good;
1194 * After we've either updated or inserted the article, update
1195 * the link tables and redirect to the new page.
1197 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1198 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1200 $wgLinkCache = new LinkCache();
1201 # Select for update
1202 $wgLinkCache->forUpdate( true );
1204 # Get old version of link table to allow incremental link updates
1205 $wgLinkCache->preFill( $this->mTitle );
1206 $wgLinkCache->clear();
1208 # Parse the text and replace links with placeholders
1209 $wgOut = new OutputPage();
1210 $wgOut->addWikiText( $text );
1212 # Look up the links in the DB and add them to the link cache
1213 $wgOut->transformBuffer( RLH_FOR_UPDATE );
1215 if( $this->isRedirect( $text ) )
1216 $r = 'redirect=no';
1217 else
1218 $r = '';
1219 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1221 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1222 # this will be improved later (to-do)
1224 include_once( "UserMailer.php" );
1225 $wgEnotif = new EmailNotification ();
1226 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle->getDBkey(), $this->mTitle->getNamespace(),$now, $summary, $me2, $oldid );
1230 * Mark this particular edit as patrolled
1232 function markpatrolled() {
1233 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1234 $wgOut->setRobotpolicy( 'noindex,follow' );
1236 if ( !$wgUseRCPatrol )
1238 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1239 return;
1241 if ( $wgUser->isAnon() )
1243 $wgOut->loginToUse();
1244 return;
1246 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1248 $wgOut->sysopRequired();
1249 return;
1251 $rcid = $wgRequest->getVal( 'rcid' );
1252 if ( !is_null ( $rcid ) )
1254 RecentChange::markPatrolled( $rcid );
1255 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1256 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1258 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1259 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1261 else
1263 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1268 * Validate function
1270 function validate() {
1271 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1273 if ( !$wgUseValidation ) # Are we using article validation at all?
1275 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1276 return ;
1279 $wgOut->setRobotpolicy( 'noindex,follow' );
1280 $revision = $wgRequest->getVal( 'revision' );
1282 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1284 $v = new Validation ;
1285 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1286 $t = $v->showList ( $this ) ;
1287 else
1288 $t = $v->validatePageForm ( $this , $revision ) ;
1290 $wgOut->addHTML ( $t ) ;
1294 * Add this page to $wgUser's watchlist
1297 function watch() {
1299 global $wgUser, $wgOut;
1301 if ( $wgUser->isAnon() ) {
1302 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1303 return;
1305 if ( wfReadOnly() ) {
1306 $wgOut->readOnlyPage();
1307 return;
1310 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1312 $wgUser->addWatch( $this->mTitle );
1313 $wgUser->saveSettings();
1315 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1317 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1318 $wgOut->setRobotpolicy( 'noindex,follow' );
1320 $link = $this->mTitle->getPrefixedText();
1321 $text = wfMsg( 'addedwatchtext', $link );
1322 $wgOut->addWikiText( $text );
1325 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1329 * Stop watching a page
1332 function unwatch() {
1334 global $wgUser, $wgOut;
1336 if ( $wgUser->isAnon() ) {
1337 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1338 return;
1340 if ( wfReadOnly() ) {
1341 $wgOut->readOnlyPage();
1342 return;
1345 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1347 $wgUser->removeWatch( $this->mTitle );
1348 $wgUser->saveSettings();
1350 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1352 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1353 $wgOut->setRobotpolicy( 'noindex,follow' );
1355 $link = $this->mTitle->getPrefixedText();
1356 $text = wfMsg( 'removedwatchtext', $link );
1357 $wgOut->addWikiText( $text );
1360 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1364 * protect a page
1366 function protect( $limit = 'sysop' ) {
1367 global $wgUser, $wgOut, $wgRequest;
1369 if ( ! $wgUser->isAllowed('protect') ) {
1370 $wgOut->sysopRequired();
1371 return;
1373 if ( wfReadOnly() ) {
1374 $wgOut->readOnlyPage();
1375 return;
1377 $id = $this->mTitle->getArticleID();
1378 if ( 0 == $id ) {
1379 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1380 return;
1383 $confirm = $wgRequest->wasPosted() &&
1384 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1385 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1386 $reason = $wgRequest->getText( 'wpReasonProtect' );
1388 if ( $confirm ) {
1389 $dbw =& wfGetDB( DB_MASTER );
1390 $dbw->update( 'page',
1391 array( /* SET */
1392 'page_touched' => $dbw->timestamp(),
1393 'page_restrictions' => (string)$limit
1394 ), array( /* WHERE */
1395 'page_id' => $id
1396 ), 'Article::protect'
1399 $restrictions = "move=" . $limit;
1400 if( !$moveonly ) {
1401 $restrictions .= ":edit=" . $limit;
1403 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1405 $dbw =& wfGetDB( DB_MASTER );
1406 $dbw->update( 'page',
1407 array( /* SET */
1408 'page_touched' => $dbw->timestamp(),
1409 'page_restrictions' => $restrictions
1410 ), array( /* WHERE */
1411 'page_id' => $id
1412 ), 'Article::protect'
1415 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1417 $log = new LogPage( 'protect' );
1418 if ( $limit === '' ) {
1419 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1420 } else {
1421 $log->addEntry( 'protect', $this->mTitle, $reason );
1423 $wgOut->redirect( $this->mTitle->getFullURL() );
1425 return;
1426 } else {
1427 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1428 return $this->confirmProtect( '', $reason, $limit );
1433 * Output protection confirmation dialog
1435 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1436 global $wgOut, $wgUser;
1438 wfDebug( "Article::confirmProtect\n" );
1440 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1441 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1443 $check = '';
1444 $protcom = '';
1445 $moveonly = '';
1447 if ( $limit === '' ) {
1448 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1449 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1450 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1451 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1452 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1453 } else {
1454 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1455 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1456 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1457 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1458 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1459 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1462 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1463 $token = htmlspecialchars( $wgUser->editToken() );
1465 $wgOut->addHTML( "
1466 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1467 <table border='0'>
1468 <tr>
1469 <td align='right'>
1470 <label for='wpReasonProtect'>{$protcom}:</label>
1471 </td>
1472 <td align='left'>
1473 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1474 </td>
1475 </tr>" );
1476 if($moveonly != '') {
1477 $wgOut->AddHTML( "
1478 <tr>
1479 <td align='right'>
1480 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1481 </td>
1482 <td align='left'>
1483 <label for='wpMoveOnly'>{$moveonly}</label>
1484 </td>
1485 </tr> " );
1487 $wgOut->addHTML( "
1488 <tr>
1489 <td>&nbsp;</td>
1490 <td>
1491 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1492 </td>
1493 </tr>
1494 </table>
1495 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1496 </form>" );
1498 $wgOut->returnToMain( false );
1502 * Unprotect the pages
1504 function unprotect() {
1505 return $this->protect( '' );
1509 * UI entry point for page deletion
1511 function delete() {
1512 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1513 $fname = 'Article::delete';
1514 $confirm = $wgRequest->wasPosted() &&
1515 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1516 $reason = $wgRequest->getText( 'wpReason' );
1518 # This code desperately needs to be totally rewritten
1520 # Check permissions
1521 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1522 $wgOut->sysopRequired();
1523 return;
1525 if ( wfReadOnly() ) {
1526 $wgOut->readOnlyPage();
1527 return;
1530 # Better double-check that it hasn't been deleted yet!
1531 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1532 if ( ( '' == trim( $this->mTitle->getText() ) )
1533 or ( $this->mTitle->getArticleId() == 0 ) ) {
1534 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1535 return;
1538 if ( $confirm ) {
1539 $this->doDelete( $reason );
1540 return;
1543 # determine whether this page has earlier revisions
1544 # and insert a warning if it does
1545 # we select the text because it might be useful below
1546 $dbr =& $this->getDB();
1547 $ns = $this->mTitle->getNamespace();
1548 $title = $this->mTitle->getDBkey();
1549 $revisions = $dbr->select( array( 'page', 'revision' ),
1550 array( 'rev_id' ),
1551 array(
1552 'page_namespace' => $ns,
1553 'page_title' => $title,
1554 'rev_page = page_id'
1555 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1558 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1559 $skin=$wgUser->getSkin();
1560 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1561 $wgOut->addHTML( $skin->historyLink() .'</b>');
1564 # Fetch cur_text
1565 $s = $dbr->selectRow( array( 'page', 'text' ),
1566 array( 'old_text' ),
1567 array(
1568 'page_namespace' => $ns,
1569 'page_title' => $title,
1570 'page_latest = old_id'
1571 ), $fname, $this->getSelectOptions()
1574 if( $s !== false ) {
1575 # if this is a mini-text, we can paste part of it into the deletion reason
1577 #if this is empty, an earlier revision may contain "useful" text
1578 $blanked = false;
1579 if($s->old_text != '') {
1580 $text=$s->old_text;
1581 } else {
1582 if($old) { # TODO
1583 $text = Revision::getRevisionText( $old );
1584 $blanked = true;
1589 $length=strlen($text);
1591 # this should not happen, since it is not possible to store an empty, new
1592 # page. Let's insert a standard text in case it does, though
1593 if($length == 0 && $reason === '') {
1594 $reason = wfMsg('exblank');
1597 if($length < 500 && $reason === '') {
1599 # comment field=255, let's grep the first 150 to have some user
1600 # space left
1601 $text=substr($text,0,150);
1602 # let's strip out newlines and HTML tags
1603 $text=preg_replace('/\"/',"'",$text);
1604 $text=preg_replace('/\</','&lt;',$text);
1605 $text=preg_replace('/\>/','&gt;',$text);
1606 $text=preg_replace("/[\n\r]/",'',$text);
1607 if(!$blanked) {
1608 $reason=wfMsg('excontent'). " '".$text;
1609 } else {
1610 $reason=wfMsg('exbeforeblank') . " '".$text;
1612 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1613 $reason.="'";
1617 return $this->confirmDelete( '', $reason );
1621 * Output deletion confirmation dialog
1623 function confirmDelete( $par, $reason ) {
1624 global $wgOut, $wgUser;
1626 wfDebug( "Article::confirmDelete\n" );
1628 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1629 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1630 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1631 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1633 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1635 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1636 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1637 $token = htmlspecialchars( $wgUser->editToken() );
1639 $wgOut->addHTML( "
1640 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1641 <table border='0'>
1642 <tr>
1643 <td align='right'>
1644 <label for='wpReason'>{$delcom}:</label>
1645 </td>
1646 <td align='left'>
1647 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1648 </td>
1649 </tr>
1650 <tr>
1651 <td>&nbsp;</td>
1652 <td>
1653 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1654 </td>
1655 </tr>
1656 </table>
1657 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1658 </form>\n" );
1660 $wgOut->returnToMain( false );
1665 * Perform a deletion and output success or failure messages
1667 function doDelete( $reason ) {
1668 global $wgOut, $wgUser, $wgContLang;
1669 $fname = 'Article::doDelete';
1670 wfDebug( $fname."\n" );
1672 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1673 if ( $this->doDeleteArticle( $reason ) ) {
1674 $deleted = $this->mTitle->getPrefixedText();
1676 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1677 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1679 $sk = $wgUser->getSkin();
1680 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_SPECIAL ) .
1681 ':Log/delete',
1682 wfMsg( 'deletionlog' ) );
1684 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1686 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1687 $wgOut->returnToMain( false );
1688 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1689 } else {
1690 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1696 * Back-end article deletion
1697 * Deletes the article with database consistency, writes logs, purges caches
1698 * Returns success
1700 function doDeleteArticle( $reason ) {
1701 global $wgUser;
1702 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1704 $fname = 'Article::doDeleteArticle';
1705 wfDebug( $fname."\n" );
1707 $dbw =& wfGetDB( DB_MASTER );
1708 $ns = $this->mTitle->getNamespace();
1709 $t = $this->mTitle->getDBkey();
1710 $id = $this->mTitle->getArticleID();
1712 if ( $t == '' || $id == 0 ) {
1713 return false;
1716 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1717 array_push( $wgDeferredUpdateList, $u );
1719 $linksTo = $this->mTitle->getLinksTo();
1721 # Squid purging
1722 if ( $wgUseSquid ) {
1723 $urls = array(
1724 $this->mTitle->getInternalURL(),
1725 $this->mTitle->getInternalURL( 'history' )
1728 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1729 array_push( $wgPostCommitUpdateList, $u );
1733 # Client and file cache invalidation
1734 Title::touchArray( $linksTo );
1737 // For now, shunt the revision data into the archive table.
1738 // Text is *not* removed from the text table; bulk storage
1739 // is left intact to avoid breaking block-compression or
1740 // immutable storage schemes.
1742 // For backwards compatibility, note that some older archive
1743 // table entries will have ar_text and ar_flags fields still.
1745 // In the future, we may keep revisions and mark them with
1746 // the rev_deleted field, which is reserved for this purpose.
1747 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1748 array(
1749 'ar_namespace' => 'page_namespace',
1750 'ar_title' => 'page_title',
1751 'ar_comment' => 'rev_comment',
1752 'ar_user' => 'rev_user',
1753 'ar_user_text' => 'rev_user_text',
1754 'ar_timestamp' => 'rev_timestamp',
1755 'ar_minor_edit' => 'rev_minor_edit',
1756 'ar_rev_id' => 'rev_id',
1757 'ar_text_id' => 'rev_text_id',
1758 ), array(
1759 'page_id' => $id,
1760 'page_id = rev_page'
1761 ), $fname
1764 # Now that it's safely backed up, delete it
1765 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1766 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1768 # Clean up recentchanges entries...
1769 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1771 # Finally, clean up the link tables
1772 $t = $this->mTitle->getPrefixedDBkey();
1774 Article::onArticleDelete( $this->mTitle );
1776 # Insert broken links
1777 $brokenLinks = array();
1778 foreach ( $linksTo as $titleObj ) {
1779 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1780 $linkID = $titleObj->getArticleID();
1781 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1783 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1785 # Delete live links
1786 $dbw->delete( 'links', array( 'l_to' => $id ) );
1787 $dbw->delete( 'links', array( 'l_from' => $id ) );
1788 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1789 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1790 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1792 # Log the deletion
1793 $log = new LogPage( 'delete' );
1794 $log->addEntry( 'delete', $this->mTitle, $reason );
1796 # Clear the cached article id so the interface doesn't act like we exist
1797 $this->mTitle->resetArticleID( 0 );
1798 $this->mTitle->mArticleID = 0;
1799 return true;
1803 * Revert a modification
1805 function rollback() {
1806 global $wgUser, $wgOut, $wgRequest;
1807 $fname = 'Article::rollback';
1809 if ( ! $wgUser->isAllowed('rollback') ) {
1810 $wgOut->sysopRequired();
1811 return;
1813 if ( wfReadOnly() ) {
1814 $wgOut->readOnlyPage( $this->getContent( true ) );
1815 return;
1817 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1818 array( $this->mTitle->getPrefixedText(),
1819 $wgRequest->getVal( 'from' ) ) ) ) {
1820 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1821 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1822 return;
1824 $dbw =& wfGetDB( DB_MASTER );
1826 # Enhanced rollback, marks edits rc_bot=1
1827 $bot = $wgRequest->getBool( 'bot' );
1829 # Replace all this user's current edits with the next one down
1830 $tt = $this->mTitle->getDBKey();
1831 $n = $this->mTitle->getNamespace();
1833 # Get the last editor, lock table exclusively
1834 $dbw->begin();
1835 $current = Revision::newFromTitle( $this->mTitle );
1836 if( is_null( $current ) ) {
1837 # Something wrong... no page?
1838 $dbw->rollback();
1839 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1840 return;
1843 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1844 if( $from != $current->getUserText() ) {
1845 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1846 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1847 htmlspecialchars( $this->mTitle->getPrefixedText()),
1848 htmlspecialchars( $from ),
1849 htmlspecialchars( $current->getUserText() ) ) );
1850 if( $current->getComment() != '') {
1851 $wgOut->addHTML(
1852 wfMsg( 'editcomment',
1853 htmlspecialchars( $current->getComment() ) ) );
1855 return;
1858 # Get the last edit not by this guy
1859 $user = IntVal( $current->getUser() );
1860 $user_text = $dbw->addQuotes( $current->getUserText() );
1861 $s = $dbw->selectRow( 'revision',
1862 array( 'rev_id', 'rev_timestamp' ),
1863 array(
1864 'rev_page' => $current->getPage(),
1865 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1866 ), $fname,
1867 array(
1868 'USE INDEX' => 'page_timestamp',
1869 'ORDER BY' => 'rev_timestamp DESC' )
1871 if( $s === false ) {
1872 # Something wrong
1873 $dbw->rollback();
1874 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1875 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1876 return;
1879 if ( $bot ) {
1880 # Mark all reverted edits as bot
1881 $dbw->update( 'recentchanges',
1882 array( /* SET */
1883 'rc_bot' => 1
1884 ), array( /* WHERE */
1885 'rc_cur_id' => $current->getPage(),
1886 'rc_user_text' => $current->getUserText(),
1887 "rc_timestamp > '{$s->rev_timestamp}'",
1888 ), $fname
1892 # Save it!
1893 $target = Revision::newFromId( $s->rev_id );
1894 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1896 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1897 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1898 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1900 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1901 Article::onArticleEdit( $this->mTitle );
1903 $dbw->commit();
1904 $wgOut->returnToMain( false );
1909 * Do standard deferred updates after page view
1910 * @private
1912 function viewUpdates() {
1913 global $wgDeferredUpdateList;
1915 if ( 0 != $this->getID() ) {
1916 global $wgDisableCounters;
1917 if( !$wgDisableCounters ) {
1918 Article::incViewCount( $this->getID() );
1919 $u = new SiteStatsUpdate( 1, 0, 0 );
1920 array_push( $wgDeferredUpdateList, $u );
1924 # Update newtalk status if user is reading their own
1925 # talk page
1927 global $wgUser;
1928 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1929 $this->mTitle->getText() == $wgUser->getName()) {
1930 require_once( 'UserTalkUpdate.php' );
1931 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
1932 } else {
1933 $wgUser->clearNotification( $this->mTitle );
1939 * Do standard deferred updates after page edit.
1940 * Every 1000th edit, prune the recent changes table.
1941 * @private
1942 * @param string $text
1944 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1945 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1946 global $wgMessageCache, $wgUser;
1948 wfSeedRandom();
1949 if ( 0 == mt_rand( 0, 999 ) ) {
1950 # Periodically flush old entries from the recentchanges table.
1951 global $wgRCMaxAge;
1952 $dbw =& wfGetDB( DB_MASTER );
1953 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1954 $recentchanges = $dbw->tableName( 'recentchanges' );
1955 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1956 $dbw->query( $sql );
1958 $id = $this->getID();
1959 $title = $this->mTitle->getPrefixedDBkey();
1960 $shortTitle = $this->mTitle->getDBkey();
1962 $adj = $this->mCountAdjustment;
1964 if ( 0 != $id ) {
1965 $u = new LinksUpdate( $id, $title );
1966 array_push( $wgDeferredUpdateList, $u );
1967 $u = new SiteStatsUpdate( 0, 1, $adj );
1968 array_push( $wgDeferredUpdateList, $u );
1969 $u = new SearchUpdate( $id, $title, $text );
1970 array_push( $wgDeferredUpdateList, $u );
1972 # If this is another user's talk page,
1973 # create a watchlist entry for this page
1975 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1976 $shortTitle != $wgUser->getName()) {
1977 require_once( 'UserTalkUpdate.php' );
1978 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1981 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1982 $wgMessageCache->replace( $shortTitle, $text );
1988 * @todo document this function
1989 * @private
1990 * @param string $oldid Revision ID of this article revision
1992 function setOldSubtitle( $oldid=0 ) {
1993 global $wgLang, $wgOut, $wgUser;
1995 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1996 $sk = $wgUser->getSkin();
1997 $lnk = $sk->makeKnownLinkObj ( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
1998 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1999 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2000 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2001 $wgOut->setSubtitle( $r );
2005 * This function is called right before saving the wikitext,
2006 * so we can do things like signatures and links-in-context.
2008 * @param string $text
2010 function preSaveTransform( $text ) {
2011 global $wgParser, $wgUser;
2012 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2015 /* Caching functions */
2018 * checkLastModified returns true if it has taken care of all
2019 * output to the client that is necessary for this request.
2020 * (that is, it has sent a cached version of the page)
2022 function tryFileCache() {
2023 static $called = false;
2024 if( $called ) {
2025 wfDebug( " tryFileCache() -- called twice!?\n" );
2026 return;
2028 $called = true;
2029 if($this->isFileCacheable()) {
2030 $touched = $this->mTouched;
2031 $cache = new CacheManager( $this->mTitle );
2032 if($cache->isFileCacheGood( $touched )) {
2033 global $wgOut;
2034 wfDebug( " tryFileCache() - about to load\n" );
2035 $cache->loadFromFileCache();
2036 return true;
2037 } else {
2038 wfDebug( " tryFileCache() - starting buffer\n" );
2039 ob_start( array(&$cache, 'saveToFileCache' ) );
2041 } else {
2042 wfDebug( " tryFileCache() - not cacheable\n" );
2047 * Check if the page can be cached
2048 * @return bool
2050 function isFileCacheable() {
2051 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2052 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2054 return $wgUseFileCache
2055 and (!$wgShowIPinHeader)
2056 and ($this->getID() != 0)
2057 and ($wgUser->isAnon())
2058 and (!$wgUser->getNewtalk())
2059 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2060 and (empty( $action ) || $action == 'view')
2061 and (!isset($oldid))
2062 and (!isset($diff))
2063 and (!isset($redirect))
2064 and (!isset($printable))
2065 and (!$this->mRedirectedFrom);
2069 * Loads cur_touched and returns a value indicating if it should be used
2072 function checkTouched() {
2073 $fname = 'Article::checkTouched';
2074 if( !$this->mDataLoaded ) {
2075 $dbr =& $this->getDB();
2076 $data = $this->pageDataFromId( $dbr, $this->getId() );
2077 if( $data ) {
2078 $this->loadPageData( $data );
2081 return !$this->mIsRedirect;
2085 * Edit an article without doing all that other stuff
2086 * The article must already exist; link tables etc
2087 * are not updated, caches are not flushed.
2089 * @param string $text text submitted
2090 * @param string $comment comment submitted
2091 * @param bool $minor whereas it's a minor modification
2093 function quickEdit( $text, $comment = '', $minor = 0 ) {
2094 $fname = 'Article::quickEdit';
2095 wfProfileIn( $fname );
2097 $dbw =& wfGetDB( DB_MASTER );
2098 $dbw->begin();
2099 $revision = new Revision( array(
2100 'page' => $this->getId(),
2101 'text' => $text,
2102 'comment' => $comment,
2103 'minor_edit' => $minor ? 1 : 0,
2104 ) );
2105 $revisionId = $revision->insertOn( $dbw );
2106 $this->updateRevisionOn( $dbw, $revision );
2107 $dbw->commit();
2109 wfProfileOut( $fname );
2113 * Used to increment the view counter
2115 * @static
2116 * @param integer $id article id
2118 function incViewCount( $id ) {
2119 $id = intval( $id );
2120 global $wgHitcounterUpdateFreq;
2122 $dbw =& wfGetDB( DB_MASTER );
2123 $pageTable = $dbw->tableName( 'page' );
2124 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2125 $acchitsTable = $dbw->tableName( 'acchits' );
2127 if( $wgHitcounterUpdateFreq <= 1 ){ //
2128 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2129 return;
2132 # Not important enough to warrant an error page in case of failure
2133 $oldignore = $dbw->ignoreErrors( true );
2135 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2137 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2138 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2139 # Most of the time (or on SQL errors), skip row count check
2140 $dbw->ignoreErrors( $oldignore );
2141 return;
2144 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2145 $row = $dbw->fetchObject( $res );
2146 $rown = intval( $row->n );
2147 if( $rown >= $wgHitcounterUpdateFreq ){
2148 wfProfileIn( 'Article::incViewCount-collect' );
2149 $old_user_abort = ignore_user_abort( true );
2151 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2152 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2153 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2154 'GROUP BY hc_id');
2155 $dbw->query("DELETE FROM $hitcounterTable");
2156 $dbw->query('UNLOCK TABLES');
2157 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2158 'WHERE page_id = hc_id');
2159 $dbw->query("DROP TABLE $acchitsTable");
2161 ignore_user_abort( $old_user_abort );
2162 wfProfileOut( 'Article::incViewCount-collect' );
2164 $dbw->ignoreErrors( $oldignore );
2167 /**#@+
2168 * The onArticle*() functions are supposed to be a kind of hooks
2169 * which should be called whenever any of the specified actions
2170 * are done.
2172 * This is a good place to put code to clear caches, for instance.
2174 * This is called on page move and undelete, as well as edit
2175 * @static
2176 * @param $title_obj a title object
2179 function onArticleCreate($title_obj) {
2180 global $wgUseSquid, $wgPostCommitUpdateList;
2182 $titles = $title_obj->getBrokenLinksTo();
2184 # Purge squid
2185 if ( $wgUseSquid ) {
2186 $urls = $title_obj->getSquidURLs();
2187 foreach ( $titles as $linkTitle ) {
2188 $urls[] = $linkTitle->getInternalURL();
2190 $u = new SquidUpdate( $urls );
2191 array_push( $wgPostCommitUpdateList, $u );
2194 # Clear persistent link cache
2195 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2198 function onArticleDelete($title_obj) {
2199 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
2201 function onArticleEdit($title_obj) {
2202 LinkCache::linksccClearPage( $title_obj->getArticleID() );
2204 /**#@-*/
2207 * Info about this page
2208 * Called for ?action=info when $wgAllowPageInfo is on.
2210 * @access public
2212 function info() {
2213 global $wgLang, $wgOut, $wgAllowPageInfo;
2214 $fname = 'Article::info';
2216 if ( !$wgAllowPageInfo ) {
2217 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2218 return;
2221 $page = $this->mTitle->getSubjectPage();
2223 $wgOut->setPagetitle( $page->getPrefixedText() );
2224 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2226 # first, see if the page exists at all.
2227 $exists = $page->getArticleId() != 0;
2228 if( !$exists ) {
2229 $wgOut->addHTML( wfMsg('noarticletext') );
2230 } else {
2231 $dbr =& $this->getDB( DB_SLAVE );
2232 $wl_clause = array(
2233 'wl_title' => $page->getDBkey(),
2234 'wl_namespace' => $page->getNamespace() );
2235 $numwatchers = $dbr->selectField(
2236 'watchlist',
2237 'COUNT(*)',
2238 $wl_clause,
2239 $fname,
2240 $this->getSelectOptions() );
2242 $pageInfo = $this->pageCountInfo( $page );
2243 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2245 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2246 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2247 if( $talkInfo ) {
2248 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2250 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2251 if( $talkInfo ) {
2252 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2254 $wgOut->addHTML( '</ul>' );
2260 * Return the total number of edits and number of unique editors
2261 * on a given page. If page does not exist, returns false.
2263 * @param Title $title
2264 * @return array
2265 * @access private
2267 function pageCountInfo( $title ) {
2268 $id = $title->getArticleId();
2269 if( $id == 0 ) {
2270 return false;
2273 $dbr =& $this->getDB( DB_SLAVE );
2275 $rev_clause = array( 'rev_page' => $id );
2276 $fname = 'Article::pageCountInfo';
2278 $edits = $dbr->selectField(
2279 'revision',
2280 'COUNT(rev_page)',
2281 $rev_clause,
2282 $fname,
2283 $this->getSelectOptions() );
2285 $authors = $dbr->selectField(
2286 'revision',
2287 'COUNT(DISTINCT rev_user_text)',
2288 $rev_clause,
2289 $fname,
2290 $this->getSelectOptions() );
2292 return array( 'edits' => $edits, 'authors' => $authors );
2296 * Return a list of templates used by this article.
2297 * Uses the links table to find the templates
2299 * @return array
2301 function getUsedTemplates() {
2302 $result = array();
2303 $id = $this->mTitle->getArticleID();
2305 $db =& wfGetDB( DB_SLAVE );
2306 $page = $db->tableName( 'page' );
2307 $links = $db->tableName( 'links' );
2308 $sql = "SELECT page_title ".
2309 "FROM $page,$links WHERE l_to=page_id AND l_from={$id} and page_namespace=".NS_TEMPLATE;
2310 $res = $db->query( $sql, "Article:getUsedTemplates" );
2311 if ( false !== $res ) {
2312 if ( $db->numRows( $res ) ) {
2313 while ( $row = $db->fetchObject( $res ) ) {
2314 $result[] = $row->page_title;
2318 $db->freeResult( $res );
2319 return $result;