8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
22 var $mContentLoaded; //!<
25 var $mGoodAdjustment; //!<
29 var $mRedirectedFrom; //!<
30 var $mRedirectUrl; //!<
31 var $mRevIdFetched; //!<
35 var $mTotalAdjustment; //!<
42 * Constructor and clear the article
43 * @param $title Reference to a Title object.
44 * @param $oldId Integer revision ID, null to fetch from request, zero for current
46 function Article( &$title, $oldId = null ) {
47 $this->mTitle
=& $title;
48 $this->mOldId
= $oldId;
53 * Tell the page view functions that this view was redirected
54 * from another page on the wiki.
55 * @param $from Title object.
57 function setRedirectedFrom( $from ) {
58 $this->mRedirectedFrom
= $from;
62 * @return mixed false, Title of in-wiki target, or string with URL
64 function followRedirect() {
65 $text = $this->getContent();
66 $rt = Title
::newFromRedirect( $text );
68 # process if title object is valid and not special:userlogout
70 if( $rt->getInterwiki() != '' ) {
71 if( $rt->isLocal() ) {
72 // Offsite wikis need an HTTP redirect.
74 // This can be hard to reverse and may produce loops,
75 // so they may be disabled in the site configuration.
77 $source = $this->mTitle
->getFullURL( 'redirect=no' );
78 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
81 if( $rt->getNamespace() == NS_SPECIAL
) {
82 // Gotta handle redirects to special pages differently:
83 // Fill the HTTP response "Location" header and ignore
84 // the rest of the page we're on.
86 // This can be hard to reverse, so they may be disabled.
88 if( $rt->isSpecial( 'Userlogout' ) ) {
91 return $rt->getFullURL();
98 // No or invalid redirect
103 * get the title object of the article
105 function getTitle() {
106 return $this->mTitle
;
114 $this->mDataLoaded
= false;
115 $this->mContentLoaded
= false;
117 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
118 $this->mRedirectedFrom
= null; # Title object if set
120 $this->mTimestamp
= $this->mComment
= '';
121 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
122 $this->mTouched
= '19700101000000';
123 $this->mForUpdate
= false;
124 $this->mIsRedirect
= false;
125 $this->mRevIdFetched
= 0;
126 $this->mRedirectUrl
= false;
127 $this->mLatest
= false;
131 * Note that getContent/loadContent do not follow redirects anymore.
132 * If you need to fetch redirectable content easily, try
133 * the shortcut in Article::followContent()
135 * @todo There are still side-effects in this!
136 * In general, you should use the Revision class, not Article,
137 * to fetch text for purposes other than page views.
139 * @return Return the text of this revision
141 function getContent() {
142 global $wgUser, $wgOut;
144 wfProfileIn( __METHOD__
);
146 if ( 0 == $this->getID() ) {
147 wfProfileOut( __METHOD__
);
148 $wgOut->setRobotpolicy( 'noindex,nofollow' );
150 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
151 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
153 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
156 return "<div class='noarticletext'>$ret</div>";
158 $this->loadContent();
159 wfProfileOut( __METHOD__
);
160 return $this->mContent
;
165 * This function returns the text of a section, specified by a number ($section).
166 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
167 * the first section before any such heading (section 0).
169 * If a section contains subsections, these are also returned.
171 * @param $text String: text to look in
172 * @param $section Integer: section number
173 * @return string text of the requested section
176 function getSection($text,$section) {
178 return $wgParser->getSection( $text, $section );
182 * @return int The oldid of the article that is to be shown, 0 for the
185 function getOldID() {
186 if ( is_null( $this->mOldId
) ) {
187 $this->mOldId
= $this->getOldIDFromRequest();
189 return $this->mOldId
;
193 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
195 * @return int The old id for the request
197 function getOldIDFromRequest() {
199 $this->mRedirectUrl
= false;
200 $oldid = $wgRequest->getVal( 'oldid' );
201 if ( isset( $oldid ) ) {
202 $oldid = intval( $oldid );
203 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
204 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
208 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
210 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
211 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
229 * Load the revision (including text) into this object
231 function loadContent() {
232 if ( $this->mContentLoaded
) return;
235 $oldid = $this->getOldID();
237 # Pre-fill content with error message so that if something
238 # fails we'll have something telling us what we intended.
239 $this->mOldId
= $oldid;
240 $this->fetchContent( $oldid );
245 * Fetch a page record with the given conditions
246 * @param Database $dbr
247 * @param array $conditions
250 function pageData( &$dbr, $conditions ) {
262 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
263 $row = $dbr->selectRow( 'page',
266 'Article::pageData' );
267 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
272 * @param Database $dbr
273 * @param Title $title
275 function pageDataFromTitle( &$dbr, $title ) {
276 return $this->pageData( $dbr, array(
277 'page_namespace' => $title->getNamespace(),
278 'page_title' => $title->getDBkey() ) );
282 * @param Database $dbr
285 function pageDataFromId( &$dbr, $id ) {
286 return $this->pageData( $dbr, array( 'page_id' => $id ) );
290 * Set the general counter, title etc data loaded from
293 * @param object $data
296 function loadPageData( $data = 'fromdb' ) {
297 if ( $data === 'fromdb' ) {
298 $dbr =& $this->getDB();
299 $data = $this->pageDataFromId( $dbr, $this->getId() );
302 $lc =& LinkCache
::singleton();
304 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
306 $this->mTitle
->mArticleID
= $data->page_id
;
308 $this->mCounter
= $data->page_counter
;
309 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
310 $this->mIsRedirect
= $data->page_is_redirect
;
311 $this->mLatest
= $data->page_latest
;
313 if ( is_object( $this->mTitle
) ) {
314 $lc->addBadLinkObj( $this->mTitle
);
316 $this->mTitle
->mArticleID
= 0;
319 $this->mDataLoaded
= true;
323 * Get text of an article from database
324 * Does *NOT* follow redirects.
325 * @param int $oldid 0 for whatever the latest revision is
328 function fetchContent( $oldid = 0 ) {
329 if ( $this->mContentLoaded
) {
330 return $this->mContent
;
333 $dbr =& $this->getDB();
335 # Pre-fill content with error message so that if something
336 # fails we'll have something telling us what we intended.
337 $t = $this->mTitle
->getPrefixedText();
339 $t .= ',oldid='.$oldid;
341 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
344 $revision = Revision
::newFromId( $oldid );
345 if( is_null( $revision ) ) {
346 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
349 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
351 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
354 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
355 $this->loadPageData( $data );
357 if( !$this->mDataLoaded
) {
358 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
360 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
363 $this->loadPageData( $data );
365 $revision = Revision
::newFromId( $this->mLatest
);
366 if( is_null( $revision ) ) {
367 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
372 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
373 // We should instead work with the Revision object when we need it...
374 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
375 //$this->mContent = $revision->getText();
377 $this->mUser
= $revision->getUser();
378 $this->mUserText
= $revision->getUserText();
379 $this->mComment
= $revision->getComment();
380 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
382 $this->mRevIdFetched
= $revision->getID();
383 $this->mContentLoaded
= true;
384 $this->mRevision
=& $revision;
386 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
388 return $this->mContent
;
392 * Read/write accessor to select FOR UPDATE
394 * @param $x Mixed: FIXME
396 function forUpdate( $x = NULL ) {
397 return wfSetVar( $this->mForUpdate
, $x );
401 * Get the database which should be used for reads
406 $ret =& wfGetDB( DB_MASTER
);
411 * Get options for all SELECT statements
413 * @param $options Array: an optional options array which'll be appended to
415 * @return Array: options
417 function getSelectOptions( $options = '' ) {
418 if ( $this->mForUpdate
) {
419 if ( is_array( $options ) ) {
420 $options[] = 'FOR UPDATE';
422 $options = 'FOR UPDATE';
429 * @return int Page ID
432 if( $this->mTitle
) {
433 return $this->mTitle
->getArticleID();
440 * @return bool Whether or not the page exists in the database
443 return $this->getId() != 0;
447 * @return int The view count for the page
449 function getCount() {
450 if ( -1 == $this->mCounter
) {
451 $id = $this->getID();
455 $dbr =& wfGetDB( DB_SLAVE
);
456 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
457 'Article::getCount', $this->getSelectOptions() );
460 return $this->mCounter
;
464 * Determine whether a page would be suitable for being counted as an
465 * article in the site_stats table based on the title & its content
467 * @param $text String: text to analyze
470 function isCountable( $text ) {
471 global $wgUseCommaCount;
473 $token = $wgUseCommaCount ?
',' : '[[';
475 $this->mTitle
->isContentPage()
476 && !$this->isRedirect( $text )
477 && in_string( $token, $text );
481 * Tests if the article text represents a redirect
483 * @param $text String: FIXME
486 function isRedirect( $text = false ) {
487 if ( $text === false ) {
488 $this->loadContent();
489 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
491 $titleObj = Title
::newFromRedirect( $text );
493 return $titleObj !== NULL;
497 * Returns true if the currently-referenced revision is the current edit
498 * to this page (and it exists).
501 function isCurrent() {
502 return $this->exists() &&
503 isset( $this->mRevision
) &&
504 $this->mRevision
->isCurrent();
508 * Loads everything except the text
509 * This isn't necessary for all uses, so it's only done if needed.
512 function loadLastEdit() {
513 if ( -1 != $this->mUser
)
516 # New or non-existent articles have no user information
517 $id = $this->getID();
518 if ( 0 == $id ) return;
520 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
521 if( !is_null( $this->mLastRevision
) ) {
522 $this->mUser
= $this->mLastRevision
->getUser();
523 $this->mUserText
= $this->mLastRevision
->getUserText();
524 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
525 $this->mComment
= $this->mLastRevision
->getComment();
526 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
527 $this->mRevIdFetched
= $this->mLastRevision
->getID();
531 function getTimestamp() {
532 // Check if the field has been filled by ParserCache::get()
533 if ( !$this->mTimestamp
) {
534 $this->loadLastEdit();
536 return wfTimestamp(TS_MW
, $this->mTimestamp
);
540 $this->loadLastEdit();
544 function getUserText() {
545 $this->loadLastEdit();
546 return $this->mUserText
;
549 function getComment() {
550 $this->loadLastEdit();
551 return $this->mComment
;
554 function getMinorEdit() {
555 $this->loadLastEdit();
556 return $this->mMinorEdit
;
559 function getRevIdFetched() {
560 $this->loadLastEdit();
561 return $this->mRevIdFetched
;
565 * @todo Document, fixme $offset never used.
566 * @param $limit Integer: default 0.
567 * @param $offset Integer: default 0.
569 function getContributors($limit = 0, $offset = 0) {
570 # XXX: this is expensive; cache this info somewhere.
573 $dbr =& wfGetDB( DB_SLAVE
);
574 $revTable = $dbr->tableName( 'revision' );
575 $userTable = $dbr->tableName( 'user' );
576 $user = $this->getUser();
577 $pageId = $this->getId();
579 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
580 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
581 WHERE rev_page = $pageId
582 AND rev_user != $user
583 GROUP BY rev_user, rev_user_text, user_real_name
584 ORDER BY timestamp DESC";
586 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
587 $sql .= ' '. $this->getSelectOptions();
589 $res = $dbr->query($sql, __METHOD__
);
591 while ( $line = $dbr->fetchObject( $res ) ) {
592 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
595 $dbr->freeResult($res);
600 * This is the default action of the script: just view the page of
604 global $wgUser, $wgOut, $wgRequest, $wgContLang;
605 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
606 global $wgUseTrackbacks, $wgNamespaceRobotPolicies;
607 $sk = $wgUser->getSkin();
609 wfProfileIn( __METHOD__
);
611 $parserCache =& ParserCache
::singleton();
612 $ns = $this->mTitle
->getNamespace(); # shortcut
614 # Get variables from query string
615 $oldid = $this->getOldID();
617 # getOldID may want us to redirect somewhere else
618 if ( $this->mRedirectUrl
) {
619 $wgOut->redirect( $this->mRedirectUrl
);
620 wfProfileOut( __METHOD__
);
624 $diff = $wgRequest->getVal( 'diff' );
625 $rcid = $wgRequest->getVal( 'rcid' );
626 $rdfrom = $wgRequest->getVal( 'rdfrom' );
628 $wgOut->setArticleFlag( true );
629 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
630 $policy = $wgNamespaceRobotPolicies[$ns];
632 # The default policy. Dev note: make sure you change the documentation
633 # in DefaultSettings.php before changing it.
634 $policy = 'index,follow';
636 $wgOut->setRobotpolicy( $policy );
638 # If we got diff and oldid in the query, we want to see a
639 # diff page instead of the article.
641 if ( !is_null( $diff ) ) {
642 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
644 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
645 // DifferenceEngine directly fetched the revision:
646 $this->mRevIdFetched
= $de->mNewid
;
649 // Needed to get the page's current revision
650 $this->loadPageData();
651 if( $diff == 0 ||
$diff == $this->mLatest
) {
652 # Run view updates for current revision only
653 $this->viewUpdates();
655 wfProfileOut( __METHOD__
);
659 if ( empty( $oldid ) && $this->checkTouched() ) {
660 $wgOut->setETag($parserCache->getETag($this, $wgUser));
662 if( $wgOut->checkLastModified( $this->mTouched
) ){
663 wfProfileOut( __METHOD__
);
665 } else if ( $this->tryFileCache() ) {
666 # tell wgOut that output is taken care of
668 $this->viewUpdates();
669 wfProfileOut( __METHOD__
);
674 # Should the parser cache be used?
675 $pcache = $wgEnableParserCache &&
676 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
679 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
680 if ( $wgUser->getOption( 'stubthreshold' ) ) {
681 wfIncrStats( 'pcache_miss_stub' );
684 $wasRedirected = false;
685 if ( isset( $this->mRedirectedFrom
) ) {
686 // This is an internally redirected page view.
687 // We'll need a backlink to the source page for navigation.
688 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
689 $sk = $wgUser->getSkin();
690 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
691 $s = wfMsg( 'redirectedfrom', $redir );
692 $wgOut->setSubtitle( $s );
694 // Set the fragment if one was specified in the redirect
695 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
696 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
697 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
699 $wasRedirected = true;
701 } elseif ( !empty( $rdfrom ) ) {
702 // This is an externally redirected view, from some other wiki.
703 // If it was reported from a trusted site, supply a backlink.
704 global $wgRedirectSources;
705 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
706 $sk = $wgUser->getSkin();
707 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
708 $s = wfMsg( 'redirectedfrom', $redir );
709 $wgOut->setSubtitle( $s );
710 $wasRedirected = true;
716 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
717 wfRunHooks( 'ArticleViewHeader', array( &$this ) );
721 if ( !$outputDone ) {
722 $text = $this->getContent();
723 if ( $text === false ) {
724 # Failed to load, replace text with error message
725 $t = $this->mTitle
->getPrefixedText();
727 $t .= ',oldid='.$oldid;
728 $text = wfMsg( 'missingarticle', $t );
730 $text = wfMsg( 'noarticletext', $t );
734 # Another whitelist check in case oldid is altering the title
735 if ( !$this->mTitle
->userCanRead() ) {
736 $wgOut->loginToUse();
741 # We're looking at an old revision
743 if ( !empty( $oldid ) ) {
744 $wgOut->setRobotpolicy( 'noindex,nofollow' );
745 if( is_null( $this->mRevision
) ) {
746 // FIXME: This would be a nice place to load the 'no such page' text.
748 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
749 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
750 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
751 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
752 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
755 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
756 // and we are allowed to see...
765 * @fixme: this hook doesn't work most of the time, as it doesn't
766 * trigger when the parser cache is used.
768 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
769 $wgOut->setRevisionId( $this->getRevIdFetched() );
770 # wrap user css and user js in pre and don't parse
771 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
774 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
776 $wgOut->addWikiText( wfMsg('clearyourcache'));
777 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
778 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
780 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
781 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
782 # Don't overwrite the subtitle if this was an old revision
783 if( !$wasRedirected && $this->isCurrent() ) {
784 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
786 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
788 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
789 '<span class="redirectText">'.$link.'</span>' );
791 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
792 $wgOut->addParserOutputNoText( $parseout );
793 } else if ( $pcache ) {
794 # Display content and save to parser cache
795 $this->outputWikiText( $text );
797 # Display content, don't attempt to save to parser cache
798 # Don't show section-edit links on old revisions... this way lies madness.
799 if( !$this->isCurrent() ) {
800 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
802 # Display content and don't save to parser cache
803 $this->outputWikiText( $text, false );
805 if( !$this->isCurrent() ) {
806 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
810 /* title may have been set from the cache */
811 $t = $wgOut->getPageTitle();
813 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
816 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
817 if( $ns == NS_USER_TALK
&&
818 User
::isIP( $this->mTitle
->getText() ) ) {
819 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
822 # If we have been passed an &rcid= parameter, we want to give the user a
823 # chance to mark this new article as patrolled.
824 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
826 "<div class='patrollink'>" .
827 wfMsg ( 'markaspatrolledlink',
828 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
835 if ($wgUseTrackbacks)
836 $this->addTrackbacks();
838 $this->viewUpdates();
839 wfProfileOut( __METHOD__
);
842 function addTrackbacks() {
843 global $wgOut, $wgUser;
845 $dbr =& wfGetDB(DB_SLAVE
);
847 /* FROM */ 'trackbacks',
848 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
849 /* WHERE */ array('tb_page' => $this->getID())
852 if (!$dbr->numrows($tbs))
856 while ($o = $dbr->fetchObject($tbs)) {
858 if ($wgUser->isAllowed( 'trackback' )) {
859 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
860 . $o->tb_id
. "&token=" . $wgUser->editToken());
861 $rmvtxt = wfMsg('trackbackremove', $delurl);
863 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
870 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
873 function deletetrackback() {
874 global $wgUser, $wgRequest, $wgOut, $wgTitle;
876 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
877 $wgOut->addWikitext(wfMsg('sessionfailure'));
881 if ((!$wgUser->isAllowed('delete'))) {
882 $wgOut->permissionRequired( 'delete' );
887 $wgOut->readOnlyPage();
891 $db =& wfGetDB(DB_MASTER
);
892 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
893 $wgTitle->invalidateCache();
894 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
900 $wgOut->setArticleBodyOnly(true);
905 * Handle action=purge
908 global $wgUser, $wgRequest, $wgOut;
910 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
911 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
915 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
916 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
917 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
918 $msg = str_replace( '$1',
919 "<form method=\"post\" action=\"$action\">\n" .
920 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
923 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
924 $wgOut->setRobotpolicy( 'noindex,nofollow' );
925 $wgOut->addHTML( $msg );
930 * Perform the actions of a page purging
934 // Invalidate the cache
935 $this->mTitle
->invalidateCache();
938 // Commit the transaction before the purge is sent
939 $dbw = wfGetDB( DB_MASTER
);
940 $dbw->immediateCommit();
943 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
950 * Insert a new empty page record for this article.
951 * This *must* be followed up by creating a revision
952 * and running $this->updateToLatest( $rev_id );
953 * or else the record will be left in a funky state.
954 * Best if all done inside a transaction.
956 * @param Database $dbw
957 * @param string $restrictions
958 * @return int The newly created page_id key
961 function insertOn( &$dbw, $restrictions = '' ) {
962 wfProfileIn( __METHOD__
);
964 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
965 $dbw->insert( 'page', array(
966 'page_id' => $page_id,
967 'page_namespace' => $this->mTitle
->getNamespace(),
968 'page_title' => $this->mTitle
->getDBkey(),
970 'page_is_redirect' => 0, # Will set this shortly...
972 'page_random' => wfRandom(),
973 'page_touched' => $dbw->timestamp(),
974 'page_latest' => 0, # Fill this in shortly...
975 'page_len' => 0, # Fill this in shortly...
977 $newid = $dbw->insertId();
979 $this->mTitle
->resetArticleId( $newid );
981 wfProfileOut( __METHOD__
);
986 * Update the page record to point to a newly saved revision.
988 * @param Database $dbw
989 * @param Revision $revision For ID number, and text used to set
990 length and redirect status fields
991 * @param int $lastRevision If given, will not overwrite the page field
992 * when different from the currently set value.
993 * Giving 0 indicates the new page flag should
995 * @param bool $lastRevIsRedirect If given, will optimize adding and
996 * removing rows in redirect table.
997 * @return bool true on success, false on failure
1000 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1001 wfProfileIn( __METHOD__
);
1003 $text = $revision->getText();
1004 $rt = Title
::newFromRedirect( $text );
1006 $conditions = array( 'page_id' => $this->getId() );
1007 if( !is_null( $lastRevision ) ) {
1008 # An extra check against threads stepping on each other
1009 $conditions['page_latest'] = $lastRevision;
1012 $dbw->update( 'page',
1014 'page_latest' => $revision->getId(),
1015 'page_touched' => $dbw->timestamp(),
1016 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1017 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1018 'page_len' => strlen( $text ),
1023 $result = $dbw->affectedRows() != 0;
1026 // FIXME: Should the result from updateRedirectOn() be returned instead?
1027 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1030 wfProfileOut( __METHOD__
);
1035 * Add row to the redirect table if this is a redirect, remove otherwise.
1037 * @param Database $dbw
1038 * @param $redirectTitle a title object pointing to the redirect target,
1039 * or NULL if this is not a redirect
1040 * @param bool $lastRevIsRedirect If given, will optimize adding and
1041 * removing rows in redirect table.
1042 * @return bool true on success, false on failure
1045 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1047 // Always update redirects (target link might have changed)
1048 // Update/Insert if we don't know if the last revision was a redirect or not
1049 // Delete if changing from redirect to non-redirect
1050 $isRedirect = !is_null($redirectTitle);
1051 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1053 wfProfileIn( __METHOD__
);
1057 // This title is a redirect, Add/Update row in the redirect table
1058 $set = array( /* SET */
1059 'rd_namespace' => $redirectTitle->getNamespace(),
1060 'rd_title' => $redirectTitle->getDBkey(),
1061 'rd_from' => $this->getId(),
1064 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1066 // This is not a redirect, remove row from redirect table
1067 $where = array( 'rd_from' => $this->getId() );
1068 $dbw->delete( 'redirect', $where, __METHOD__
);
1071 wfProfileOut( __METHOD__
);
1072 return ( $dbw->affectedRows() != 0 );
1079 * If the given revision is newer than the currently set page_latest,
1080 * update the page record. Otherwise, do nothing.
1082 * @param Database $dbw
1083 * @param Revision $revision
1085 function updateIfNewerOn( &$dbw, $revision ) {
1086 wfProfileIn( __METHOD__
);
1088 $row = $dbw->selectRow(
1089 array( 'revision', 'page' ),
1090 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1092 'page_id' => $this->getId(),
1093 'page_latest=rev_id' ),
1096 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1097 wfProfileOut( __METHOD__
);
1100 $prev = $row->rev_id
;
1101 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1103 # No or missing previous revision; mark the page as new
1105 $lastRevIsRedirect = null;
1108 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1109 wfProfileOut( __METHOD__
);
1114 * @return string Complete article text, or null if error
1116 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1117 wfProfileIn( __METHOD__
);
1119 if( $section == '' ) {
1120 // Whole-page edit; let the text through unmolested.
1122 if( is_null( $edittime ) ) {
1123 $rev = Revision
::newFromTitle( $this->mTitle
);
1125 $dbw =& wfGetDB( DB_MASTER
);
1126 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1128 if( is_null( $rev ) ) {
1129 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1130 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1133 $oldtext = $rev->getText();
1135 if( $section == 'new' ) {
1136 # Inserting a new section
1137 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1138 $text = strlen( trim( $oldtext ) ) > 0
1139 ?
"{$oldtext}\n\n{$subject}{$text}"
1140 : "{$subject}{$text}";
1142 # Replacing an existing section; roll out the big guns
1144 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1149 wfProfileOut( __METHOD__
);
1154 * @deprecated use Article::doEdit()
1156 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1157 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1158 ( $isminor ? EDIT_MINOR
: 0 ) |
1159 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1161 # If this is a comment, add the summary as headline
1162 if ( $comment && $summary != "" ) {
1163 $text = "== {$summary} ==\n\n".$text;
1166 $this->doEdit( $text, $summary, $flags );
1168 $dbw =& wfGetDB( DB_MASTER
);
1170 if (!$this->mTitle
->userIsWatching()) {
1176 if ( $this->mTitle
->userIsWatching() ) {
1182 $this->doRedirect( $this->isRedirect( $text ) );
1186 * @deprecated use Article::doEdit()
1188 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1189 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1190 ( $minor ? EDIT_MINOR
: 0 ) |
1191 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1193 $good = $this->doEdit( $text, $summary, $flags );
1195 $dbw =& wfGetDB( DB_MASTER
);
1197 if (!$this->mTitle
->userIsWatching()) {
1203 if ( $this->mTitle
->userIsWatching() ) {
1210 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1218 * Change an existing article or create a new article. Updates RC and all necessary caches,
1219 * optionally via the deferred update array.
1221 * $wgUser must be set before calling this function.
1223 * @param string $text New text
1224 * @param string $summary Edit summary
1225 * @param integer $flags bitfield:
1227 * Article is known or assumed to be non-existent, create a new one
1229 * Article is known or assumed to be pre-existing, update it
1231 * Mark this edit minor, if the user is allowed to do so
1233 * Do not log the change in recentchanges
1235 * Mark the edit a "bot" edit regardless of user rights
1236 * EDIT_DEFER_UPDATES
1237 * Defer some of the updates until the end of index.php
1239 * Fill in blank summaries with generated text where possible
1241 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1242 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1243 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1244 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1245 * to MediaWiki's performance-optimised locking strategy.
1247 * @return bool success
1249 function doEdit( $text, $summary, $flags = 0 ) {
1250 global $wgUser, $wgDBtransactions;
1252 wfProfileIn( __METHOD__
);
1255 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1256 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1258 $flags |
= EDIT_UPDATE
;
1264 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1265 &$summary, $flags & EDIT_MINOR
,
1266 null, null, &$flags ) ) )
1268 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1269 wfProfileOut( __METHOD__
);
1273 # Silently ignore EDIT_MINOR if not allowed
1274 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1275 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1277 $oldtext = $this->getContent();
1278 $oldsize = strlen( $oldtext );
1280 # Provide autosummaries if one is not provided.
1281 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1282 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1284 $text = $this->preSaveTransform( $text );
1285 $newsize = strlen( $text );
1287 $dbw =& wfGetDB( DB_MASTER
);
1288 $now = wfTimestampNow();
1290 if ( $flags & EDIT_UPDATE
) {
1291 # Update article, but only if changed.
1293 # Make sure the revision is either completely inserted or not inserted at all
1294 if( !$wgDBtransactions ) {
1295 $userAbort = ignore_user_abort( true );
1301 if ( 0 != strcmp( $text, $oldtext ) ) {
1302 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1303 - (int)$this->isCountable( $oldtext );
1304 $this->mTotalAdjustment
= 0;
1306 $lastRevision = $dbw->selectField(
1307 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1309 if ( !$lastRevision ) {
1310 # Article gone missing
1311 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1312 wfProfileOut( __METHOD__
);
1316 $revision = new Revision( array(
1317 'page' => $this->getId(),
1318 'comment' => $summary,
1319 'minor_edit' => $isminor,
1324 $revisionId = $revision->insertOn( $dbw );
1327 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1330 /* Belated edit conflict! Run away!! */
1334 # Update recentchanges
1335 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1336 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1337 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1340 # Mark as patrolled if the user can do so
1341 if( $wgUser->isAllowed( 'autopatrol' ) ) {
1342 RecentChange
::markPatrolled( $rcid );
1345 $wgUser->incEditCount();
1349 // Keep the same revision ID, but do some updates on it
1350 $revisionId = $this->getRevIdFetched();
1351 // Update page_touched, this is usually implicit in the page update
1352 // Other cache updates are done in onArticleEdit()
1353 $this->mTitle
->invalidateCache();
1356 if( !$wgDBtransactions ) {
1357 ignore_user_abort( $userAbort );
1361 # Invalidate cache of this article and all pages using this article
1362 # as a template. Partly deferred.
1363 Article
::onArticleEdit( $this->mTitle
);
1365 # Update links tables, site stats, etc.
1366 $changed = ( strcmp( $oldtext, $text ) != 0 );
1367 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1370 # Create new article
1372 # Set statistics members
1373 # We work out if it's countable after PST to avoid counter drift
1374 # when articles are created with {{subst:}}
1375 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1376 $this->mTotalAdjustment
= 1;
1380 # Add the page record; stake our claim on this title!
1381 # This will fail with a database query exception if the article already exists
1382 $newid = $this->insertOn( $dbw );
1384 # Save the revision text...
1385 $revision = new Revision( array(
1387 'comment' => $summary,
1388 'minor_edit' => $isminor,
1391 $revisionId = $revision->insertOn( $dbw );
1393 $this->mTitle
->resetArticleID( $newid );
1395 # Update the page record with revision data
1396 $this->updateRevisionOn( $dbw, $revision, 0 );
1398 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1399 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1400 '', strlen( $text ), $revisionId );
1401 # Mark as patrolled if the user can
1402 if( $wgUser->isAllowed( 'autopatrol' ) ) {
1403 RecentChange
::markPatrolled( $rcid );
1406 $wgUser->incEditCount();
1409 # Update links, etc.
1410 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1413 Article
::onArticleCreate( $this->mTitle
);
1415 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1416 $summary, $flags & EDIT_MINOR
,
1417 null, null, &$flags ) );
1420 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1424 wfRunHooks( 'ArticleSaveComplete',
1425 array( &$this, &$wgUser, $text,
1426 $summary, $flags & EDIT_MINOR
,
1427 null, null, &$flags ) );
1429 wfProfileOut( __METHOD__
);
1434 * @deprecated wrapper for doRedirect
1436 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1437 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1441 * Output a redirect back to the article.
1442 * This is typically used after an edit.
1444 * @param boolean $noRedir Add redirect=no
1445 * @param string $sectionAnchor section to redirect to, including "#"
1447 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1450 $query = 'redirect=no';
1454 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1458 * Mark this particular edit as patrolled
1460 function markpatrolled() {
1461 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1462 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1464 # Check RC patrol config. option
1465 if( !$wgUseRCPatrol ) {
1466 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1471 if( !$wgUser->isAllowed( 'patrol' ) ) {
1472 $wgOut->permissionRequired( 'patrol' );
1476 # If we haven't been given an rc_id value, we can't do anything
1477 $rcid = $wgRequest->getVal( 'rcid' );
1479 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1483 # Handle the 'MarkPatrolled' hook
1484 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1488 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1489 # If it's left up to us, check that the user is allowed to patrol this edit
1490 # If the user has the "autopatrol" right, then we'll assume there are no
1491 # other conditions stopping them doing so
1492 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1493 $rc = RecentChange
::newFromId( $rcid );
1494 # Graceful error handling, as we've done before here...
1495 # (If the recent change doesn't exist, then it doesn't matter whether
1496 # the user is allowed to patrol it or not; nothing is going to happen
1497 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1498 # The user made this edit, and can't patrol it
1499 # Tell them so, and then back off
1500 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1501 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1502 $wgOut->returnToMain( false, $return );
1507 # Mark the edit as patrolled
1508 RecentChange
::markPatrolled( $rcid );
1509 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1512 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1513 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1514 $wgOut->returnToMain( false, $return );
1518 * User-interface handler for the "watch" action
1523 global $wgUser, $wgOut;
1525 if ( $wgUser->isAnon() ) {
1526 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1529 if ( wfReadOnly() ) {
1530 $wgOut->readOnlyPage();
1534 if( $this->doWatch() ) {
1535 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1536 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1538 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1539 $text = wfMsg( 'addedwatchtext', $link );
1540 $wgOut->addWikiText( $text );
1543 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1547 * Add this page to $wgUser's watchlist
1548 * @return bool true on successful watch operation
1550 function doWatch() {
1552 if( $wgUser->isAnon() ) {
1556 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1557 $wgUser->addWatch( $this->mTitle
);
1559 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1566 * User interface handler for the "unwatch" action.
1568 function unwatch() {
1570 global $wgUser, $wgOut;
1572 if ( $wgUser->isAnon() ) {
1573 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1576 if ( wfReadOnly() ) {
1577 $wgOut->readOnlyPage();
1581 if( $this->doUnwatch() ) {
1582 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1583 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1585 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1586 $text = wfMsg( 'removedwatchtext', $link );
1587 $wgOut->addWikiText( $text );
1590 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1594 * Stop watching a page
1595 * @return bool true on successful unwatch
1597 function doUnwatch() {
1599 if( $wgUser->isAnon() ) {
1603 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1604 $wgUser->removeWatch( $this->mTitle
);
1606 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1613 * action=protect handler
1615 function protect() {
1616 $form = new ProtectionForm( $this );
1621 * action=unprotect handler (alias)
1623 function unprotect() {
1628 * Update the article's restriction field, and leave a log entry.
1630 * @param array $limit set of restriction keys
1631 * @param string $reason
1632 * @return bool true on success
1634 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0 ) {
1635 global $wgUser, $wgRestrictionTypes, $wgContLang;
1637 $id = $this->mTitle
->getArticleID();
1638 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1642 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1643 # we expect a single selection, but the schema allows otherwise.
1645 foreach( $wgRestrictionTypes as $action )
1646 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1648 $current = Article
::flattenRestrictions( $current );
1649 $updated = Article
::flattenRestrictions( $limit );
1651 $changed = ( $current != $updated );
1652 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1653 $protect = ( $updated != '' );
1655 # If nothing's changed, do nothing
1657 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1659 $dbw =& wfGetDB( DB_MASTER
);
1661 # Prepare a null revision to be added to the history
1662 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1664 $comment .= ": $reason";
1666 $comment .= " [$updated]";
1667 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1668 $nullRevId = $nullRevision->insertOn( $dbw );
1670 # Update restrictions table
1671 foreach( $limit as $action => $restrictions ) {
1672 if ($restrictions != '' ) {
1673 $dbw->replace( 'page_restrictions', array( 'pr_pagetype'),
1674 array( 'pr_page' => $id, 'pr_type' => $action
1675 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ), __METHOD__
);
1677 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1678 'pr_type' => $action ), __METHOD__
);
1682 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1684 # Update the protection log
1685 $log = new LogPage( 'protect' );
1687 $cascade_description = '';
1690 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1694 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description" ) );
1696 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1700 } # End "changed" check
1706 * Take an array of page restrictions and flatten it to a string
1707 * suitable for insertion into the page_restrictions field.
1708 * @param array $limit
1712 function flattenRestrictions( $limit ) {
1713 if( !is_array( $limit ) ) {
1714 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1718 foreach( $limit as $action => $restrictions ) {
1719 if( $restrictions != '' ) {
1720 $bits[] = "$action=$restrictions";
1723 return implode( ':', $bits );
1727 * UI entry point for page deletion
1730 global $wgUser, $wgOut, $wgRequest;
1731 $confirm = $wgRequest->wasPosted() &&
1732 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1733 $reason = $wgRequest->getText( 'wpReason' );
1735 # This code desperately needs to be totally rewritten
1738 if( $wgUser->isAllowed( 'delete' ) ) {
1739 if( $wgUser->isBlocked( !$confirm ) ) {
1740 $wgOut->blockedPage();
1744 $wgOut->permissionRequired( 'delete' );
1748 if( wfReadOnly() ) {
1749 $wgOut->readOnlyPage();
1753 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1755 # Better double-check that it hasn't been deleted yet!
1756 $dbw =& wfGetDB( DB_MASTER
);
1757 $conds = $this->mTitle
->pageCond();
1758 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1759 if ( $latest === false ) {
1760 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1765 $this->doDelete( $reason );
1766 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1768 } elseif( $this->mTitle
->userIsWatching() ) {
1774 # determine whether this page has earlier revisions
1775 # and insert a warning if it does
1777 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1779 if( count( $authors ) > 1 && !$confirm ) {
1780 $skin=$wgUser->getSkin();
1781 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1784 # If a single user is responsible for all revisions, find out who they are
1785 if ( count( $authors ) == $maxRevisions ) {
1786 // Query bailed out, too many revisions to find out if they're all the same
1787 $authorOfAll = false;
1789 $authorOfAll = reset( $authors );
1790 foreach ( $authors as $author ) {
1791 if ( $authorOfAll != $author ) {
1792 $authorOfAll = false;
1797 # Fetch article text
1798 $rev = Revision
::newFromTitle( $this->mTitle
);
1800 if( !is_null( $rev ) ) {
1801 # if this is a mini-text, we can paste part of it into the deletion reason
1802 $text = $rev->getText();
1804 #if this is empty, an earlier revision may contain "useful" text
1807 $prev = $rev->getPrevious();
1809 $text = $prev->getText();
1814 $length = strlen( $text );
1816 # this should not happen, since it is not possible to store an empty, new
1817 # page. Let's insert a standard text in case it does, though
1818 if( $length == 0 && $reason === '' ) {
1819 $reason = wfMsgForContent( 'exblank' );
1822 if( $length < 500 && $reason === '' ) {
1823 # comment field=255, let's grep the first 150 to have some user
1826 $text = $wgContLang->truncate( $text, 150, '...' );
1828 # let's strip out newlines
1829 $text = preg_replace( "/[\n\r]/", '', $text );
1832 if( $authorOfAll === false ) {
1833 $reason = wfMsgForContent( 'excontent', $text );
1835 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1838 $reason = wfMsgForContent( 'exbeforeblank', $text );
1843 return $this->confirmDelete( '', $reason );
1847 * Get the last N authors
1848 * @param int $num Number of revisions to get
1849 * @param string $revLatest The latest rev_id, selected from the master (optional)
1850 * @return array Array of authors, duplicates not removed
1852 function getLastNAuthors( $num, $revLatest = 0 ) {
1853 wfProfileIn( __METHOD__
);
1855 // First try the slave
1856 // If that doesn't have the latest revision, try the master
1858 $db =& wfGetDB( DB_SLAVE
);
1860 $res = $db->select( array( 'page', 'revision' ),
1861 array( 'rev_id', 'rev_user_text' ),
1863 'page_namespace' => $this->mTitle
->getNamespace(),
1864 'page_title' => $this->mTitle
->getDBkey(),
1865 'rev_page = page_id'
1866 ), __METHOD__
, $this->getSelectOptions( array(
1867 'ORDER BY' => 'rev_timestamp DESC',
1872 wfProfileOut( __METHOD__
);
1875 $row = $db->fetchObject( $res );
1876 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1877 $db =& wfGetDB( DB_MASTER
);
1882 } while ( $continue );
1884 $authors = array( $row->rev_user_text
);
1885 while ( $row = $db->fetchObject( $res ) ) {
1886 $authors[] = $row->rev_user_text
;
1888 wfProfileOut( __METHOD__
);
1893 * Output deletion confirmation dialog
1895 function confirmDelete( $par, $reason ) {
1896 global $wgOut, $wgUser;
1898 wfDebug( "Article::confirmDelete\n" );
1900 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1901 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1902 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1903 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1905 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1907 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1908 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1909 $token = htmlspecialchars( $wgUser->editToken() );
1910 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
1913 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1917 <label for='wpReason'>{$delcom}:</label>
1920 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
1930 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
1934 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1937 $wgOut->returnToMain( false );
1942 * Perform a deletion and output success or failure messages
1944 function doDelete( $reason ) {
1945 global $wgOut, $wgUser;
1946 wfDebug( __METHOD__
."\n" );
1948 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1949 if ( $this->doDeleteArticle( $reason ) ) {
1950 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1952 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1953 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1955 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1956 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1958 $wgOut->addWikiText( $text );
1959 $wgOut->returnToMain( false );
1960 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1962 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1968 * Back-end article deletion
1969 * Deletes the article with database consistency, writes logs, purges caches
1972 function doDeleteArticle( $reason ) {
1973 global $wgUseSquid, $wgDeferredUpdateList;
1974 global $wgUseTrackbacks;
1976 wfDebug( __METHOD__
."\n" );
1978 $dbw =& wfGetDB( DB_MASTER
);
1979 $ns = $this->mTitle
->getNamespace();
1980 $t = $this->mTitle
->getDBkey();
1981 $id = $this->mTitle
->getArticleID();
1983 if ( $t == '' ||
$id == 0 ) {
1987 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1988 array_push( $wgDeferredUpdateList, $u );
1990 // For now, shunt the revision data into the archive table.
1991 // Text is *not* removed from the text table; bulk storage
1992 // is left intact to avoid breaking block-compression or
1993 // immutable storage schemes.
1995 // For backwards compatibility, note that some older archive
1996 // table entries will have ar_text and ar_flags fields still.
1998 // In the future, we may keep revisions and mark them with
1999 // the rev_deleted field, which is reserved for this purpose.
2000 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2002 'ar_namespace' => 'page_namespace',
2003 'ar_title' => 'page_title',
2004 'ar_comment' => 'rev_comment',
2005 'ar_user' => 'rev_user',
2006 'ar_user_text' => 'rev_user_text',
2007 'ar_timestamp' => 'rev_timestamp',
2008 'ar_minor_edit' => 'rev_minor_edit',
2009 'ar_rev_id' => 'rev_id',
2010 'ar_text_id' => 'rev_text_id',
2011 'ar_text' => '\'\'', // Be explicit to appease
2012 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2015 'page_id = rev_page'
2019 # Delete restrictions for it
2020 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2022 # Now that it's safely backed up, delete it
2023 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2025 # If using cascading deletes, we can skip some explicit deletes
2026 if ( !$dbw->cascadingDeletes() ) {
2028 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2030 if ($wgUseTrackbacks)
2031 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2033 # Delete outgoing links
2034 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2035 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2036 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2037 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2038 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2039 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2040 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2043 # If using cleanup triggers, we can skip some manual deletes
2044 if ( !$dbw->cleanupTriggers() ) {
2046 # Clean up recentchanges entries...
2047 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2051 Article
::onArticleDelete( $this->mTitle
);
2054 $log = new LogPage( 'delete' );
2055 $log->addEntry( 'delete', $this->mTitle
, $reason );
2057 # Clear the cached article id so the interface doesn't act like we exist
2058 $this->mTitle
->resetArticleID( 0 );
2059 $this->mTitle
->mArticleID
= 0;
2064 * Revert a modification
2066 function rollback() {
2067 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2069 if( $wgUser->isAllowed( 'rollback' ) ) {
2070 if( $wgUser->isBlocked() ) {
2071 $wgOut->blockedPage();
2075 $wgOut->permissionRequired( 'rollback' );
2079 if ( wfReadOnly() ) {
2080 $wgOut->readOnlyPage( $this->getContent() );
2083 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2084 array( $this->mTitle
->getPrefixedText(),
2085 $wgRequest->getVal( 'from' ) ) ) ) {
2086 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2087 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2090 $dbw =& wfGetDB( DB_MASTER
);
2092 # Enhanced rollback, marks edits rc_bot=1
2093 $bot = $wgRequest->getBool( 'bot' );
2095 # Replace all this user's current edits with the next one down
2097 # Get the last editor
2098 $current = Revision
::newFromTitle( $this->mTitle
);
2099 if( is_null( $current ) ) {
2100 # Something wrong... no page?
2101 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2105 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2106 if( $from != $current->getUserText() ) {
2107 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2108 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2109 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2110 htmlspecialchars( $from ),
2111 htmlspecialchars( $current->getUserText() ) ) );
2112 if( $current->getComment() != '') {
2114 wfMsg( 'editcomment',
2115 htmlspecialchars( $current->getComment() ) ) );
2120 # Get the last edit not by this guy
2121 $user = intval( $current->getUser() );
2122 $user_text = $dbw->addQuotes( $current->getUserText() );
2123 $s = $dbw->selectRow( 'revision',
2124 array( 'rev_id', 'rev_timestamp' ),
2126 'rev_page' => $current->getPage(),
2127 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2130 'USE INDEX' => 'page_timestamp',
2131 'ORDER BY' => 'rev_timestamp DESC' )
2133 if( $s === false ) {
2135 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2136 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2142 # Mark all reverted edits as bot
2145 if ( $wgUseRCPatrol ) {
2146 # Mark all reverted edits as patrolled
2147 $set['rc_patrolled'] = 1;
2151 $dbw->update( 'recentchanges', $set,
2153 'rc_cur_id' => $current->getPage(),
2154 'rc_user_text' => $current->getUserText(),
2155 "rc_timestamp > '{$s->rev_timestamp}'",
2160 # Get the edit summary
2161 $target = Revision
::newFromId( $s->rev_id
);
2162 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2163 $newComment = $wgRequest->getText( 'summary', $newComment );
2166 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2167 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2168 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2170 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2172 $wgOut->returnToMain( false );
2177 * Do standard deferred updates after page view
2180 function viewUpdates() {
2181 global $wgDeferredUpdateList;
2183 if ( 0 != $this->getID() ) {
2184 global $wgDisableCounters;
2185 if( !$wgDisableCounters ) {
2186 Article
::incViewCount( $this->getID() );
2187 $u = new SiteStatsUpdate( 1, 0, 0 );
2188 array_push( $wgDeferredUpdateList, $u );
2192 # Update newtalk / watchlist notification status
2194 $wgUser->clearNotification( $this->mTitle
);
2198 * Do standard deferred updates after page edit.
2199 * Update links tables, site stats, search index and message cache.
2200 * Every 1000th edit, prune the recent changes table.
2203 * @param $text New text of the article
2204 * @param $summary Edit summary
2205 * @param $minoredit Minor edit
2206 * @param $timestamp_of_pagechange Timestamp associated with the page change
2207 * @param $newid rev_id value of the new revision
2208 * @param $changed Whether or not the content actually changed
2210 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2211 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2213 wfProfileIn( __METHOD__
);
2216 $options = new ParserOptions
;
2217 $options->setTidy(true);
2218 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2220 # Save it to the parser cache
2221 $parserCache =& ParserCache
::singleton();
2222 $parserCache->save( $poutput, $this, $wgUser );
2224 # Update the links tables
2225 $u = new LinksUpdate( $this->mTitle
, $poutput );
2228 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2230 if ( 0 == mt_rand( 0, 999 ) ) {
2231 # Periodically flush old entries from the recentchanges table.
2234 $dbw =& wfGetDB( DB_MASTER
);
2235 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2236 $recentchanges = $dbw->tableName( 'recentchanges' );
2237 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2238 $dbw->query( $sql );
2242 $id = $this->getID();
2243 $title = $this->mTitle
->getPrefixedDBkey();
2244 $shortTitle = $this->mTitle
->getDBkey();
2247 wfProfileOut( __METHOD__
);
2251 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2252 array_push( $wgDeferredUpdateList, $u );
2253 $u = new SearchUpdate( $id, $title, $text );
2254 array_push( $wgDeferredUpdateList, $u );
2256 # If this is another user's talk page, update newtalk
2257 # Don't do this if $changed = false otherwise some idiot can null-edit a
2258 # load of user talk pages and piss people off, nor if it's a minor edit
2259 # by a properly-flagged bot.
2260 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2261 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2262 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2263 $other = User
::newFromName( $shortTitle );
2264 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2265 // An anonymous user
2266 $other = new User();
2267 $other->setName( $shortTitle );
2270 $other->setNewtalk( true );
2275 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2276 $wgMessageCache->replace( $shortTitle, $text );
2279 wfProfileOut( __METHOD__
);
2283 * Perform article updates on a special page creation.
2285 * @param Revision $rev
2287 * @fixme This is a shitty interface function. Kill it and replace the
2288 * other shitty functions like editUpdates and such so it's not needed
2291 function createUpdates( $rev ) {
2292 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2293 $this->mTotalAdjustment
= 1;
2294 $this->editUpdates( $rev->getText(), $rev->getComment(),
2295 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2299 * Generate the navigation links when browsing through an article revisions
2300 * It shows the information as:
2301 * Revision as of \<date\>; view current revision
2302 * \<- Previous version | Next Version -\>
2305 * @param string $oldid Revision ID of this article revision
2307 function setOldSubtitle( $oldid=0 ) {
2308 global $wgLang, $wgOut, $wgUser;
2310 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2314 $revision = Revision
::newFromId( $oldid );
2316 $current = ( $oldid == $this->mLatest
);
2317 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2318 $sk = $wgUser->getSkin();
2320 ?
wfMsg( 'currentrevisionlink' )
2321 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2324 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2325 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2327 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2328 : wfMsg( 'previousrevision' );
2330 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2332 $nextlink = $current
2333 ?
wfMsg( 'nextrevision' )
2334 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2335 $nextdiff = $current
2337 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2339 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2340 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2342 $r = "\n\t\t\t\t<div id=\"mw-revision-info\">" . wfMsg( 'revision-info', $td, $userlinks ) . "</div>\n" .
2343 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2344 $wgOut->setSubtitle( $r );
2348 * This function is called right before saving the wikitext,
2349 * so we can do things like signatures and links-in-context.
2351 * @param string $text
2353 function preSaveTransform( $text ) {
2354 global $wgParser, $wgUser;
2355 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2358 /* Caching functions */
2361 * checkLastModified returns true if it has taken care of all
2362 * output to the client that is necessary for this request.
2363 * (that is, it has sent a cached version of the page)
2365 function tryFileCache() {
2366 static $called = false;
2368 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2372 if($this->isFileCacheable()) {
2373 $touched = $this->mTouched
;
2374 $cache = new HTMLFileCache( $this->mTitle
);
2375 if($cache->isFileCacheGood( $touched )) {
2376 wfDebug( "Article::tryFileCache(): about to load file\n" );
2377 $cache->loadFromFileCache();
2380 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2381 ob_start( array(&$cache, 'saveToFileCache' ) );
2384 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2389 * Check if the page can be cached
2392 function isFileCacheable() {
2393 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2394 $action = $wgRequest->getVal( 'action' );
2395 $oldid = $wgRequest->getVal( 'oldid' );
2396 $diff = $wgRequest->getVal( 'diff' );
2397 $redirect = $wgRequest->getVal( 'redirect' );
2398 $printable = $wgRequest->getVal( 'printable' );
2400 return $wgUseFileCache
2401 and (!$wgShowIPinHeader)
2402 and ($this->getID() != 0)
2403 and ($wgUser->isAnon())
2404 and (!$wgUser->getNewtalk())
2405 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2406 and (empty( $action ) ||
$action == 'view')
2407 and (!isset($oldid))
2409 and (!isset($redirect))
2410 and (!isset($printable))
2411 and (!$this->mRedirectedFrom
);
2415 * Loads page_touched and returns a value indicating if it should be used
2418 function checkTouched() {
2419 if( !$this->mDataLoaded
) {
2420 $this->loadPageData();
2422 return !$this->mIsRedirect
;
2426 * Get the page_touched field
2428 function getTouched() {
2429 # Ensure that page data has been loaded
2430 if( !$this->mDataLoaded
) {
2431 $this->loadPageData();
2433 return $this->mTouched
;
2437 * Get the page_latest field
2439 function getLatest() {
2440 if ( !$this->mDataLoaded
) {
2441 $this->loadPageData();
2443 return $this->mLatest
;
2447 * Edit an article without doing all that other stuff
2448 * The article must already exist; link tables etc
2449 * are not updated, caches are not flushed.
2451 * @param string $text text submitted
2452 * @param string $comment comment submitted
2453 * @param bool $minor whereas it's a minor modification
2455 function quickEdit( $text, $comment = '', $minor = 0 ) {
2456 wfProfileIn( __METHOD__
);
2458 $dbw =& wfGetDB( DB_MASTER
);
2460 $revision = new Revision( array(
2461 'page' => $this->getId(),
2463 'comment' => $comment,
2464 'minor_edit' => $minor ?
1 : 0,
2466 $revision->insertOn( $dbw );
2467 $this->updateRevisionOn( $dbw, $revision );
2470 wfProfileOut( __METHOD__
);
2474 * Used to increment the view counter
2477 * @param integer $id article id
2479 function incViewCount( $id ) {
2480 $id = intval( $id );
2481 global $wgHitcounterUpdateFreq, $wgDBtype;
2483 $dbw =& wfGetDB( DB_MASTER
);
2484 $pageTable = $dbw->tableName( 'page' );
2485 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2486 $acchitsTable = $dbw->tableName( 'acchits' );
2488 if( $wgHitcounterUpdateFreq <= 1 ) {
2489 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2493 # Not important enough to warrant an error page in case of failure
2494 $oldignore = $dbw->ignoreErrors( true );
2496 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2498 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2499 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2500 # Most of the time (or on SQL errors), skip row count check
2501 $dbw->ignoreErrors( $oldignore );
2505 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2506 $row = $dbw->fetchObject( $res );
2507 $rown = intval( $row->n
);
2508 if( $rown >= $wgHitcounterUpdateFreq ){
2509 wfProfileIn( 'Article::incViewCount-collect' );
2510 $old_user_abort = ignore_user_abort( true );
2512 if ($wgDBtype == 'mysql')
2513 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2514 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2515 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2516 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2518 $dbw->query("DELETE FROM $hitcounterTable");
2519 if ($wgDBtype == 'mysql') {
2520 $dbw->query('UNLOCK TABLES');
2521 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2522 'WHERE page_id = hc_id');
2525 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2526 "FROM $acchitsTable WHERE page_id = hc_id");
2528 $dbw->query("DROP TABLE $acchitsTable");
2530 ignore_user_abort( $old_user_abort );
2531 wfProfileOut( 'Article::incViewCount-collect' );
2533 $dbw->ignoreErrors( $oldignore );
2537 * The onArticle*() functions are supposed to be a kind of hooks
2538 * which should be called whenever any of the specified actions
2541 * This is a good place to put code to clear caches, for instance.
2543 * This is called on page move and undelete, as well as edit
2545 * @param $title_obj a title object
2548 static function onArticleCreate($title) {
2549 # The talk page isn't in the regular link tables, so we need to update manually:
2550 if ( $title->isTalkPage() ) {
2551 $other = $title->getSubjectPage();
2553 $other = $title->getTalkPage();
2555 $other->invalidateCache();
2556 $other->purgeSquid();
2558 $title->touchLinks();
2559 $title->purgeSquid();
2562 static function onArticleDelete( $title ) {
2563 global $wgUseFileCache, $wgMessageCache;
2565 $title->touchLinks();
2566 $title->purgeSquid();
2569 if ( $wgUseFileCache ) {
2570 $cm = new HTMLFileCache( $title );
2571 @unlink
( $cm->fileCacheName() );
2574 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2575 $wgMessageCache->replace( $title->getDBkey(), false );
2580 * Purge caches on page update etc
2582 static function onArticleEdit( $title ) {
2583 global $wgDeferredUpdateList, $wgUseFileCache;
2585 // Invalidate caches of articles which include this page
2586 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2587 $wgDeferredUpdateList[] = $update;
2589 # Purge squid for this page only
2590 $title->purgeSquid();
2593 if ( $wgUseFileCache ) {
2594 $cm = new HTMLFileCache( $title );
2595 @unlink
( $cm->fileCacheName() );
2602 * Info about this page
2603 * Called for ?action=info when $wgAllowPageInfo is on.
2608 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2610 if ( !$wgAllowPageInfo ) {
2611 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2615 $page = $this->mTitle
->getSubjectPage();
2617 $wgOut->setPagetitle( $page->getPrefixedText() );
2618 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2620 # first, see if the page exists at all.
2621 $exists = $page->getArticleId() != 0;
2623 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2624 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2626 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2629 $dbr =& wfGetDB( DB_SLAVE
);
2631 'wl_title' => $page->getDBkey(),
2632 'wl_namespace' => $page->getNamespace() );
2633 $numwatchers = $dbr->selectField(
2638 $this->getSelectOptions() );
2640 $pageInfo = $this->pageCountInfo( $page );
2641 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2643 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2644 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2646 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2648 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2650 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2652 $wgOut->addHTML( '</ul>' );
2658 * Return the total number of edits and number of unique editors
2659 * on a given page. If page does not exist, returns false.
2661 * @param Title $title
2665 function pageCountInfo( $title ) {
2666 $id = $title->getArticleId();
2671 $dbr =& wfGetDB( DB_SLAVE
);
2673 $rev_clause = array( 'rev_page' => $id );
2675 $edits = $dbr->selectField(
2680 $this->getSelectOptions() );
2682 $authors = $dbr->selectField(
2684 'COUNT(DISTINCT rev_user_text)',
2687 $this->getSelectOptions() );
2689 return array( 'edits' => $edits, 'authors' => $authors );
2693 * Return a list of templates used by this article.
2694 * Uses the templatelinks table
2696 * @return array Array of Title objects
2698 function getUsedTemplates() {
2700 $id = $this->mTitle
->getArticleID();
2705 $dbr =& wfGetDB( DB_SLAVE
);
2706 $res = $dbr->select( array( 'templatelinks' ),
2707 array( 'tl_namespace', 'tl_title' ),
2708 array( 'tl_from' => $id ),
2709 'Article:getUsedTemplates' );
2710 if ( false !== $res ) {
2711 if ( $dbr->numRows( $res ) ) {
2712 while ( $row = $dbr->fetchObject( $res ) ) {
2713 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2717 $dbr->freeResult( $res );
2722 * Return an auto-generated summary if the text provided is a redirect.
2724 * @param string $text The wikitext to check
2725 * @return string '' or an appropriate summary
2727 public static function getRedirectAutosummary( $text ) {
2728 $rt = Title
::newFromRedirect( $text );
2729 if( is_object( $rt ) )
2730 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2736 * Return an auto-generated summary if the new text is much shorter than
2739 * @param string $oldtext The previous text of the page
2740 * @param string $text The submitted text of the page
2741 * @return string An appropriate autosummary, or an empty string.
2743 public static function getBlankingAutosummary( $oldtext, $text ) {
2744 if ($oldtext!='' && $text=='') {
2745 return wfMsgForContent('autosumm-blank');
2746 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2747 #Removing more than 90% of the article
2749 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2750 return wfMsgForContent('autosumm-replace', $truncatedtext);
2757 * Return an applicable autosummary if one exists for the given edit.
2758 * @param string $oldtext The previous text of the page.
2759 * @param string $newtext The submitted text of the page.
2760 * @param bitmask $flags A bitmask of flags submitted for the edit.
2761 * @return string An appropriate autosummary, or an empty string.
2763 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2765 # This code is UGLY UGLY UGLY.
2766 # Somebody PLEASE come up with a more elegant way to do it.
2768 #Redirect autosummaries
2769 $summary = self
::getRedirectAutosummary( $newtext );
2774 #Blanking autosummaries
2775 if (!($flags & EDIT_NEW
))
2776 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
2781 #New page autosummaries
2782 if ($flags & EDIT_NEW
&& strlen($newtext)) {
2783 #If they're making a new article, give its text, truncated, in the summary.
2785 $truncatedtext = $wgContLang->truncate(
2786 str_replace("\n", ' ', $newtext),
2787 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2789 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2799 * Add the primary page-view wikitext to the output buffer
2800 * Saves the text into the parser cache if possible.
2801 * Updates templatelinks if it is out of date.
2803 * @param string $text
2804 * @param bool $cache
2806 public function outputWikiText( $text, $cache = true ) {
2807 global $wgParser, $wgUser, $wgOut;
2809 $popts = $wgOut->parserOptions();
2810 $popts->setTidy(true);
2811 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
2812 $popts, true, true, $this->getRevIdFetched() );
2813 $popts->setTidy(false);
2814 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
2815 $parserCache =& ParserCache
::singleton();
2816 $parserCache->save( $parserOutput, $this, $wgUser );
2819 if ( !wfReadOnly() ) {
2821 # Get templates from templatelinks
2823 $id = $this->mTitle
->getArticleID();
2825 $tlTemplates = array();
2827 $dbr =& wfGetDB( DB_SLAVE
);
2828 $res = $dbr->select( array( 'templatelinks' ),
2829 array( 'tl_namespace', 'tl_title' ),
2830 array( 'tl_from' => $id ),
2831 'Article:getUsedTemplates' );
2835 if ( false !== $res ) {
2836 if ( $dbr->numRows( $res ) ) {
2837 while ( $row = $dbr->fetchObject( $res ) ) {
2838 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
2843 # Get templates from parser output.
2844 $poTemplates_allns = $parserOutput->getTemplates();
2846 $poTemplates = array ();
2847 foreach ( $poTemplates_allns as $ns_templates ) {
2848 $poTemplates = array_merge( $poTemplates, $ns_templates );
2852 $templates_diff = array_diff( $poTemplates, $tlTemplates );
2854 if ( count( $templates_diff ) > 0 ) {
2855 # Whee, link updates time.
2856 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
2858 $dbw =& wfGetDb( DB_MASTER
);
2867 $wgOut->addParserOutput( $parserOutput );