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.
14 * @internal documentation reviewed 15 Mar 2010
21 var $mContentLoaded = false; // !<
22 var $mCounter = -1; // !< Not loaded
23 var $mDataLoaded = false; // !<
24 var $mForUpdate = false; // !<
25 var $mGoodAdjustment = 0; // !<
26 var $mIsRedirect = false; // !<
27 var $mLatest = false; // !<
29 var $mPreparedEdit = false; // !< Title object if set
30 var $mRedirectedFrom = null; // !< Title object if set
31 var $mRedirectTarget = null; // !< Title object if set
32 var $mRedirectUrl = false; // !<
33 var $mRevIdFetched = 0; // !<
34 var $mLastRevision = null; // !< Latest revision if set
35 var $mRevision = null; // !< Loaded revision object if set
36 var $mTimestamp = ''; // !<
37 var $mTitle; // !< Title object
38 var $mTotalAdjustment = 0; // !<
39 var $mTouched = '19700101000000'; // !<
40 var $mParserOptions; // !< ParserOptions object
41 var $mParserOutput; // !< ParserCache object if set
45 * Constructor and clear the article
46 * @param $title Reference to a Title object.
47 * @param $oldId Integer revision ID, null to fetch from request, zero for current
49 public function __construct( Title
$title, $oldId = null ) {
50 // FIXME: does the reference play any role here?
51 $this->mTitle
=& $title;
52 $this->mOldId
= $oldId;
56 * Constructor from an page id
57 * @param $id Int article ID to load
59 public static function newFromID( $id ) {
60 $t = Title
::newFromID( $id );
61 # FIXME: doesn't inherit right
62 return $t == null ?
null : new self( $t );
63 # return $t == null ? null : new static( $t ); // PHP 5.3
67 * Tell the page view functions that this view was redirected
68 * from another page on the wiki.
69 * @param $from Title object.
71 public function setRedirectedFrom( Title
$from ) {
72 $this->mRedirectedFrom
= $from;
76 * If this page is a redirect, get its target
78 * The target will be fetched from the redirect table if possible.
79 * If this page doesn't have an entry there, call insertRedirect()
80 * @return mixed Title object, or null if this page is not a redirect
82 public function getRedirectTarget() {
83 if ( !$this->mTitle
->isRedirect() ) {
87 if ( $this->mRedirectTarget
!== null ) {
88 return $this->mRedirectTarget
;
91 # Query the redirect table
92 $dbr = wfGetDB( DB_SLAVE
);
93 $row = $dbr->selectRow( 'redirect',
94 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
95 array( 'rd_from' => $this->getID() ),
99 // rd_fragment and rd_interwiki were added later, populate them if empty
100 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
101 return $this->mRedirectTarget
= Title
::makeTitle(
102 $row->rd_namespace
, $row->rd_title
,
103 $row->rd_fragment
, $row->rd_interwiki
);
106 # This page doesn't have an entry in the redirect table
107 return $this->mRedirectTarget
= $this->insertRedirect();
111 * Insert an entry for this page into the redirect table.
113 * Don't call this function directly unless you know what you're doing.
114 * @return Title object or null if not a redirect
116 public function insertRedirect() {
117 // recurse through to only get the final target
118 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
122 $this->insertRedirectEntry( $retval );
127 * Insert or update the redirect table entry for this page to indicate
128 * it redirects to $rt .
129 * @param $rt Title redirect target
131 public function insertRedirectEntry( $rt ) {
132 $dbw = wfGetDB( DB_MASTER
);
133 $dbw->replace( 'redirect', array( 'rd_from' ),
135 'rd_from' => $this->getID(),
136 'rd_namespace' => $rt->getNamespace(),
137 'rd_title' => $rt->getDBkey(),
138 'rd_fragment' => $rt->getFragment(),
139 'rd_interwiki' => $rt->getInterwiki(),
146 * Get the Title object or URL this page redirects to
148 * @return mixed false, Title of in-wiki target, or string with URL
150 public function followRedirect() {
151 return $this->getRedirectURL( $this->getRedirectTarget() );
155 * Get the Title object this text redirects to
157 * @param $text string article content containing redirect info
158 * @return mixed false, Title of in-wiki target, or string with URL
159 * @deprecated since 1.17
161 public function followRedirectText( $text ) {
162 // recurse through to only get the final target
163 return $this->getRedirectURL( Title
::newFromRedirectRecurse( $text ) );
167 * Get the Title object or URL to use for a redirect. We use Title
168 * objects for same-wiki, non-special redirects and URLs for everything
170 * @param $rt Title Redirect target
171 * @return mixed false, Title object of local target, or string with URL
173 public function getRedirectURL( $rt ) {
175 if ( $rt->getInterwiki() != '' ) {
176 if ( $rt->isLocal() ) {
177 // Offsite wikis need an HTTP redirect.
179 // This can be hard to reverse and may produce loops,
180 // so they may be disabled in the site configuration.
181 $source = $this->mTitle
->getFullURL( 'redirect=no' );
182 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
185 if ( $rt->getNamespace() == NS_SPECIAL
) {
186 // Gotta handle redirects to special pages differently:
187 // Fill the HTTP response "Location" header and ignore
188 // the rest of the page we're on.
190 // This can be hard to reverse, so they may be disabled.
191 if ( $rt->isSpecial( 'Userlogout' ) ) {
194 return $rt->getFullURL();
202 // No or invalid redirect
207 * Get the title object of the article
208 * @return Title object of this page
210 public function getTitle() {
211 return $this->mTitle
;
216 * FIXME: shouldn't this be public?
219 public function clear() {
220 $this->mDataLoaded
= false;
221 $this->mContentLoaded
= false;
223 $this->mCounter
= -1; # Not loaded
224 $this->mRedirectedFrom
= null; # Title object if set
225 $this->mRedirectTarget
= null; # Title object if set
226 $this->mLastRevision
= null; # Latest revision
227 $this->mTimestamp
= '';
228 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
229 $this->mTouched
= '19700101000000';
230 $this->mForUpdate
= false;
231 $this->mIsRedirect
= false;
232 $this->mRevIdFetched
= 0;
233 $this->mRedirectUrl
= false;
234 $this->mLatest
= false;
235 $this->mPreparedEdit
= false;
239 * Note that getContent/loadContent do not follow redirects anymore.
240 * If you need to fetch redirectable content easily, try
241 * the shortcut in Article::followRedirect()
243 * This function has side effects! Do not use this function if you
244 * only want the real revision text if any.
246 * @return Return the text of this revision
248 public function getContent() {
251 wfProfileIn( __METHOD__
);
253 if ( $this->getID() === 0 ) {
254 # If this is a MediaWiki:x message, then load the messages
255 # and return the message value for x.
256 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
257 $text = $this->mTitle
->getDefaultMessageText();
258 if ( $text === false ) {
262 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
264 wfProfileOut( __METHOD__
);
268 $this->loadContent();
269 wfProfileOut( __METHOD__
);
271 return $this->mContent
;
276 * Get the text of the current revision. No side-effects...
278 * @return Return the text of the current revision
280 public function getRawText() {
281 // Check process cache for current revision
282 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
283 return $this->mContent
;
286 $rev = Revision
::newFromTitle( $this->mTitle
);
287 $text = $rev ?
$rev->getRawText() : false;
293 * This function returns the text of a section, specified by a number ($section).
294 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
295 * the first section before any such heading (section 0).
297 * If a section contains subsections, these are also returned.
299 * @param $text String: text to look in
300 * @param $section Integer: section number
301 * @return string text of the requested section
304 public function getSection( $text, $section ) {
306 return $wgParser->getSection( $text, $section );
310 * Get the text that needs to be saved in order to undo all revisions
311 * between $undo and $undoafter. Revisions must belong to the same page,
312 * must exist and must not be deleted
313 * @param $undo Revision
314 * @param $undoafter Revision Must be an earlier revision than $undo
315 * @return mixed string on success, false on failure
317 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
318 $currentRev = Revision
::newFromTitle( $this->mTitle
);
319 if ( !$currentRev ) {
320 return false; // no page
322 $undo_text = $undo->getText();
323 $undoafter_text = $undoafter->getText();
324 $cur_text = $currentRev->getText();
326 if ( $cur_text == $undo_text ) {
327 # No use doing a merge if it's just a straight revert.
328 return $undoafter_text;
333 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
341 * @return int The oldid of the article that is to be shown, 0 for the
344 public function getOldID() {
345 if ( is_null( $this->mOldId
) ) {
346 $this->mOldId
= $this->getOldIDFromRequest();
349 return $this->mOldId
;
353 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
355 * @return int The old id for the request
357 public function getOldIDFromRequest() {
360 $this->mRedirectUrl
= false;
362 $oldid = $wgRequest->getVal( 'oldid' );
364 if ( isset( $oldid ) ) {
365 $oldid = intval( $oldid );
366 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
367 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
371 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
373 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
374 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
389 * Load the revision (including text) into this object
391 function loadContent() {
392 if ( $this->mContentLoaded
) {
396 wfProfileIn( __METHOD__
);
398 $this->fetchContent( $this->getOldID() );
400 wfProfileOut( __METHOD__
);
404 * Return the list of revision fields that should be selected to create
407 public static function selectFields() {
424 * Fetch a page record with the given conditions
425 * @param $dbr Database object
426 * @param $conditions Array
427 * @return mixed Database result resource, or false on failure
429 protected function pageData( $dbr, $conditions ) {
430 $fields = self
::selectFields();
432 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
434 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
436 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
442 * Fetch a page record matching the Title object's namespace and title
443 * using a sanitized title string
445 * @param $dbr Database object
446 * @param $title Title object
447 * @return mixed Database result resource, or false on failure
449 protected function pageDataFromTitle( $dbr, $title ) {
450 return $this->pageData( $dbr, array(
451 'page_namespace' => $title->getNamespace(),
452 'page_title' => $title->getDBkey() ) );
456 * Fetch a page record matching the requested ID
458 * @param $dbr Database
461 protected function pageDataFromId( $dbr, $id ) {
462 return $this->pageData( $dbr, array( 'page_id' => $id ) );
466 * Set the general counter, title etc data loaded from
469 * @param $data Database row object or "fromdb"
471 public function loadPageData( $data = 'fromdb' ) {
472 if ( $data === 'fromdb' ) {
473 $dbr = wfGetDB( DB_SLAVE
);
474 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
477 $lc = LinkCache
::singleton();
480 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
482 $this->mTitle
->mArticleID
= intval( $data->page_id
);
484 # Old-fashioned restrictions
485 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
487 $this->mCounter
= intval( $data->page_counter
);
488 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
489 $this->mIsRedirect
= intval( $data->page_is_redirect
);
490 $this->mLatest
= intval( $data->page_latest
);
492 $lc->addBadLinkObj( $this->mTitle
);
493 $this->mTitle
->mArticleID
= 0;
496 $this->mDataLoaded
= true;
500 * Get text of an article from database
501 * Does *NOT* follow redirects.
503 * @param $oldid Int: 0 for whatever the latest revision is
504 * @return mixed string containing article contents, or false if null
506 function fetchContent( $oldid = 0 ) {
507 if ( $this->mContentLoaded
) {
508 return $this->mContent
;
511 # Pre-fill content with error message so that if something
512 # fails we'll have something telling us what we intended.
513 $t = $this->mTitle
->getPrefixedText();
514 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
515 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
518 $revision = Revision
::newFromId( $oldid );
519 if ( $revision === null ) {
520 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
524 if ( !$this->mDataLoaded ||
$this->getID() != $revision->getPage() ) {
525 $data = $this->pageDataFromId( wfGetDB( DB_SLAVE
), $revision->getPage() );
528 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
532 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
533 $this->loadPageData( $data );
536 if ( !$this->mDataLoaded
) {
537 $this->loadPageData();
540 if ( $this->mLatest
=== false ) {
541 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
545 $revision = Revision
::newFromId( $this->mLatest
);
546 if ( $revision === null ) {
547 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
552 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
553 // We should instead work with the Revision object when we need it...
554 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
556 if ( $revision->getId() == $this->mLatest
) {
557 $this->setLastEdit( $revision );
560 $this->mRevIdFetched
= $revision->getId();
561 $this->mContentLoaded
= true;
562 $this->mRevision
=& $revision;
564 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) );
566 return $this->mContent
;
570 * Read/write accessor to select FOR UPDATE
572 * @param $x Mixed: FIXME
573 * @return mixed value of $x, or value stored in Article::mForUpdate
575 public function forUpdate( $x = null ) {
576 return wfSetVar( $this->mForUpdate
, $x );
580 * Get options for all SELECT statements
582 * @param $options Array: an optional options array which'll be appended to
584 * @return Array: options
586 protected function getSelectOptions( $options = '' ) {
587 if ( $this->mForUpdate
) {
588 if ( is_array( $options ) ) {
589 $options[] = 'FOR UPDATE';
591 $options = 'FOR UPDATE';
599 * @return int Page ID
601 public function getID() {
602 return $this->mTitle
->getArticleID();
606 * @return bool Whether or not the page exists in the database
608 public function exists() {
609 return $this->getId() > 0;
613 * Check if this page is something we're going to be showing
614 * some sort of sensible content for. If we return false, page
615 * views (plain action=view) will return an HTTP 404 response,
616 * so spiders and robots can know they're following a bad link.
620 public function hasViewableContent() {
621 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
625 * @return int The view count for the page
627 public function getCount() {
628 if ( -1 == $this->mCounter
) {
629 $id = $this->getID();
634 $dbr = wfGetDB( DB_SLAVE
);
635 $this->mCounter
= $dbr->selectField( 'page',
637 array( 'page_id' => $id ),
639 $this->getSelectOptions()
644 return $this->mCounter
;
648 * Determine whether a page would be suitable for being counted as an
649 * article in the site_stats table based on the title & its content
651 * @param $text String: text to analyze
654 public function isCountable( $text ) {
655 global $wgUseCommaCount;
657 $token = $wgUseCommaCount ?
',' : '[[';
659 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
663 * Tests if the article text represents a redirect
665 * @param $text mixed string containing article contents, or boolean
668 public function isRedirect( $text = false ) {
669 if ( $text === false ) {
670 if ( !$this->mDataLoaded
) {
671 $this->loadPageData();
674 return (bool)$this->mIsRedirect
;
676 return Title
::newFromRedirect( $text ) !== null;
681 * Returns true if the currently-referenced revision is the current edit
682 * to this page (and it exists).
685 public function isCurrent() {
686 # If no oldid, this is the current version.
687 if ( $this->getOldID() == 0 ) {
691 return $this->exists() && $this->mRevision
&& $this->mRevision
->isCurrent();
695 * Loads everything except the text
696 * This isn't necessary for all uses, so it's only done if needed.
698 protected function loadLastEdit() {
699 if ( $this->mLastRevision
!== null ) {
700 return; // already loaded
703 # New or non-existent articles have no user information
704 $id = $this->getID();
709 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
711 $this->setLastEdit( $revision );
716 * Set the latest revision
718 protected function setLastEdit( Revision
$revision ) {
719 $this->mLastRevision
= $revision;
720 $this->mTimestamp
= $revision->getTimestamp();
724 * @return string GMT timestamp of last article revision
726 public function getTimestamp() {
727 // Check if the field has been filled by ParserCache::get()
728 if ( !$this->mTimestamp
) {
729 $this->loadLastEdit();
731 return wfTimestamp( TS_MW
, $this->mTimestamp
);
735 * @param $audience Integer: one of:
736 * Revision::FOR_PUBLIC to be displayed to all users
737 * Revision::FOR_THIS_USER to be displayed to $wgUser
738 * Revision::RAW get the text regardless of permissions
739 * @return int user ID for the user that made the last article revision
741 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
742 $this->loadLastEdit();
743 if ( $this->mLastRevision
) {
744 return $this->mLastRevision
->getUser( $audience );
751 * @param $audience Integer: one of:
752 * Revision::FOR_PUBLIC to be displayed to all users
753 * Revision::FOR_THIS_USER to be displayed to $wgUser
754 * Revision::RAW get the text regardless of permissions
755 * @return string username of the user that made the last article revision
757 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
758 $this->loadLastEdit();
759 if ( $this->mLastRevision
) {
760 return $this->mLastRevision
->getUserText( $audience );
767 * @param $audience Integer: one of:
768 * Revision::FOR_PUBLIC to be displayed to all users
769 * Revision::FOR_THIS_USER to be displayed to $wgUser
770 * Revision::RAW get the text regardless of permissions
771 * @return string Comment stored for the last article revision
773 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
774 $this->loadLastEdit();
775 if ( $this->mLastRevision
) {
776 return $this->mLastRevision
->getComment( $audience );
783 * Returns true if last revision was marked as "minor edit"
785 * @return boolean Minor edit indicator for the last article revision.
787 public function getMinorEdit() {
788 $this->loadLastEdit();
789 if ( $this->mLastRevision
) {
790 return $this->mLastRevision
->isMinor();
797 * Use this to fetch the rev ID used on page views
799 * @return int revision ID of last article revision
801 public function getRevIdFetched() {
802 if ( $this->mRevIdFetched
) {
803 return $this->mRevIdFetched
;
805 return $this->getLatest();
810 * Get a list of users who have edited this article, not including the user who made
811 * the most recent revision, which you can get from $article->getUser() if you want it
814 public function getContributors() {
815 # FIXME: this is expensive; cache this info somewhere.
817 $dbr = wfGetDB( DB_SLAVE
);
818 $userTable = $dbr->tableName( 'user' );
820 $tables = array( 'revision', 'user' );
824 'rev_user_text AS user_name',
825 'MAX(rev_timestamp) AS timestamp',
828 $conds = array( 'rev_page' => $this->getId() );
830 // The user who made the top revision gets credited as "this page was last edited by
831 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
832 $user = $this->getUser();
834 $conds[] = "rev_user != $user";
836 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
839 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
842 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
846 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
847 'ORDER BY' => 'timestamp DESC',
850 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
851 return new UserArrayFromResult( $res );
855 * This is the default action of the index.php entry point: just view the
856 * page of the given title.
858 public function view() {
859 global $wgUser, $wgOut, $wgRequest, $wgParser;
860 global $wgUseFileCache, $wgUseETag;
862 wfProfileIn( __METHOD__
);
864 # Get variables from query string
865 $oldid = $this->getOldID();
867 # getOldID may want us to redirect somewhere else
868 if ( $this->mRedirectUrl
) {
869 $wgOut->redirect( $this->mRedirectUrl
);
870 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
871 wfProfileOut( __METHOD__
);
876 $wgOut->setArticleFlag( true );
877 # Set page title (may be overridden by DISPLAYTITLE)
878 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
880 # If we got diff in the query, we want to see a diff page instead of the article.
881 if ( $wgRequest->getCheck( 'diff' ) ) {
882 wfDebug( __METHOD__
. ": showing diff page\n" );
883 $this->showDiffPage();
884 wfProfileOut( __METHOD__
);
889 # Allow frames by default
890 $wgOut->allowClickjacking();
892 $parserCache = ParserCache
::singleton();
894 $parserOptions = $this->getParserOptions();
895 # Render printable version, use printable version cache
896 if ( $wgOut->isPrintable() ) {
897 $parserOptions->setIsPrintable( true );
898 $parserOptions->setEditSection( false );
899 } else if ( $wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
900 $parserOptions->setEditSection( false );
903 # Try client and file cache
904 if ( $oldid === 0 && $this->checkTouched() ) {
906 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
909 # Is it client cached?
910 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
911 wfDebug( __METHOD__
. ": done 304\n" );
912 wfProfileOut( __METHOD__
);
916 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
917 wfDebug( __METHOD__
. ": done file cache\n" );
918 # tell wgOut that output is taken care of
920 $this->viewUpdates();
921 wfProfileOut( __METHOD__
);
927 if ( !$wgUseETag && !$this->mTitle
->quickUserCan( 'edit' ) ) {
928 $parserOptions->setEditSection( false );
931 # Should the parser cache be used?
932 $useParserCache = $this->useParserCache( $oldid );
933 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
934 if ( $wgUser->getStubThreshold() ) {
935 wfIncrStats( 'pcache_miss_stub' );
938 $wasRedirected = $this->showRedirectedFromHeader();
939 $this->showNamespaceHeader();
941 # Iterate through the possible ways of constructing the output text.
942 # Keep going until $outputDone is set, or we run out of things to do.
945 $this->mParserOutput
= false;
947 while ( !$outputDone && ++
$pass ) {
950 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
953 # Try the parser cache
954 if ( $useParserCache ) {
955 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
957 if ( $this->mParserOutput
!== false ) {
958 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
959 $wgOut->addParserOutput( $this->mParserOutput
);
960 # Ensure that UI elements requiring revision ID have
961 # the correct version information.
962 $wgOut->setRevisionId( $this->mLatest
);
968 $text = $this->getContent();
969 if ( $text === false ||
$this->getID() == 0 ) {
970 wfDebug( __METHOD__
. ": showing missing article\n" );
971 $this->showMissingArticle();
972 wfProfileOut( __METHOD__
);
976 # Another whitelist check in case oldid is altering the title
977 if ( !$this->mTitle
->userCanRead() ) {
978 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
979 $wgOut->loginToUse();
982 wfProfileOut( __METHOD__
);
986 # Are we looking at an old revision
987 if ( $oldid && !is_null( $this->mRevision
) ) {
988 $this->setOldSubtitle( $oldid );
990 if ( !$this->showDeletedRevisionHeader() ) {
991 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
992 wfProfileOut( __METHOD__
);
996 # If this "old" version is the current, then try the parser cache...
997 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
998 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
999 if ( $this->mParserOutput
) {
1000 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
1001 $wgOut->addParserOutput( $this->mParserOutput
);
1002 $wgOut->setRevisionId( $this->mLatest
);
1009 # Ensure that UI elements requiring revision ID have
1010 # the correct version information.
1011 $wgOut->setRevisionId( $this->getRevIdFetched() );
1013 # Pages containing custom CSS or JavaScript get special treatment
1014 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
1015 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
1016 $this->showCssOrJsPage();
1019 $rt = Title
::newFromRedirectArray( $text );
1021 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
1022 # Viewing a redirect page (e.g. with parameter redirect=no)
1023 # Don't append the subtitle if this was an old revision
1024 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
1025 # Parse just to get categories, displaytitle, etc.
1026 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
1027 $wgOut->addParserOutputNoText( $this->mParserOutput
);
1033 # Run the parse, protected by a pool counter
1034 wfDebug( __METHOD__
. ": doing uncached parse\n" );
1036 $key = $parserCache->getKey( $this, $parserOptions );
1037 $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1039 if ( !$poolArticleView->execute() ) {
1040 # Connection or timeout error
1041 wfProfileOut( __METHOD__
);
1047 # Should be unreachable, but just in case...
1053 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1054 if ( $this->mParserOutput
) {
1055 $titleText = $this->mParserOutput
->getTitleText();
1057 if ( strval( $titleText ) !== '' ) {
1058 $wgOut->setPageTitle( $titleText );
1062 # For the main page, overwrite the <title> element with the con-
1063 # tents of 'pagetitle-view-mainpage' instead of the default (if
1064 # that's not empty).
1065 # This message always exists because it is in the i18n files
1066 if ( $this->mTitle
->equals( Title
::newMainPage() ) ) {
1067 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
1068 if ( !$msg->isDisabled() ) {
1069 $wgOut->setHTMLTitle( $msg->title( $this->mTitle
)->text() );
1073 # Now that we've filled $this->mParserOutput, we know whether
1074 # there are any __NOINDEX__ tags on the page
1075 $policy = $this->getRobotPolicy( 'view' );
1076 $wgOut->setIndexPolicy( $policy['index'] );
1077 $wgOut->setFollowPolicy( $policy['follow'] );
1079 $this->showViewFooter();
1080 $this->viewUpdates();
1081 wfProfileOut( __METHOD__
);
1085 * Show a diff page according to current request variables. For use within
1086 * Article::view() only, other callers should use the DifferenceEngine class.
1088 public function showDiffPage() {
1089 global $wgRequest, $wgUser;
1091 $diff = $wgRequest->getVal( 'diff' );
1092 $rcid = $wgRequest->getVal( 'rcid' );
1093 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1094 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1095 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1096 $oldid = $this->getOldID();
1098 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
1099 // DifferenceEngine directly fetched the revision:
1100 $this->mRevIdFetched
= $de->mNewid
;
1101 $de->showDiffPage( $diffOnly );
1103 if ( $diff == 0 ||
$diff == $this->getLatest() ) {
1104 # Run view updates for current revision only
1105 $this->viewUpdates();
1110 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1111 * Article::view() only.
1113 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1116 protected function showCssOrJsPage() {
1119 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1121 // Give hooks a chance to customise the output
1122 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
1123 // Wrap the whole lot in a <pre> and don't parse
1125 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
1126 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1127 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
1128 $wgOut->addHTML( "\n</pre>\n" );
1133 * Get the robot policy to be used for the current view
1134 * @param $action String the action= GET parameter
1135 * @return Array the policy that should be set
1136 * TODO: actions other than 'view'
1138 public function getRobotPolicy( $action ) {
1139 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1140 global $wgDefaultRobotPolicy, $wgRequest;
1142 $ns = $this->mTitle
->getNamespace();
1144 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1145 # Don't index user and user talk pages for blocked users (bug 11443)
1146 if ( !$this->mTitle
->isSubpage() ) {
1147 if ( Block
::newFromTarget( null, $this->mTitle
->getText() ) instanceof Block
) {
1149 'index' => 'noindex',
1150 'follow' => 'nofollow'
1156 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1157 # Non-articles (special pages etc), and old revisions
1159 'index' => 'noindex',
1160 'follow' => 'nofollow'
1162 } elseif ( $wgOut->isPrintable() ) {
1163 # Discourage indexing of printable versions, but encourage following
1165 'index' => 'noindex',
1166 'follow' => 'follow'
1168 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1169 # For ?curid=x urls, disallow indexing
1171 'index' => 'noindex',
1172 'follow' => 'follow'
1176 # Otherwise, construct the policy based on the various config variables.
1177 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1179 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1180 # Honour customised robot policies for this namespace
1181 $policy = array_merge(
1183 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1186 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1187 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1188 # a final sanity check that we have really got the parser output.
1189 $policy = array_merge(
1191 array( 'index' => $this->mParserOutput
->getIndexPolicy() )
1195 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1196 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1197 $policy = array_merge(
1199 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] )
1207 * Converts a String robot policy into an associative array, to allow
1208 * merging of several policies using array_merge().
1209 * @param $policy Mixed, returns empty array on null/false/'', transparent
1210 * to already-converted arrays, converts String.
1211 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1213 public static function formatRobotPolicy( $policy ) {
1214 if ( is_array( $policy ) ) {
1216 } elseif ( !$policy ) {
1220 $policy = explode( ',', $policy );
1221 $policy = array_map( 'trim', $policy );
1224 foreach ( $policy as $var ) {
1225 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1226 $arr['index'] = $var;
1227 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1228 $arr['follow'] = $var;
1236 * If this request is a redirect view, send "redirected from" subtitle to
1237 * $wgOut. Returns true if the header was needed, false if this is not a
1238 * redirect view. Handles both local and remote redirects.
1242 public function showRedirectedFromHeader() {
1243 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1245 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1247 if ( isset( $this->mRedirectedFrom
) ) {
1248 // This is an internally redirected page view.
1249 // We'll need a backlink to the source page for navigation.
1250 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1251 $redir = $wgUser->getSkin()->link(
1252 $this->mRedirectedFrom
,
1255 array( 'redirect' => 'no' ),
1256 array( 'known', 'noclasses' )
1259 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1260 $wgOut->setSubtitle( $s );
1262 // Set the fragment if one was specified in the redirect
1263 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1264 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1265 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1268 // Add a <link rel="canonical"> tag
1269 $wgOut->addLink( array( 'rel' => 'canonical',
1270 'href' => $this->mTitle
->getLocalURL() )
1275 } elseif ( $rdfrom ) {
1276 // This is an externally redirected view, from some other wiki.
1277 // If it was reported from a trusted site, supply a backlink.
1278 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1279 $redir = $wgUser->getSkin()->makeExternalLink( $rdfrom, $rdfrom );
1280 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1281 $wgOut->setSubtitle( $s );
1291 * Show a header specific to the namespace currently being viewed, like
1292 * [[MediaWiki:Talkpagetext]]. For Article::view().
1294 public function showNamespaceHeader() {
1297 if ( $this->mTitle
->isTalkPage() ) {
1298 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
1299 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1305 * Show the footer section of an ordinary page view
1307 public function showViewFooter() {
1308 global $wgOut, $wgUseTrackbacks;
1310 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1311 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1312 $wgOut->addWikiMsg( 'anontalkpagetext' );
1315 # If we have been passed an &rcid= parameter, we want to give the user a
1316 # chance to mark this new article as patrolled.
1317 $this->showPatrolFooter();
1320 if ( $wgUseTrackbacks ) {
1321 $this->addTrackbacks();
1324 wfRunHooks( 'ArticleViewFooter', array( $this ) );
1329 * If patrol is possible, output a patrol UI box. This is called from the
1330 * footer section of ordinary page views. If patrol is not possible or not
1331 * desired, does nothing.
1333 public function showPatrolFooter() {
1334 global $wgOut, $wgRequest, $wgUser;
1336 $rcid = $wgRequest->getVal( 'rcid' );
1338 if ( !$rcid ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1342 $sk = $wgUser->getSkin();
1343 $token = $wgUser->editToken( $rcid );
1344 $wgOut->preventClickjacking();
1347 "<div class='patrollink'>" .
1349 'markaspatrolledlink',
1352 wfMsgHtml( 'markaspatrolledtext' ),
1355 'action' => 'markpatrolled',
1359 array( 'known', 'noclasses' )
1367 * Show the error text for a missing article. For articles in the MediaWiki
1368 * namespace, show the default message text. To be called from Article::view().
1370 public function showMissingArticle() {
1371 global $wgOut, $wgRequest, $wgUser;
1373 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1374 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1375 $parts = explode( '/', $this->mTitle
->getText() );
1376 $rootPart = $parts[0];
1377 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1378 $ip = User
::isIP( $rootPart );
1380 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1381 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1382 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1383 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1384 LogEventsList
::showLogExtract(
1387 $user->getUserPage()->getPrefixedText(),
1391 'showIfEmpty' => false,
1393 'blocked-notice-logextract',
1394 $user->getName() # Support GENDER in notice
1401 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1403 # Show delete and move logs
1404 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1406 'conds' => array( "log_action != 'revision'" ),
1407 'showIfEmpty' => false,
1408 'msgKey' => array( 'moveddeleted-notice' ) )
1411 # Show error message
1412 $oldid = $this->getOldID();
1414 $text = wfMsgNoTrans( 'missing-article',
1415 $this->mTitle
->getPrefixedText(),
1416 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1417 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1418 // Use the default message text
1419 $text = $this->mTitle
->getDefaultMessageText();
1421 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1422 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1423 $errors = array_merge( $createErrors, $editErrors );
1425 if ( !count( $errors ) ) {
1426 $text = wfMsgNoTrans( 'noarticletext' );
1428 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1431 $text = "<div class='noarticletext'>\n$text\n</div>";
1433 if ( !$this->hasViewableContent() ) {
1434 // If there's no backing content, send a 404 Not Found
1435 // for better machine handling of broken links.
1436 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1439 $wgOut->addWikiText( $text );
1443 * If the revision requested for view is deleted, check permissions.
1444 * Send either an error message or a warning header to $wgOut.
1446 * @return boolean true if the view is allowed, false if not.
1448 public function showDeletedRevisionHeader() {
1449 global $wgOut, $wgRequest;
1451 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1456 // If the user is not allowed to see it...
1457 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1458 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1459 'rev-deleted-text-permission' );
1462 // If the user needs to confirm that they want to see it...
1463 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1464 # Give explanation and add a link to view the revision...
1465 $oldid = intval( $this->getOldID() );
1466 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1467 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1468 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1469 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1470 array( $msg, $link ) );
1473 // We are allowed to see...
1475 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1476 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1477 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1484 * Should the parser cache be used?
1488 public function useParserCache( $oldid ) {
1489 global $wgUser, $wgEnableParserCache;
1491 return $wgEnableParserCache
1492 && $wgUser->getStubThreshold() == 0
1495 && !$this->mTitle
->isCssOrJsPage()
1496 && !$this->mTitle
->isCssJsSubpage();
1500 * Execute the uncached parse for action=view
1502 public function doViewParse() {
1505 $oldid = $this->getOldID();
1506 $parserOptions = $this->getParserOptions();
1508 # Render printable version, use printable version cache
1509 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1511 # Don't show section-edit links on old revisions... this way lies madness.
1512 if ( !$this->isCurrent() ||
$wgOut->isPrintable() ||
!$this->mTitle
->quickUserCan( 'edit' ) ) {
1513 $parserOptions->setEditSection( false );
1516 $useParserCache = $this->useParserCache( $oldid );
1517 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1523 * Try to fetch an expired entry from the parser cache. If it is present,
1524 * output it and return true. If it is not present, output nothing and
1525 * return false. This is used as a callback function for
1526 * PoolCounter::executeProtected().
1530 public function tryDirtyCache() {
1532 $parserCache = ParserCache
::singleton();
1533 $options = $this->getParserOptions();
1535 if ( $wgOut->isPrintable() ) {
1536 $options->setIsPrintable( true );
1537 $options->setEditSection( false );
1540 $output = $parserCache->getDirty( $this, $options );
1543 wfDebug( __METHOD__
. ": sending dirty output\n" );
1544 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1545 $wgOut->setSquidMaxage( 0 );
1546 $this->mParserOutput
= $output;
1547 $wgOut->addParserOutput( $output );
1548 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1552 wfDebugLog( 'dirty', "dirty missing\n" );
1553 wfDebug( __METHOD__
. ": no dirty cache\n" );
1562 * @param $target Title|Array of destination(s) to redirect
1563 * @param $appendSubtitle Boolean [optional]
1564 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1565 * @return string containing HMTL with redirect link
1567 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1568 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1570 if ( !is_array( $target ) ) {
1571 $target = array( $target );
1574 $imageDir = $wgContLang->getDir();
1576 if ( $appendSubtitle ) {
1577 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1580 $sk = $wgUser->getSkin();
1581 // the loop prepends the arrow image before the link, so the first case needs to be outside
1582 $title = array_shift( $target );
1584 if ( $forceKnown ) {
1585 $link = $sk->linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1587 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1590 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1591 $alt = $wgContLang->isRTL() ?
'←' : '→';
1592 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1593 foreach ( $target as $rt ) {
1594 $link .= Html
::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1595 if ( $forceKnown ) {
1596 $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1598 $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1602 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1603 return '<div class="redirectMsg">' .
1604 Html
::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1605 '<span class="redirectText">' . $link . '</span></div>';
1609 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1611 public function addTrackbacks() {
1614 $dbr = wfGetDB( DB_SLAVE
);
1615 $tbs = $dbr->select( 'trackbacks',
1616 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1617 array( 'tb_page' => $this->getID() )
1620 if ( !$dbr->numRows( $tbs ) ) {
1624 $wgOut->preventClickjacking();
1627 foreach ( $tbs as $o ) {
1630 if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
1631 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1632 $o->tb_id
. "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
1633 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1637 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1645 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1649 * Removes trackback record for current article from trackbacks table
1651 public function deletetrackback() {
1652 global $wgRequest, $wgOut;
1654 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1655 $wgOut->addWikiMsg( 'sessionfailure' );
1660 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
1662 if ( count( $permission_errors ) ) {
1663 $wgOut->showPermissionsErrorPage( $permission_errors );
1668 $db = wfGetDB( DB_MASTER
);
1669 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1671 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1672 $this->mTitle
->invalidateCache();
1676 * Handle action=render
1679 public function render() {
1682 $wgOut->setArticleBodyOnly( true );
1687 * Handle action=purge
1689 public function purge() {
1690 global $wgRequest, $wgOut;
1692 if ( $wgOut->getUser()->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1693 //FIXME: shouldn't this be in doPurge()?
1694 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1699 $formParams = array(
1701 'action' => $wgRequest->getRequestURL(),
1704 $wgOut->addWikiMsg( 'confirm-purge-top' );
1706 $form = Html
::openElement( 'form', $formParams );
1707 $form .= Xml
::submitButton( wfMsg( 'confirm_purge_button' ) );
1708 $form .= Html
::closeElement( 'form' );
1710 $wgOut->addHTML( $form );
1711 $wgOut->addWikiMsg( 'confirm-purge-bottom' );
1713 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1714 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1719 * Perform the actions of a page purging
1721 public function doPurge() {
1724 // Invalidate the cache
1725 $this->mTitle
->invalidateCache();
1728 if ( $wgUseSquid ) {
1729 // Commit the transaction before the purge is sent
1730 $dbw = wfGetDB( DB_MASTER
);
1734 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1735 $update->doUpdate();
1738 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1739 if ( $this->getID() == 0 ) {
1742 $text = $this->getRawText();
1745 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1750 * Insert a new empty page record for this article.
1751 * This *must* be followed up by creating a revision
1752 * and running $this->updateRevisionOn( ... );
1753 * or else the record will be left in a funky state.
1754 * Best if all done inside a transaction.
1756 * @param $dbw Database
1757 * @return int The newly created page_id key, or false if the title already existed
1760 public function insertOn( $dbw ) {
1761 wfProfileIn( __METHOD__
);
1763 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1764 $dbw->insert( 'page', array(
1765 'page_id' => $page_id,
1766 'page_namespace' => $this->mTitle
->getNamespace(),
1767 'page_title' => $this->mTitle
->getDBkey(),
1768 'page_counter' => 0,
1769 'page_restrictions' => '',
1770 'page_is_redirect' => 0, # Will set this shortly...
1772 'page_random' => wfRandom(),
1773 'page_touched' => $dbw->timestamp(),
1774 'page_latest' => 0, # Fill this in shortly...
1775 'page_len' => 0, # Fill this in shortly...
1776 ), __METHOD__
, 'IGNORE' );
1778 $affected = $dbw->affectedRows();
1781 $newid = $dbw->insertId();
1782 $this->mTitle
->resetArticleID( $newid );
1784 wfProfileOut( __METHOD__
);
1786 return $affected ?
$newid : false;
1790 * Update the page record to point to a newly saved revision.
1792 * @param $dbw DatabaseBase: object
1793 * @param $revision Revision: For ID number, and text used to set
1794 length and redirect status fields
1795 * @param $lastRevision Integer: if given, will not overwrite the page field
1796 * when different from the currently set value.
1797 * Giving 0 indicates the new page flag should be set
1799 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1800 * removing rows in redirect table.
1801 * @param $setNewFlag Boolean: Set to true if a page flag should be set
1802 * Needed when $lastRevision has to be set to sth. !=0
1803 * @return bool true on success, false on failure
1806 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
1807 wfProfileIn( __METHOD__
);
1809 $text = $revision->getText();
1810 $rt = Title
::newFromRedirectRecurse( $text );
1812 $conditions = array( 'page_id' => $this->getId() );
1814 if ( !is_null( $lastRevision ) ) {
1815 # An extra check against threads stepping on each other
1816 $conditions['page_latest'] = $lastRevision;
1819 if ( !$setNewFlag ) {
1820 $setNewFlag = ( $lastRevision === 0 );
1823 $dbw->update( 'page',
1825 'page_latest' => $revision->getId(),
1826 'page_touched' => $dbw->timestamp(),
1827 'page_is_new' => $setNewFlag,
1828 'page_is_redirect' => $rt !== null ?
1 : 0,
1829 'page_len' => strlen( $text ),
1834 $result = $dbw->affectedRows() != 0;
1836 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1839 wfProfileOut( __METHOD__
);
1844 * Add row to the redirect table if this is a redirect, remove otherwise.
1846 * @param $dbw Database
1847 * @param $redirectTitle Title object pointing to the redirect target,
1848 * or NULL if this is not a redirect
1849 * @param $lastRevIsRedirect If given, will optimize adding and
1850 * removing rows in redirect table.
1851 * @return bool true on success, false on failure
1854 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1855 // Always update redirects (target link might have changed)
1856 // Update/Insert if we don't know if the last revision was a redirect or not
1857 // Delete if changing from redirect to non-redirect
1858 $isRedirect = !is_null( $redirectTitle );
1860 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1864 wfProfileIn( __METHOD__
);
1865 if ( $isRedirect ) {
1866 $this->insertRedirectEntry( $redirectTitle );
1868 // This is not a redirect, remove row from redirect table
1869 $where = array( 'rd_from' => $this->getId() );
1870 $dbw->delete( 'redirect', $where, __METHOD__
);
1873 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1874 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1876 wfProfileOut( __METHOD__
);
1878 return ( $dbw->affectedRows() != 0 );
1882 * If the given revision is newer than the currently set page_latest,
1883 * update the page record. Otherwise, do nothing.
1885 * @param $dbw Database object
1886 * @param $revision Revision object
1889 public function updateIfNewerOn( &$dbw, $revision ) {
1890 wfProfileIn( __METHOD__
);
1892 $row = $dbw->selectRow(
1893 array( 'revision', 'page' ),
1894 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1896 'page_id' => $this->getId(),
1897 'page_latest=rev_id' ),
1901 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1902 wfProfileOut( __METHOD__
);
1905 $prev = $row->rev_id
;
1906 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1908 # No or missing previous revision; mark the page as new
1910 $lastRevIsRedirect = null;
1913 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1915 wfProfileOut( __METHOD__
);
1920 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1921 * @param $text String: new text of the section
1922 * @param $summary String: new section's subject, only if $section is 'new'
1923 * @param $edittime String: revision timestamp or null to use the current revision
1924 * @return string Complete article text, or null if error
1926 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1927 wfProfileIn( __METHOD__
);
1929 if ( strval( $section ) == '' ) {
1930 // Whole-page edit; let the whole text through
1932 if ( is_null( $edittime ) ) {
1933 $rev = Revision
::newFromTitle( $this->mTitle
);
1935 $dbw = wfGetDB( DB_MASTER
);
1936 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1940 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1941 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1942 wfProfileOut( __METHOD__
);
1946 $oldtext = $rev->getText();
1948 if ( $section == 'new' ) {
1949 # Inserting a new section
1950 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1951 $text = strlen( trim( $oldtext ) ) > 0
1952 ?
"{$oldtext}\n\n{$subject}{$text}"
1953 : "{$subject}{$text}";
1955 # Replacing an existing section; roll out the big guns
1958 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1962 wfProfileOut( __METHOD__
);
1967 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1969 * @return Int updated $flags
1971 function checkFlags( $flags ) {
1972 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1973 if ( $this->mTitle
->getArticleID() ) {
1974 $flags |
= EDIT_UPDATE
;
1986 * Change an existing article or create a new article. Updates RC and all necessary caches,
1987 * optionally via the deferred update array.
1989 * $wgUser must be set before calling this function.
1991 * @param $text String: new text
1992 * @param $summary String: edit summary
1993 * @param $flags Integer bitfield:
1995 * Article is known or assumed to be non-existent, create a new one
1997 * Article is known or assumed to be pre-existing, update it
1999 * Mark this edit minor, if the user is allowed to do so
2001 * Do not log the change in recentchanges
2003 * Mark the edit a "bot" edit regardless of user rights
2004 * EDIT_DEFER_UPDATES
2005 * Defer some of the updates until the end of index.php
2007 * Fill in blank summaries with generated text where possible
2009 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2010 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2011 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2012 * edit-already-exists error will be returned. These two conditions are also possible with
2013 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2015 * @param $baseRevId the revision ID this edit was based off, if any
2016 * @param $user User (optional), $wgUser will be used if not passed
2018 * @return Status object. Possible errors:
2019 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2020 * edit-gone-missing: In update mode, but the article didn't exist
2021 * edit-conflict: In update mode, the article changed unexpectedly
2022 * edit-no-change: Warning that the text was the same as before
2023 * edit-already-exists: In creation mode, but the article already exists
2025 * Extensions may define additional errors.
2027 * $return->value will contain an associative array with members as follows:
2028 * new: Boolean indicating if the function attempted to create a new article
2029 * revision: The revision object for the inserted revision, or null
2031 * Compatibility note: this function previously returned a boolean value indicating success/failure
2033 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2034 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2036 # Low-level sanity check
2037 if ( $this->mTitle
->getText() === '' ) {
2038 throw new MWException( 'Something is trying to edit an article with an empty title' );
2041 wfProfileIn( __METHOD__
);
2043 $user = is_null( $user ) ?
$wgUser : $user;
2044 $status = Status
::newGood( array() );
2046 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2047 $this->loadPageData();
2049 $flags = $this->checkFlags( $flags );
2051 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2052 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
2054 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
2056 if ( $status->isOK() ) {
2057 $status->fatal( 'edit-hook-aborted' );
2060 wfProfileOut( __METHOD__
);
2064 # Silently ignore EDIT_MINOR if not allowed
2065 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
2066 $bot = $flags & EDIT_FORCE_BOT
;
2068 $oldtext = $this->getRawText(); // current revision
2069 $oldsize = strlen( $oldtext );
2071 # Provide autosummaries if one is not provided and autosummaries are enabled.
2072 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
2073 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2076 $editInfo = $this->prepareTextForEdit( $text, null, $user );
2077 $text = $editInfo->pst
;
2078 $newsize = strlen( $text );
2080 $dbw = wfGetDB( DB_MASTER
);
2081 $now = wfTimestampNow();
2082 $this->mTimestamp
= $now;
2084 if ( $flags & EDIT_UPDATE
) {
2085 # Update article, but only if changed.
2086 $status->value
['new'] = false;
2088 # Make sure the revision is either completely inserted or not inserted at all
2089 if ( !$wgDBtransactions ) {
2090 $userAbort = ignore_user_abort( true );
2093 $changed = ( strcmp( $text, $oldtext ) != 0 );
2096 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
2097 - (int)$this->isCountable( $oldtext );
2098 $this->mTotalAdjustment
= 0;
2100 if ( !$this->mLatest
) {
2101 # Article gone missing
2102 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
2103 $status->fatal( 'edit-gone-missing' );
2105 wfProfileOut( __METHOD__
);
2109 $revision = new Revision( array(
2110 'page' => $this->getId(),
2111 'comment' => $summary,
2112 'minor_edit' => $isminor,
2114 'parent_id' => $this->mLatest
,
2115 'user' => $user->getId(),
2116 'user_text' => $user->getName(),
2121 $revisionId = $revision->insertOn( $dbw );
2125 # Note that we use $this->mLatest instead of fetching a value from the master DB
2126 # during the course of this function. This makes sure that EditPage can detect
2127 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2128 # before this function is called. A previous function used a separate query, this
2129 # creates a window where concurrent edits can cause an ignored edit conflict.
2130 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
2133 /* Belated edit conflict! Run away!! */
2134 $status->fatal( 'edit-conflict' );
2136 # Delete the invalid revision if the DB is not transactional
2137 if ( !$wgDBtransactions ) {
2138 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
2144 global $wgUseRCPatrol;
2145 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2146 # Update recentchanges
2147 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2148 # Mark as patrolled if the user can do so
2149 $patrolled = $wgUseRCPatrol && !count(
2150 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2151 # Add RC row to the DB
2152 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
2153 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2154 $revisionId, $patrolled
2157 # Log auto-patrolled edits
2159 PatrolLog
::record( $rc, true );
2162 $user->incEditCount();
2166 $status->warning( 'edit-no-change' );
2168 // Keep the same revision ID, but do some updates on it
2169 $revisionId = $this->getLatest();
2170 // Update page_touched, this is usually implicit in the page update
2171 // Other cache updates are done in onArticleEdit()
2172 $this->mTitle
->invalidateCache();
2175 if ( !$wgDBtransactions ) {
2176 ignore_user_abort( $userAbort );
2179 // Now that ignore_user_abort is restored, we can respond to fatal errors
2180 if ( !$status->isOK() ) {
2181 wfProfileOut( __METHOD__
);
2185 # Invalidate cache of this article and all pages using this article
2186 # as a template. Partly deferred.
2187 Article
::onArticleEdit( $this->mTitle
);
2188 # Update links tables, site stats, etc.
2189 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
2191 # Create new article
2192 $status->value
['new'] = true;
2194 # Set statistics members
2195 # We work out if it's countable after PST to avoid counter drift
2196 # when articles are created with {{subst:}}
2197 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2198 $this->mTotalAdjustment
= 1;
2202 # Add the page record; stake our claim on this title!
2203 # This will return false if the article already exists
2204 $newid = $this->insertOn( $dbw );
2206 if ( $newid === false ) {
2208 $status->fatal( 'edit-already-exists' );
2210 wfProfileOut( __METHOD__
);
2214 # Save the revision text...
2215 $revision = new Revision( array(
2217 'comment' => $summary,
2218 'minor_edit' => $isminor,
2220 'user' => $user->getId(),
2221 'user_text' => $user->getName(),
2224 $revisionId = $revision->insertOn( $dbw );
2226 $this->mTitle
->resetArticleID( $newid );
2227 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached (FIXME?)
2228 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
2230 # Update the page record with revision data
2231 $this->updateRevisionOn( $dbw, $revision, 0 );
2233 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2235 # Update recentchanges
2236 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2237 global $wgUseRCPatrol, $wgUseNPPatrol;
2239 # Mark as patrolled if the user can do so
2240 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
2241 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
2242 # Add RC row to the DB
2243 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2244 '', strlen( $text ), $revisionId, $patrolled );
2246 # Log auto-patrolled edits
2248 PatrolLog
::record( $rc, true );
2251 $user->incEditCount();
2254 # Update links, etc.
2255 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user );
2258 Article
::onArticleCreate( $this->mTitle
);
2260 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2261 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2264 # Do updates right now unless deferral was requested
2265 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2269 // Return the new revision (or null) to the caller
2270 $status->value
['revision'] = $revision;
2272 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2273 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2275 wfProfileOut( __METHOD__
);
2280 * Output a redirect back to the article.
2281 * This is typically used after an edit.
2283 * @param $noRedir Boolean: add redirect=no
2284 * @param $sectionAnchor String: section to redirect to, including "#"
2285 * @param $extraQuery String: extra query params
2287 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2291 $query = 'redirect=no';
2293 $query .= "&$extraQuery";
2295 $query = $extraQuery;
2298 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2302 * Mark this particular edit/page as patrolled
2304 public function markpatrolled() {
2305 global $wgOut, $wgRequest;
2307 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2309 # If we haven't been given an rc_id value, we can't do anything
2310 $rcid = (int) $wgRequest->getVal( 'rcid' );
2312 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2313 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2317 $rc = RecentChange
::newFromId( $rcid );
2319 if ( is_null( $rc ) ) {
2320 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2324 # It would be nice to see where the user had actually come from, but for now just guess
2325 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2326 $return = SpecialPage
::getTitleFor( $returnto );
2328 $errors = $rc->doMarkPatrolled();
2330 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2331 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2336 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2337 // The hook itself has handled any output
2341 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2342 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2343 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2344 $wgOut->returnToMain( false, $return );
2349 if ( !empty( $errors ) ) {
2350 $wgOut->showPermissionsErrorPage( $errors );
2356 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2357 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2358 $wgOut->returnToMain( false, $return );
2362 * User-interface handler for the "watch" action
2364 public function watch() {
2367 if ( $wgOut->getUser()->isAnon() ) {
2368 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2372 if ( wfReadOnly() ) {
2373 $wgOut->readOnlyPage();
2377 if ( $this->doWatch() ) {
2378 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2379 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2380 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
2383 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2387 * Add this page to $wgUser's watchlist
2389 * This is safe to be called multiple times
2391 * @return bool true on successful watch operation
2393 public function doWatch() {
2396 if ( $wgUser->isAnon() ) {
2400 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2401 $wgUser->addWatch( $this->mTitle
);
2402 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2409 * User interface handler for the "unwatch" action.
2411 public function unwatch() {
2414 if ( $wgOut->getUser()->isAnon() ) {
2415 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2419 if ( wfReadOnly() ) {
2420 $wgOut->readOnlyPage();
2424 if ( $this->doUnwatch() ) {
2425 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2426 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2427 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
2430 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2434 * Stop watching a page
2435 * @return bool true on successful unwatch
2437 public function doUnwatch() {
2440 if ( $wgUser->isAnon() ) {
2444 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2445 $wgUser->removeWatch( $this->mTitle
);
2446 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2453 * action=protect handler
2455 public function protect() {
2456 $form = new ProtectionForm( $this );
2461 * action=unprotect handler (alias)
2463 public function unprotect() {
2468 * Update the article's restriction field, and leave a log entry.
2470 * @param $limit Array: set of restriction keys
2471 * @param $reason String
2472 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2473 * @param $expiry Array: per restriction type expiration
2474 * @return bool true on success
2476 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2477 global $wgUser, $wgContLang;
2479 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2481 $id = $this->mTitle
->getArticleID();
2484 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2488 if ( wfReadOnly() ) {
2489 wfDebug( "updateRestrictions failed: read-only\n" );
2493 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2494 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2502 // Take this opportunity to purge out expired restrictions
2503 Title
::purgeExpiredRestrictions();
2505 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2506 # we expect a single selection, but the schema allows otherwise.
2508 $updated = Article
::flattenRestrictions( $limit );
2511 foreach ( $restrictionTypes as $action ) {
2512 if ( isset( $expiry[$action] ) ) {
2513 # Get current restrictions on $action
2514 $aLimits = $this->mTitle
->getRestrictions( $action );
2515 $current[$action] = implode( '', $aLimits );
2516 # Are any actual restrictions being dealt with here?
2517 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2519 # If something changed, we need to log it. Checking $aRChanged
2520 # assures that "unprotecting" a page that is not protected does
2521 # not log just because the expiry was "changed".
2522 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2528 $current = Article
::flattenRestrictions( $current );
2530 $changed = ( $changed ||
$current != $updated );
2531 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2532 $protect = ( $updated != '' );
2534 # If nothing's changed, do nothing
2536 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2537 $dbw = wfGetDB( DB_MASTER
);
2539 # Prepare a null revision to be added to the history
2540 $modified = $current != '' && $protect;
2543 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2545 $comment_type = 'unprotectedarticle';
2548 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2550 # Only restrictions with the 'protect' right can cascade...
2551 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2552 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2554 # The schema allows multiple restrictions
2555 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2559 $cascade_description = '';
2562 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2566 $comment .= ": $reason";
2569 $editComment = $comment;
2570 $encodedExpiry = array();
2571 $protect_description = '';
2572 foreach ( $limit as $action => $restrictions ) {
2573 if ( !isset( $expiry[$action] ) )
2574 $expiry[$action] = $dbw->getInfinity();
2576 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2577 if ( $restrictions != '' ) {
2578 $protect_description .= "[$action=$restrictions] (";
2579 if ( $encodedExpiry[$action] != 'infinity' ) {
2580 $protect_description .= wfMsgForContent( 'protect-expiring',
2581 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2582 $wgContLang->date( $expiry[$action], false, false ) ,
2583 $wgContLang->time( $expiry[$action], false, false ) );
2585 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2588 $protect_description .= ') ';
2591 $protect_description = trim( $protect_description );
2593 if ( $protect_description && $protect ) {
2594 $editComment .= " ($protect_description)";
2598 $editComment .= "$cascade_description";
2601 # Update restrictions table
2602 foreach ( $limit as $action => $restrictions ) {
2603 if ( $restrictions != '' ) {
2604 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2605 array( 'pr_page' => $id,
2606 'pr_type' => $action,
2607 'pr_level' => $restrictions,
2608 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2609 'pr_expiry' => $encodedExpiry[$action]
2614 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2615 'pr_type' => $action ), __METHOD__
);
2619 # Insert a null revision
2620 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2621 $nullRevId = $nullRevision->insertOn( $dbw );
2623 $latest = $this->getLatest();
2624 # Update page record
2625 $dbw->update( 'page',
2627 'page_touched' => $dbw->timestamp(),
2628 'page_restrictions' => '',
2629 'page_latest' => $nullRevId
2630 ), array( /* WHERE */
2632 ), 'Article::protect'
2635 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2636 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2638 # Update the protection log
2639 $log = new LogPage( 'protect' );
2641 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2642 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2644 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2647 } # End "changed" check
2653 * Take an array of page restrictions and flatten it to a string
2654 * suitable for insertion into the page_restrictions field.
2655 * @param $limit Array
2658 protected static function flattenRestrictions( $limit ) {
2659 if ( !is_array( $limit ) ) {
2660 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2666 foreach ( $limit as $action => $restrictions ) {
2667 if ( $restrictions != '' ) {
2668 $bits[] = "$action=$restrictions";
2672 return implode( ':', $bits );
2676 * Auto-generates a deletion reason
2678 * @param &$hasHistory Boolean: whether the page has a history
2679 * @return mixed String containing deletion reason or empty string, or boolean false
2680 * if no revision occurred
2682 public function generateReason( &$hasHistory ) {
2685 $dbw = wfGetDB( DB_MASTER
);
2686 // Get the last revision
2687 $rev = Revision
::newFromTitle( $this->mTitle
);
2689 if ( is_null( $rev ) ) {
2693 // Get the article's contents
2694 $contents = $rev->getText();
2697 // If the page is blank, use the text from the previous revision,
2698 // which can only be blank if there's a move/import/protect dummy revision involved
2699 if ( $contents == '' ) {
2700 $prev = $rev->getPrevious();
2703 $contents = $prev->getText();
2708 // Find out if there was only one contributor
2709 // Only scan the last 20 revisions
2710 $res = $dbw->select( 'revision', 'rev_user_text',
2711 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2713 array( 'LIMIT' => 20 )
2716 if ( $res === false ) {
2717 // This page has no revisions, which is very weird
2721 $hasHistory = ( $res->numRows() > 1 );
2722 $row = $dbw->fetchObject( $res );
2724 if ( $row ) { // $row is false if the only contributor is hidden
2725 $onlyAuthor = $row->rev_user_text
;
2726 // Try to find a second contributor
2727 foreach ( $res as $row ) {
2728 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2729 $onlyAuthor = false;
2734 $onlyAuthor = false;
2737 // Generate the summary with a '$1' placeholder
2739 // The current revision is blank and the one before is also
2740 // blank. It's just not our lucky day
2741 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2743 if ( $onlyAuthor ) {
2744 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2746 $reason = wfMsgForContent( 'excontent', '$1' );
2750 if ( $reason == '-' ) {
2751 // Allow these UI messages to be blanked out cleanly
2755 // Replace newlines with spaces to prevent uglyness
2756 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2757 // Calculate the maximum amount of chars to get
2758 // Max content length = max comment length - length of the comment (excl. $1)
2759 $maxLength = 255 - ( strlen( $reason ) - 2 );
2760 $contents = $wgContLang->truncate( $contents, $maxLength );
2761 // Remove possible unfinished links
2762 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2763 // Now replace the '$1' placeholder
2764 $reason = str_replace( '$1', $contents, $reason );
2771 * UI entry point for page deletion
2773 public function delete() {
2774 global $wgOut, $wgRequest;
2776 $confirm = $wgRequest->wasPosted() &&
2777 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2779 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2780 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2782 $reason = $this->DeleteReasonList
;
2784 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2785 // Entry from drop down menu + additional comment
2786 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2787 } elseif ( $reason == 'other' ) {
2788 $reason = $this->DeleteReason
;
2791 # Flag to hide all contents of the archived revisions
2792 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2794 # This code desperately needs to be totally rewritten
2796 # Read-only check...
2797 if ( wfReadOnly() ) {
2798 $wgOut->readOnlyPage();
2804 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2806 if ( count( $permission_errors ) > 0 ) {
2807 $wgOut->showPermissionsErrorPage( $permission_errors );
2812 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2814 # Better double-check that it hasn't been deleted yet!
2815 $dbw = wfGetDB( DB_MASTER
);
2816 $conds = $this->mTitle
->pageCond();
2817 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2818 if ( $latest === false ) {
2819 $wgOut->showFatalError(
2822 array( 'class' => 'error mw-error-cannotdelete' ),
2823 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2826 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2827 LogEventsList
::showLogExtract(
2830 $this->mTitle
->getPrefixedText()
2836 # Hack for big sites
2837 $bigHistory = $this->isBigDeletion();
2838 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2839 global $wgLang, $wgDeleteRevisionsLimit;
2841 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2842 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2848 $this->doDelete( $reason, $suppress );
2850 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2852 } elseif ( $this->mTitle
->userIsWatching() ) {
2859 // Generate deletion reason
2860 $hasHistory = false;
2862 $reason = $this->generateReason( $hasHistory );
2865 // If the page has a history, insert a warning
2866 if ( $hasHistory && !$confirm ) {
2869 $skin = $wgOut->getSkin();
2870 $revisions = $this->estimateRevisionCount();
2872 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2873 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2874 wfMsgHtml( 'word-separator' ) . $skin->link( $this->mTitle
,
2875 wfMsgHtml( 'history' ),
2876 array( 'rel' => 'archives' ),
2877 array( 'action' => 'history' ) ) .
2881 if ( $bigHistory ) {
2882 global $wgDeleteRevisionsLimit;
2883 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2884 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2888 return $this->confirmDelete( $reason );
2892 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2894 public function isBigDeletion() {
2895 global $wgDeleteRevisionsLimit;
2897 if ( $wgDeleteRevisionsLimit ) {
2898 $revCount = $this->estimateRevisionCount();
2900 return $revCount > $wgDeleteRevisionsLimit;
2907 * @return int approximate revision count
2909 public function estimateRevisionCount() {
2910 $dbr = wfGetDB( DB_SLAVE
);
2912 // For an exact count...
2913 // return $dbr->selectField( 'revision', 'COUNT(*)',
2914 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2915 return $dbr->estimateRowCount( 'revision', '*',
2916 array( 'rev_page' => $this->getId() ), __METHOD__
);
2920 * Get the last N authors
2921 * @param $num Integer: number of revisions to get
2922 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2923 * @return array Array of authors, duplicates not removed
2925 public function getLastNAuthors( $num, $revLatest = 0 ) {
2926 wfProfileIn( __METHOD__
);
2927 // First try the slave
2928 // If that doesn't have the latest revision, try the master
2930 $db = wfGetDB( DB_SLAVE
);
2933 $res = $db->select( array( 'page', 'revision' ),
2934 array( 'rev_id', 'rev_user_text' ),
2936 'page_namespace' => $this->mTitle
->getNamespace(),
2937 'page_title' => $this->mTitle
->getDBkey(),
2938 'rev_page = page_id'
2939 ), __METHOD__
, $this->getSelectOptions( array(
2940 'ORDER BY' => 'rev_timestamp DESC',
2946 wfProfileOut( __METHOD__
);
2950 $row = $db->fetchObject( $res );
2952 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2953 $db = wfGetDB( DB_MASTER
);
2958 } while ( $continue );
2960 $authors = array( $row->rev_user_text
);
2962 foreach ( $res as $row ) {
2963 $authors[] = $row->rev_user_text
;
2966 wfProfileOut( __METHOD__
);
2971 * Output deletion confirmation dialog
2972 * FIXME: Move to another file?
2973 * @param $reason String: prefilled reason
2975 public function confirmDelete( $reason ) {
2978 wfDebug( "Article::confirmDelete\n" );
2980 $deleteBackLink = $wgOut->getSkin()->linkKnown( $this->mTitle
);
2981 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2982 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2983 $wgOut->addWikiMsg( 'confirmdeletetext' );
2985 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2987 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2988 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2990 <td class='mw-input'><strong>" .
2991 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2992 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2998 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
3000 $form = Xml
::openElement( 'form', array( 'method' => 'post',
3001 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
3002 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
3003 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
3004 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
3005 "<tr id=\"wpDeleteReasonListRow\">
3006 <td class='mw-label'>" .
3007 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
3009 <td class='mw-input'>" .
3010 Xml
::listDropDown( 'wpDeleteReasonList',
3011 wfMsgForContent( 'deletereason-dropdown' ),
3012 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
3015 <tr id=\"wpDeleteReasonRow\">
3016 <td class='mw-label'>" .
3017 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
3019 <td class='mw-input'>" .
3020 Html
::input( 'wpReason', $reason, 'text', array(
3022 'maxlength' => '255',
3030 # Disallow watching if user is not logged in
3031 if ( $wgOut->getUser()->isLoggedIn() ) {
3035 <td class='mw-input'>" .
3036 Xml
::checkLabel( wfMsg( 'watchthis' ),
3037 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3046 <td class='mw-submit'>" .
3047 Xml
::submitButton( wfMsg( 'deletepage' ),
3048 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3051 Xml
::closeElement( 'table' ) .
3052 Xml
::closeElement( 'fieldset' ) .
3053 Html
::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
3054 Xml
::closeElement( 'form' );
3056 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
3057 $skin = $wgOut->getSkin();
3058 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
3059 $link = $skin->link(
3061 wfMsgHtml( 'delete-edit-reasonlist' ),
3063 array( 'action' => 'edit' )
3065 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3068 $wgOut->addHTML( $form );
3069 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3070 LogEventsList
::showLogExtract( $wgOut, 'delete',
3071 $this->mTitle
->getPrefixedText()
3076 * Perform a deletion and output success or failure messages
3078 public function doDelete( $reason, $suppress = false ) {
3081 $id = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3084 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
3085 $deleted = $this->mTitle
->getPrefixedText();
3087 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3088 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3090 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3092 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3093 $wgOut->returnToMain( false );
3095 if ( $error == '' ) {
3096 $wgOut->showFatalError(
3099 array( 'class' => 'error mw-error-cannotdelete' ),
3100 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
3104 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
3106 LogEventsList
::showLogExtract(
3109 $this->mTitle
->getPrefixedText()
3112 $wgOut->showFatalError( $error );
3118 * Back-end article deletion
3119 * Deletes the article with database consistency, writes logs, purges caches
3121 * @param $reason string delete reason for deletion log
3122 * @param suppress bitfield
3123 * Revision::DELETED_TEXT
3124 * Revision::DELETED_COMMENT
3125 * Revision::DELETED_USER
3126 * Revision::DELETED_RESTRICTED
3127 * @param $id int article ID
3128 * @param $commit boolean defaults to true, triggers transaction end
3129 * @return boolean true if successful
3131 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3132 global $wgDeferredUpdateList, $wgUseTrackbacks;
3135 wfDebug( __METHOD__
. "\n" );
3137 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3140 $dbw = wfGetDB( DB_MASTER
);
3141 $t = $this->mTitle
->getDBkey();
3142 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
3144 if ( $t === '' ||
$id == 0 ) {
3148 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3149 array_push( $wgDeferredUpdateList, $u );
3151 // Bitfields to further suppress the content
3154 // This should be 15...
3155 $bitfield |
= Revision
::DELETED_TEXT
;
3156 $bitfield |
= Revision
::DELETED_COMMENT
;
3157 $bitfield |
= Revision
::DELETED_USER
;
3158 $bitfield |
= Revision
::DELETED_RESTRICTED
;
3160 $bitfield = 'rev_deleted';
3164 // For now, shunt the revision data into the archive table.
3165 // Text is *not* removed from the text table; bulk storage
3166 // is left intact to avoid breaking block-compression or
3167 // immutable storage schemes.
3169 // For backwards compatibility, note that some older archive
3170 // table entries will have ar_text and ar_flags fields still.
3172 // In the future, we may keep revisions and mark them with
3173 // the rev_deleted field, which is reserved for this purpose.
3174 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3176 'ar_namespace' => 'page_namespace',
3177 'ar_title' => 'page_title',
3178 'ar_comment' => 'rev_comment',
3179 'ar_user' => 'rev_user',
3180 'ar_user_text' => 'rev_user_text',
3181 'ar_timestamp' => 'rev_timestamp',
3182 'ar_minor_edit' => 'rev_minor_edit',
3183 'ar_rev_id' => 'rev_id',
3184 'ar_text_id' => 'rev_text_id',
3185 'ar_text' => '\'\'', // Be explicit to appease
3186 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3187 'ar_len' => 'rev_len',
3188 'ar_page_id' => 'page_id',
3189 'ar_deleted' => $bitfield
3192 'page_id = rev_page'
3196 # Delete restrictions for it
3197 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
3199 # Now that it's safely backed up, delete it
3200 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
3201 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3208 # Fix category table counts
3210 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
3212 foreach ( $res as $row ) {
3213 $cats [] = $row->cl_to
;
3216 $this->updateCategoryCounts( array(), $cats );
3218 # If using cascading deletes, we can skip some explicit deletes
3219 if ( !$dbw->cascadingDeletes() ) {
3220 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
3222 if ( $wgUseTrackbacks )
3223 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
3225 # Delete outgoing links
3226 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3227 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3228 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3229 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3230 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3231 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3232 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3235 # If using cleanup triggers, we can skip some manual deletes
3236 if ( !$dbw->cleanupTriggers() ) {
3237 # Clean up recentchanges entries...
3238 $dbw->delete( 'recentchanges',
3239 array( 'rc_type != ' . RC_LOG
,
3240 'rc_namespace' => $this->mTitle
->getNamespace(),
3241 'rc_title' => $this->mTitle
->getDBkey() ),
3243 $dbw->delete( 'recentchanges',
3244 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
3249 Article
::onArticleDelete( $this->mTitle
);
3251 # Clear the cached article id so the interface doesn't act like we exist
3252 $this->mTitle
->resetArticleID( 0 );
3254 # Log the deletion, if the page was suppressed, log it at Oversight instead
3255 $logtype = $suppress ?
'suppress' : 'delete';
3256 $log = new LogPage( $logtype );
3258 # Make sure logging got through
3259 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3265 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3270 * Roll back the most recent consecutive set of edits to a page
3271 * from the same user; fails if there are no eligible edits to
3272 * roll back to, e.g. user is the sole contributor. This function
3273 * performs permissions checks on $wgUser, then calls commitRollback()
3274 * to do the dirty work
3276 * @param $fromP String: Name of the user whose edits to rollback.
3277 * @param $summary String: Custom summary. Set to default summary if empty.
3278 * @param $token String: Rollback token.
3279 * @param $bot Boolean: If true, mark all reverted edits as bot.
3281 * @param $resultDetails Array: contains result-specific array of additional values
3282 * 'alreadyrolled' : 'current' (rev)
3283 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3285 * @return array of errors, each error formatted as
3286 * array(messagekey, param1, param2, ...).
3287 * On success, the array is empty. This array can also be passed to
3288 * OutputPage::showPermissionsErrorPage().
3290 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3293 $resultDetails = null;
3296 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3297 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3298 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3300 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
3301 $errors[] = array( 'sessionfailure' );
3304 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3305 $errors[] = array( 'actionthrottledtext' );
3308 # If there were errors, bail out now
3309 if ( !empty( $errors ) ) {
3313 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3317 * Backend implementation of doRollback(), please refer there for parameter
3318 * and return value documentation
3320 * NOTE: This function does NOT check ANY permissions, it just commits the
3321 * rollback to the DB Therefore, you should only call this function direct-
3322 * ly if you want to use custom permissions checks. If you don't, use
3323 * doRollback() instead.
3325 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3326 global $wgUseRCPatrol, $wgUser, $wgLang;
3328 $dbw = wfGetDB( DB_MASTER
);
3330 if ( wfReadOnly() ) {
3331 return array( array( 'readonlytext' ) );
3334 # Get the last editor
3335 $current = Revision
::newFromTitle( $this->mTitle
);
3336 if ( is_null( $current ) ) {
3337 # Something wrong... no page?
3338 return array( array( 'notanarticle' ) );
3341 $from = str_replace( '_', ' ', $fromP );
3342 # User name given should match up with the top revision.
3343 # If the user was deleted then $from should be empty.
3344 if ( $from != $current->getUserText() ) {
3345 $resultDetails = array( 'current' => $current );
3346 return array( array( 'alreadyrolled',
3347 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3348 htmlspecialchars( $fromP ),
3349 htmlspecialchars( $current->getUserText() )
3353 # Get the last edit not by this guy...
3354 # Note: these may not be public values
3355 $user = intval( $current->getRawUser() );
3356 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3357 $s = $dbw->selectRow( 'revision',
3358 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3359 array( 'rev_page' => $current->getPage(),
3360 "rev_user != {$user} OR rev_user_text != {$user_text}"
3362 array( 'USE INDEX' => 'page_timestamp',
3363 'ORDER BY' => 'rev_timestamp DESC' )
3365 if ( $s === false ) {
3366 # No one else ever edited this page
3367 return array( array( 'cantrollback' ) );
3368 } else if ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
3369 # Only admins can see this text
3370 return array( array( 'notvisiblerev' ) );
3374 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3375 # Mark all reverted edits as bot
3379 if ( $wgUseRCPatrol ) {
3380 # Mark all reverted edits as patrolled
3381 $set['rc_patrolled'] = 1;
3384 if ( count( $set ) ) {
3385 $dbw->update( 'recentchanges', $set,
3387 'rc_cur_id' => $current->getPage(),
3388 'rc_user_text' => $current->getUserText(),
3389 "rc_timestamp > '{$s->rev_timestamp}'",
3394 # Generate the edit summary if necessary
3395 $target = Revision
::newFromId( $s->rev_id
);
3396 if ( empty( $summary ) ) {
3397 if ( $from == '' ) { // no public user name
3398 $summary = wfMsgForContent( 'revertpage-nouser' );
3400 $summary = wfMsgForContent( 'revertpage' );
3404 # Allow the custom summary to use the same args as the default message
3406 $target->getUserText(), $from, $s->rev_id
,
3407 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3408 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3410 $summary = wfMsgReplaceArgs( $summary, $args );
3413 $flags = EDIT_UPDATE
;
3415 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3416 $flags |
= EDIT_MINOR
;
3419 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3420 $flags |
= EDIT_FORCE_BOT
;
3423 # Actually store the edit
3424 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3425 if ( !empty( $status->value
['revision'] ) ) {
3426 $revId = $status->value
['revision']->getId();
3431 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3433 $resultDetails = array(
3434 'summary' => $summary,
3435 'current' => $current,
3436 'target' => $target,
3444 * User interface for rollback operations
3446 public function rollback() {
3447 global $wgUser, $wgOut, $wgRequest;
3451 $result = $this->doRollback(
3452 $wgRequest->getVal( 'from' ),
3453 $wgRequest->getText( 'summary' ),
3454 $wgRequest->getVal( 'token' ),
3455 $wgRequest->getBool( 'bot' ),
3459 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3460 $wgOut->rateLimited();
3464 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3465 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3466 $errArray = $result[0];
3467 $errMsg = array_shift( $errArray );
3468 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3470 if ( isset( $details['current'] ) ) {
3471 $current = $details['current'];
3473 if ( $current->getComment() != '' ) {
3474 $wgOut->addWikiMsgArray( 'editcomment', array(
3475 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3482 # Display permissions errors before read-only message -- there's no
3483 # point in misleading the user into thinking the inability to rollback
3484 # is only temporary.
3485 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3486 # array_diff is completely broken for arrays of arrays, sigh.
3487 # Remove any 'readonlytext' error manually.
3489 foreach ( $result as $error ) {
3490 if ( $error != array( 'readonlytext' ) ) {
3494 $wgOut->showPermissionsErrorPage( $out );
3499 if ( $result == array( array( 'readonlytext' ) ) ) {
3500 $wgOut->readOnlyPage();
3505 $current = $details['current'];
3506 $target = $details['target'];
3507 $newId = $details['newid'];
3508 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3509 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3511 if ( $current->getUserText() === '' ) {
3512 $old = wfMsg( 'rev-deleted-user' );
3514 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3515 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3518 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3519 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3520 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3521 $wgOut->returnToMain( false, $this->mTitle
);
3523 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3524 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3525 $de->showDiff( '', '' );
3530 * Do standard deferred updates after page view
3532 public function viewUpdates() {
3533 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3534 if ( wfReadOnly() ) {
3538 # Don't update page view counters on views from bot users (bug 14044)
3539 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3540 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3541 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3544 # Update newtalk / watchlist notification status
3545 $wgUser->clearNotification( $this->mTitle
);
3549 * Prepare text which is about to be saved.
3550 * Returns a stdclass with source, pst and output members
3552 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
3553 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3555 return $this->mPreparedEdit
;
3560 if( $user === null ) {
3564 $popts = ParserOptions
::newFromUser( $user );
3565 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3567 $edit = (object)array();
3568 $edit->revid
= $revid;
3569 $edit->newText
= $text;
3570 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
3571 $edit->popts
= $this->getParserOptions();
3572 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
3573 $edit->oldText
= $this->getRawText();
3575 $this->mPreparedEdit
= $edit;
3581 * Do standard deferred updates after page edit.
3582 * Update links tables, site stats, search index and message cache.
3583 * Purges pages that include this page if the text was changed here.
3584 * Every 100th edit, prune the recent changes table.
3587 * @param $text String: New text of the article
3588 * @param $summary String: Edit summary
3589 * @param $minoredit Boolean: Minor edit
3590 * @param $timestamp_of_pagechange String timestamp associated with the page change
3591 * @param $newid Integer: rev_id value of the new revision
3592 * @param $changed Boolean: Whether or not the content actually changed
3593 * @param $user User object: User doing the edit
3595 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User
$user = null ) {
3596 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3598 wfProfileIn( __METHOD__
);
3601 # Be careful not to double-PST: $text is usually already PST-ed once
3602 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3603 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3604 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3606 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3607 $editInfo = $this->mPreparedEdit
;
3610 # Save it to the parser cache
3611 if ( $wgEnableParserCache ) {
3612 $parserCache = ParserCache
::singleton();
3613 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
3616 # Update the links tables
3617 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3620 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3622 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3623 if ( 0 == mt_rand( 0, 99 ) ) {
3624 // Flush old entries from the `recentchanges` table; we do this on
3625 // random requests so as to avoid an increase in writes for no good reason
3628 $dbw = wfGetDB( DB_MASTER
);
3629 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3632 array( "rc_timestamp < '$cutoff'" ),
3638 $id = $this->getID();
3639 $title = $this->mTitle
->getPrefixedDBkey();
3640 $shortTitle = $this->mTitle
->getDBkey();
3643 wfProfileOut( __METHOD__
);
3647 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3648 array_push( $wgDeferredUpdateList, $u );
3649 $u = new SearchUpdate( $id, $title, $text );
3650 array_push( $wgDeferredUpdateList, $u );
3652 # If this is another user's talk page, update newtalk
3653 # Don't do this if $changed = false otherwise some idiot can null-edit a
3654 # load of user talk pages and piss people off, nor if it's a minor edit
3655 # by a properly-flagged bot.
3656 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3657 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3659 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3660 $other = User
::newFromName( $shortTitle, false );
3662 wfDebug( __METHOD__
. ": invalid username\n" );
3663 } elseif ( User
::isIP( $shortTitle ) ) {
3664 // An anonymous user
3665 $other->setNewtalk( true );
3666 } elseif ( $other->isLoggedIn() ) {
3667 $other->setNewtalk( true );
3669 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3674 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3675 MessageCache
::singleton()->replace( $shortTitle, $text );
3678 wfProfileOut( __METHOD__
);
3682 * Perform article updates on a special page creation.
3684 * @param $rev Revision object
3686 * @todo This is a shitty interface function. Kill it and replace the
3687 * other shitty functions like editUpdates and such so it's not needed
3690 public function createUpdates( $rev ) {
3691 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3692 $this->mTotalAdjustment
= 1;
3693 $this->editUpdates( $rev->getText(), $rev->getComment(),
3694 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3698 * Generate the navigation links when browsing through an article revisions
3699 * It shows the information as:
3700 * Revision as of \<date\>; view current revision
3701 * \<- Previous version | Next Version -\>
3703 * @param $oldid String: revision ID of this article revision
3705 public function setOldSubtitle( $oldid = 0 ) {
3706 global $wgLang, $wgOut, $wgUser, $wgRequest;
3708 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3712 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3714 # Cascade unhide param in links for easy deletion browsing
3715 $extraParams = array();
3716 if ( $wgRequest->getVal( 'unhide' ) ) {
3717 $extraParams['unhide'] = 1;
3720 $revision = Revision
::newFromId( $oldid );
3722 $current = ( $oldid == $this->mLatest
);
3723 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3724 $tddate = $wgLang->date( $this->mTimestamp
, true );
3725 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3726 $sk = $wgUser->getSkin();
3728 ?
wfMsgHtml( 'currentrevisionlink' )
3731 wfMsgHtml( 'currentrevisionlink' ),
3734 array( 'known', 'noclasses' )
3737 ?
wfMsgHtml( 'diff' )
3740 wfMsgHtml( 'diff' ),
3746 array( 'known', 'noclasses' )
3748 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3752 wfMsgHtml( 'previousrevision' ),
3755 'direction' => 'prev',
3758 array( 'known', 'noclasses' )
3760 : wfMsgHtml( 'previousrevision' );
3764 wfMsgHtml( 'diff' ),
3770 array( 'known', 'noclasses' )
3772 : wfMsgHtml( 'diff' );
3773 $nextlink = $current
3774 ?
wfMsgHtml( 'nextrevision' )
3777 wfMsgHtml( 'nextrevision' ),
3780 'direction' => 'next',
3783 array( 'known', 'noclasses' )
3785 $nextdiff = $current
3786 ?
wfMsgHtml( 'diff' )
3789 wfMsgHtml( 'diff' ),
3795 array( 'known', 'noclasses' )
3800 // User can delete revisions or view deleted revisions...
3801 $canHide = $wgUser->isAllowed( 'deleterevision' );
3802 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3803 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3804 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3807 'type' => 'revision',
3808 'target' => $this->mTitle
->getPrefixedDbkey(),
3811 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3816 # Show user links if allowed to see them. If hidden, then show them only if requested...
3817 $userlinks = $sk->revUserTools( $revision, !$unhide );
3819 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3820 ?
'revision-info-current'
3823 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3826 array( 'parseinline', 'replaceafter' ),
3832 $revision->getUser()
3835 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3836 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3838 $wgOut->addHTML( $r );
3842 * This function is called right before saving the wikitext,
3843 * so we can do things like signatures and links-in-context.
3845 * @param $text String article contents
3846 * @param $user User object: user doing the edit, $wgUser will be used if
3848 * @param $popts ParserOptions object: parser options, default options for
3849 * the user loaded if null given
3850 * @return string article contents with altered wikitext markup (signatures
3851 * converted, {{subst:}}, templates, etc.)
3853 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3856 if ( $user === null ) {
3861 if ( $popts === null ) {
3862 $popts = ParserOptions
::newFromUser( $user );
3865 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3868 /* Caching functions */
3871 * checkLastModified returns true if it has taken care of all
3872 * output to the client that is necessary for this request.
3873 * (that is, it has sent a cached version of the page)
3875 * @return boolean true if cached version send, false otherwise
3877 protected function tryFileCache() {
3878 static $called = false;
3881 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3886 if ( $this->isFileCacheable() ) {
3887 $cache = new HTMLFileCache( $this->mTitle
);
3888 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3889 wfDebug( "Article::tryFileCache(): about to load file\n" );
3890 $cache->loadFromFileCache();
3893 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3894 ob_start( array( &$cache, 'saveToFileCache' ) );
3897 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3904 * Check if the page can be cached
3907 public function isFileCacheable() {
3910 if ( HTMLFileCache
::useFileCache() ) {
3911 $cacheable = $this->getID() && !$this->mRedirectedFrom
&& !$this->mTitle
->isRedirect();
3912 // Extension may have reason to disable file caching on some pages.
3914 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3922 * Loads page_touched and returns a value indicating if it should be used
3923 * @return boolean true if not a redirect
3925 public function checkTouched() {
3926 if ( !$this->mDataLoaded
) {
3927 $this->loadPageData();
3930 return !$this->mIsRedirect
;
3934 * Get the page_touched field
3935 * @return string containing GMT timestamp
3937 public function getTouched() {
3938 if ( !$this->mDataLoaded
) {
3939 $this->loadPageData();
3942 return $this->mTouched
;
3946 * Get the page_latest field
3947 * @return integer rev_id of current revision
3949 public function getLatest() {
3950 if ( !$this->mDataLoaded
) {
3951 $this->loadPageData();
3954 return (int)$this->mLatest
;
3958 * Edit an article without doing all that other stuff
3959 * The article must already exist; link tables etc
3960 * are not updated, caches are not flushed.
3962 * @param $text String: text submitted
3963 * @param $comment String: comment submitted
3964 * @param $minor Boolean: whereas it's a minor modification
3966 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3967 wfProfileIn( __METHOD__
);
3969 $dbw = wfGetDB( DB_MASTER
);
3970 $revision = new Revision( array(
3971 'page' => $this->getId(),
3973 'comment' => $comment,
3974 'minor_edit' => $minor ?
1 : 0,
3976 $revision->insertOn( $dbw );
3977 $this->updateRevisionOn( $dbw, $revision );
3980 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3982 wfProfileOut( __METHOD__
);
3986 * The onArticle*() functions are supposed to be a kind of hooks
3987 * which should be called whenever any of the specified actions
3990 * This is a good place to put code to clear caches, for instance.
3992 * This is called on page move and undelete, as well as edit
3994 * @param $title Title object
3996 public static function onArticleCreate( $title ) {
3997 # Update existence markers on article/talk tabs...
3998 if ( $title->isTalkPage() ) {
3999 $other = $title->getSubjectPage();
4001 $other = $title->getTalkPage();
4004 $other->invalidateCache();
4005 $other->purgeSquid();
4007 $title->touchLinks();
4008 $title->purgeSquid();
4009 $title->deleteTitleProtection();
4013 * Clears caches when article is deleted
4015 public static function onArticleDelete( $title ) {
4016 # Update existence markers on article/talk tabs...
4017 if ( $title->isTalkPage() ) {
4018 $other = $title->getSubjectPage();
4020 $other = $title->getTalkPage();
4023 $other->invalidateCache();
4024 $other->purgeSquid();
4026 $title->touchLinks();
4027 $title->purgeSquid();
4030 HTMLFileCache
::clearFileCache( $title );
4033 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
4034 MessageCache
::singleton()->replace( $title->getDBkey(), false );
4038 if ( $title->getNamespace() == NS_FILE
) {
4039 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4040 $update->doUpdate();
4044 if ( $title->getNamespace() == NS_USER_TALK
) {
4045 $user = User
::newFromName( $title->getText(), false );
4046 $user->setNewtalk( false );
4050 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4054 * Purge caches on page update etc
4056 * @param $title Title object
4057 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4059 public static function onArticleEdit( $title ) {
4060 global $wgDeferredUpdateList;
4062 // Invalidate caches of articles which include this page
4063 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4065 // Invalidate the caches of all pages which redirect here
4066 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4068 # Purge squid for this page only
4069 $title->purgeSquid();
4071 # Clear file cache for this page only
4072 HTMLFileCache
::clearFileCache( $title );
4078 * Overriden by ImagePage class, only present here to avoid a fatal error
4079 * Called for ?action=revert
4081 public function revert() {
4083 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4087 * Info about this page
4088 * Called for ?action=info when $wgAllowPageInfo is on.
4090 public function info() {
4091 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4093 if ( !$wgAllowPageInfo ) {
4094 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4098 $page = $this->mTitle
->getSubjectPage();
4100 $wgOut->setPagetitle( $page->getPrefixedText() );
4101 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4102 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4104 if ( !$this->mTitle
->exists() ) {
4105 $wgOut->addHTML( '<div class="noarticletext">' );
4106 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
4107 // This doesn't quite make sense; the user is asking for
4108 // information about the _page_, not the message... -- RC
4109 $wgOut->addHTML( htmlspecialchars( $this->mTitle
->getDefaultMessageText() ) );
4111 $msg = $wgUser->isLoggedIn()
4113 : 'noarticletextanon';
4114 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4117 $wgOut->addHTML( '</div>' );
4119 $dbr = wfGetDB( DB_SLAVE
);
4121 'wl_title' => $page->getDBkey(),
4122 'wl_namespace' => $page->getNamespace() );
4123 $numwatchers = $dbr->selectField(
4128 $this->getSelectOptions() );
4130 $pageInfo = $this->pageCountInfo( $page );
4131 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4134 //FIXME: unescaped messages
4135 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4136 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4139 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4142 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4145 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4148 $wgOut->addHTML( '</ul>' );
4153 * Return the total number of edits and number of unique editors
4154 * on a given page. If page does not exist, returns false.
4156 * @param $title Title object
4157 * @return mixed array or boolean false
4159 public function pageCountInfo( $title ) {
4160 $id = $title->getArticleId();
4166 $dbr = wfGetDB( DB_SLAVE
);
4167 $rev_clause = array( 'rev_page' => $id );
4168 $edits = $dbr->selectField(
4173 $this->getSelectOptions()
4175 $authors = $dbr->selectField(
4177 'COUNT(DISTINCT rev_user_text)',
4180 $this->getSelectOptions()
4183 return array( 'edits' => $edits, 'authors' => $authors );
4187 * Return a list of templates used by this article.
4188 * Uses the templatelinks table
4190 * @return Array of Title objects
4192 public function getUsedTemplates() {
4194 $id = $this->mTitle
->getArticleID();
4200 $dbr = wfGetDB( DB_SLAVE
);
4201 $res = $dbr->select( array( 'templatelinks' ),
4202 array( 'tl_namespace', 'tl_title' ),
4203 array( 'tl_from' => $id ),
4206 if ( $res !== false ) {
4207 foreach ( $res as $row ) {
4208 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
4216 * Returns a list of hidden categories this page is a member of.
4217 * Uses the page_props and categorylinks tables.
4219 * @return Array of Title objects
4221 public function getHiddenCategories() {
4223 $id = $this->mTitle
->getArticleID();
4229 $dbr = wfGetDB( DB_SLAVE
);
4230 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4232 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4233 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
4236 if ( $res !== false ) {
4237 foreach ( $res as $row ) {
4238 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
4246 * Return an applicable autosummary if one exists for the given edit.
4247 * @param $oldtext String: the previous text of the page.
4248 * @param $newtext String: The submitted text of the page.
4249 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4250 * @return string An appropriate autosummary, or an empty string.
4252 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4255 # Decide what kind of autosummary is needed.
4257 # Redirect autosummaries
4258 $ot = Title
::newFromRedirect( $oldtext );
4259 $rt = Title
::newFromRedirect( $newtext );
4261 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
4262 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4265 # New page autosummaries
4266 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
4267 # If they're making a new article, give its text, truncated, in the summary.
4269 $truncatedtext = $wgContLang->truncate(
4270 str_replace( "\n", ' ', $newtext ),
4271 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4273 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4276 # Blanking autosummaries
4277 if ( $oldtext != '' && $newtext == '' ) {
4278 return wfMsgForContent( 'autosumm-blank' );
4279 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4280 # Removing more than 90% of the article
4282 $truncatedtext = $wgContLang->truncate(
4284 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4286 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4289 # If we reach this point, there's no applicable autosummary for our case, so our
4290 # autosummary is empty.
4295 * Add the primary page-view wikitext to the output buffer
4296 * Saves the text into the parser cache if possible.
4297 * Updates templatelinks if it is out of date.
4299 * @param $text String
4300 * @param $cache Boolean
4301 * @param $parserOptions mixed ParserOptions object, or boolean false
4303 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4306 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4307 $wgOut->addParserOutput( $this->mParserOutput
);
4311 * This does all the heavy lifting for outputWikitext, except it returns the parser
4312 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4313 * say, embedding thread pages within a discussion system (LiquidThreads)
4315 * @param $text string
4316 * @param $cache boolean
4317 * @param $parserOptions parsing options, defaults to false
4318 * @return string containing parsed output
4320 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4321 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4323 if ( !$parserOptions ) {
4324 $parserOptions = $this->getParserOptions();
4328 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4329 $parserOptions, true, true, $this->getRevIdFetched() );
4334 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4335 $this->mTitle
->getPrefixedDBkey() ) );
4338 if ( $wgEnableParserCache && $cache && $this->mParserOutput
->isCacheable() ) {
4339 $parserCache = ParserCache
::singleton();
4340 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4343 // Make sure file cache is not used on uncacheable content.
4344 // Output that has magic words in it can still use the parser cache
4345 // (if enabled), though it will generally expire sooner.
4346 if ( !$this->mParserOutput
->isCacheable() ||
$this->mParserOutput
->containsOldMagic() ) {
4347 $wgUseFileCache = false;
4350 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4352 return $this->mParserOutput
;
4356 * Get parser options suitable for rendering the primary article wikitext
4357 * @return mixed ParserOptions object or boolean false
4359 public function getParserOptions() {
4362 if ( !$this->mParserOptions
) {
4363 $this->mParserOptions
= new ParserOptions( $wgUser );
4364 $this->mParserOptions
->setTidy( true );
4365 $this->mParserOptions
->enableLimitReport();
4368 // Clone to allow modifications of the return value without affecting
4370 return clone $this->mParserOptions
;
4374 * Updates cascading protections
4376 * @param $parserOutput mixed ParserOptions object, or boolean false
4378 protected function doCascadeProtectionUpdates( $parserOutput ) {
4379 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4383 // templatelinks table may have become out of sync,
4384 // especially if using variable-based transclusions.
4385 // For paranoia, check if things have changed and if
4386 // so apply updates to the database. This will ensure
4387 // that cascaded protections apply as soon as the changes
4390 # Get templates from templatelinks
4391 $id = $this->mTitle
->getArticleID();
4393 $tlTemplates = array();
4395 $dbr = wfGetDB( DB_SLAVE
);
4396 $res = $dbr->select( array( 'templatelinks' ),
4397 array( 'tl_namespace', 'tl_title' ),
4398 array( 'tl_from' => $id ),
4402 foreach ( $res as $row ) {
4403 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4406 # Get templates from parser output.
4407 $poTemplates = array();
4408 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4409 foreach ( $templates as $dbk => $id ) {
4410 $poTemplates["$ns:$dbk"] = true;
4415 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4417 if ( count( $templates_diff ) > 0 ) {
4418 # Whee, link updates time.
4419 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4425 * Update all the appropriate counts in the category table, given that
4426 * we've added the categories $added and deleted the categories $deleted.
4428 * @param $added array The names of categories that were added
4429 * @param $deleted array The names of categories that were deleted
4431 public function updateCategoryCounts( $added, $deleted ) {
4432 $ns = $this->mTitle
->getNamespace();
4433 $dbw = wfGetDB( DB_MASTER
);
4435 # First make sure the rows exist. If one of the "deleted" ones didn't
4436 # exist, we might legitimately not create it, but it's simpler to just
4437 # create it and then give it a negative value, since the value is bogus
4440 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4441 $insertCats = array_merge( $added, $deleted );
4442 if ( !$insertCats ) {
4443 # Okay, nothing to do
4447 $insertRows = array();
4449 foreach ( $insertCats as $cat ) {
4450 $insertRows[] = array(
4451 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4455 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4457 $addFields = array( 'cat_pages = cat_pages + 1' );
4458 $removeFields = array( 'cat_pages = cat_pages - 1' );
4460 if ( $ns == NS_CATEGORY
) {
4461 $addFields[] = 'cat_subcats = cat_subcats + 1';
4462 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4463 } elseif ( $ns == NS_FILE
) {
4464 $addFields[] = 'cat_files = cat_files + 1';
4465 $removeFields[] = 'cat_files = cat_files - 1';
4472 array( 'cat_title' => $added ),
4481 array( 'cat_title' => $deleted ),
4488 * Lightweight method to get the parser output for a page, checking the parser cache
4489 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4490 * consider, so it's not appropriate to use there.
4492 * @since 1.16 (r52326) for LiquidThreads
4494 * @param $oldid mixed integer Revision ID or null
4495 * @return ParserOutput or false if the given revsion ID is not found
4497 public function getParserOutput( $oldid = null ) {
4498 global $wgEnableParserCache, $wgUser;
4500 // Should the parser cache be used?
4501 $useParserCache = $wgEnableParserCache &&
4502 $wgUser->getStubThreshold() == 0 &&
4506 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4508 if ( $wgUser->getStubThreshold() ) {
4509 wfIncrStats( 'pcache_miss_stub' );
4512 if ( $useParserCache ) {
4513 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4514 if ( $parserOutput !== false ) {
4515 return $parserOutput;
4519 // Cache miss; parse and output it.
4520 if ( $oldid === null ) {
4521 $text = $this->getRawText();
4523 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4524 if ( $rev === null ) {
4527 $text = $rev->getText();
4530 return $this->getOutputFromWikitext( $text, $useParserCache );
4535 class PoolWorkArticleView
extends PoolCounterWork
{
4538 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4539 parent
::__construct( 'ArticleView', $key );
4540 $this->mArticle
= $article;
4541 $this->cacheable
= $useParserCache;
4542 $this->parserOptions
= $parserOptions;
4546 return $this->mArticle
->doViewParse();
4549 function getCachedWork() {
4552 $parserCache = ParserCache
::singleton();
4553 $this->mArticle
->mParserOutput
= $parserCache->get( $this->mArticle
, $this->parserOptions
);
4555 if ( $this->mArticle
->mParserOutput
!== false ) {
4556 wfDebug( __METHOD__
. ": showing contents parsed by someone else\n" );
4557 $wgOut->addParserOutput( $this->mArticle
->mParserOutput
);
4558 # Ensure that UI elements requiring revision ID have
4559 # the correct version information.
4560 $wgOut->setRevisionId( $this->mArticle
->getLatest() );
4566 function fallback() {
4567 return $this->mArticle
->tryDirtyCache();
4570 function error( $status ) {
4573 $wgOut->clearHTML(); // for release() errors
4574 $wgOut->enableClientCache( false );
4575 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4577 $errortext = $status->getWikiText( false, 'view-pool-error' );
4578 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );