mTitle =& $title; $this->mOldId = $oldId; } /** * Constructor from an article article * @param $id The article ID to load */ public static function newFromID( $id ) { $t = Title::newFromID( $id ); return $t == null ? null : new Article( $t ); } /** * Tell the page view functions that this view was redirected * from another page on the wiki. * @param $from Title object. */ public function setRedirectedFrom( $from ) { $this->mRedirectedFrom = $from; } /** * If this page is a redirect, get its target * * The target will be fetched from the redirect table if possible. * If this page doesn't have an entry there, call insertRedirect() * @return mixed Title object, or null if this page is not a redirect */ public function getRedirectTarget() { if( !$this->mTitle || !$this->mTitle->isRedirect() ) return null; if( !is_null($this->mRedirectTarget) ) return $this->mRedirectTarget; # Query the redirect table $dbr = wfGetDB( DB_SLAVE ); $row = $dbr->selectRow( 'redirect', array('rd_namespace', 'rd_title'), array('rd_from' => $this->getID() ), __METHOD__ ); if( $row ) { return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title); } # This page doesn't have an entry in the redirect table return $this->mRedirectTarget = $this->insertRedirect(); } /** * Insert an entry for this page into the redirect table. * * Don't call this function directly unless you know what you're doing. * @return Title object */ public function insertRedirect() { $retval = Title::newFromRedirect( $this->getContent() ); if( !$retval ) { return null; } $dbw = wfGetDB( DB_MASTER ); $dbw->replace( 'redirect', array('rd_from'), array( 'rd_from' => $this->getID(), 'rd_namespace' => $retval->getNamespace(), 'rd_title' => $retval->getDBKey() ), __METHOD__ ); return $retval; } /** * Get the Title object this page redirects to * * @return mixed false, Title of in-wiki target, or string with URL */ public function followRedirect() { $text = $this->getContent(); return $this->followRedirectText( $text ); } /** * Get the Title object this text redirects to * * @return mixed false, Title of in-wiki target, or string with URL */ public function followRedirectText( $text ) { $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target # process if title object is valid and not special:userlogout if( $rt ) { if( $rt->getInterwiki() != '' ) { if( $rt->isLocal() ) { // Offsite wikis need an HTTP redirect. // // This can be hard to reverse and may produce loops, // so they may be disabled in the site configuration. $source = $this->mTitle->getFullURL( 'redirect=no' ); return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ); } } else { if( $rt->getNamespace() == NS_SPECIAL ) { // Gotta handle redirects to special pages differently: // Fill the HTTP response "Location" header and ignore // the rest of the page we're on. // // This can be hard to reverse, so they may be disabled. if( $rt->isSpecial( 'Userlogout' ) ) { // rolleyes } else { return $rt->getFullURL(); } } return $rt; } } // No or invalid redirect return false; } /** * get the title object of the article */ public function getTitle() { return $this->mTitle; } /** * Clear the object * @private */ public function clear() { $this->mDataLoaded = false; $this->mContentLoaded = false; $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded $this->mRedirectedFrom = null; # Title object if set $this->mRedirectTarget = null; # Title object if set $this->mUserText = $this->mTimestamp = $this->mComment = ''; $this->mGoodAdjustment = $this->mTotalAdjustment = 0; $this->mTouched = '19700101000000'; $this->mForUpdate = false; $this->mIsRedirect = false; $this->mRevIdFetched = 0; $this->mRedirectUrl = false; $this->mLatest = false; $this->mPreparedEdit = false; } /** * Note that getContent/loadContent do not follow redirects anymore. * If you need to fetch redirectable content easily, try * the shortcut in Article::followContent() * * @return Return the text of this revision */ public function getContent() { global $wgUser, $wgContLang, $wgOut, $wgMessageCache; wfProfileIn( __METHOD__ ); if( $this->getID() === 0 ) { # If this is a MediaWiki:x message, then load the messages # and return the message value for x. if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) { # If this is a system message, get the default text. list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) ); $wgMessageCache->loadAllMessages( $lang ); $text = wfMsgGetKey( $message, false, $lang, false ); if( wfEmptyMsg( $message, $text ) ) $text = ''; } else { $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' ); } wfProfileOut( __METHOD__ ); return $text; } else { $this->loadContent(); wfProfileOut( __METHOD__ ); return $this->mContent; } } /** * Get the text of the current revision. No side-effects... * * @return Return the text of the current revision */ public function getRawText() { // Check process cache for current revision if( $this->mContentLoaded && $this->mOldId == 0 ) { return $this->mContent; } $rev = Revision::newFromTitle( $this->mTitle ); $text = $rev ? $rev->getRawText() : false; return $text; } /** * This function returns the text of a section, specified by a number ($section). * A section is text under a heading like == Heading == or \Heading\, or * the first section before any such heading (section 0). * * If a section contains subsections, these are also returned. * * @param $text String: text to look in * @param $section Integer: section number * @return string text of the requested section * @deprecated */ public function getSection( $text, $section ) { global $wgParser; return $wgParser->getSection( $text, $section ); } /** * Get the text that needs to be saved in order to undo all revisions * between $undo and $undoafter. Revisions must belong to the same page, * must exist and must not be deleted * @param $undo Revision * @param $undoafter Revision Must be an earlier revision than $undo * @return mixed string on success, false on failure */ public function getUndoText( Revision $undo, Revision $undoafter = null ) { $undo_text = $undo->getText(); $undoafter_text = $undoafter->getText(); $cur_text = $this->getContent(); if ( $cur_text == $undo_text ) { # No use doing a merge if it's just a straight revert. return $undoafter_text; } $undone_text = ''; if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) return false; return $undone_text; } /** * @return int The oldid of the article that is to be shown, 0 for the * current revision */ public function getOldID() { if( is_null( $this->mOldId ) ) { $this->mOldId = $this->getOldIDFromRequest(); } return $this->mOldId; } /** * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect * * @return int The old id for the request */ public function getOldIDFromRequest() { global $wgRequest; $this->mRedirectUrl = false; $oldid = $wgRequest->getVal( 'oldid' ); if( isset( $oldid ) ) { $oldid = intval( $oldid ); if( $wgRequest->getVal( 'direction' ) == 'next' ) { $nextid = $this->mTitle->getNextRevisionID( $oldid ); if( $nextid ) { $oldid = $nextid; } else { $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' ); } } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) { $previd = $this->mTitle->getPreviousRevisionID( $oldid ); if( $previd ) { $oldid = $previd; } } } if( !$oldid ) { $oldid = 0; } return $oldid; } /** * Load the revision (including text) into this object */ function loadContent() { if( $this->mContentLoaded ) return; wfProfileIn( __METHOD__ ); # Query variables :P $oldid = $this->getOldID(); # Pre-fill content with error message so that if something # fails we'll have something telling us what we intended. $this->mOldId = $oldid; $this->fetchContent( $oldid ); wfProfileOut( __METHOD__ ); } /** * Fetch a page record with the given conditions * @param $dbr Database object * @param $conditions Array */ protected function pageData( $dbr, $conditions ) { $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_restrictions', 'page_counter', 'page_is_redirect', 'page_is_new', 'page_random', 'page_touched', 'page_latest', 'page_len', ); wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) ); $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__ ); wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) ); return $row ; } /** * @param $dbr Database object * @param $title Title object */ public function pageDataFromTitle( $dbr, $title ) { return $this->pageData( $dbr, array( 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ) ); } /** * @param $dbr Database * @param $id Integer */ protected function pageDataFromId( $dbr, $id ) { return $this->pageData( $dbr, array( 'page_id' => $id ) ); } /** * Set the general counter, title etc data loaded from * some source. * * @param $data Database row object or "fromdb" */ public function loadPageData( $data = 'fromdb' ) { if( $data === 'fromdb' ) { $dbr = wfGetDB( DB_MASTER ); $data = $this->pageDataFromId( $dbr, $this->getId() ); } $lc = LinkCache::singleton(); if( $data ) { $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect ); $this->mTitle->mArticleID = $data->page_id; # Old-fashioned restrictions $this->mTitle->loadRestrictions( $data->page_restrictions ); $this->mCounter = $data->page_counter; $this->mTouched = wfTimestamp( TS_MW, $data->page_touched ); $this->mIsRedirect = $data->page_is_redirect; $this->mLatest = $data->page_latest; } else { if( is_object( $this->mTitle ) ) { $lc->addBadLinkObj( $this->mTitle ); } $this->mTitle->mArticleID = 0; } $this->mDataLoaded = true; } /** * Get text of an article from database * Does *NOT* follow redirects. * @param $oldid Int: 0 for whatever the latest revision is * @return string */ function fetchContent( $oldid = 0 ) { if( $this->mContentLoaded ) { return $this->mContent; } $dbr = wfGetDB( DB_MASTER ); # Pre-fill content with error message so that if something # fails we'll have something telling us what we intended. $t = $this->mTitle->getPrefixedText(); $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : ''; $this->mContent = wfMsg( 'missing-article', $t, $d ) ; if( $oldid ) { $revision = Revision::newFromId( $oldid ); if( is_null( $revision ) ) { wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" ); return false; } $data = $this->pageDataFromId( $dbr, $revision->getPage() ); if( !$data ) { wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" ); return false; } $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title ); $this->loadPageData( $data ); } else { if( !$this->mDataLoaded ) { $data = $this->pageDataFromTitle( $dbr, $this->mTitle ); if( !$data ) { wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" ); return false; } $this->loadPageData( $data ); } $revision = Revision::newFromId( $this->mLatest ); if( is_null( $revision ) ) { wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" ); return false; } } // FIXME: Horrible, horrible! This content-loading interface just plain sucks. // We should instead work with the Revision object when we need it... $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed $this->mUser = $revision->getUser(); $this->mUserText = $revision->getUserText(); $this->mComment = $revision->getComment(); $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() ); $this->mRevIdFetched = $revision->getId(); $this->mContentLoaded = true; $this->mRevision =& $revision; wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ; return $this->mContent; } /** * Read/write accessor to select FOR UPDATE * * @param $x Mixed: FIXME */ public function forUpdate( $x = NULL ) { return wfSetVar( $this->mForUpdate, $x ); } /** * Get the database which should be used for reads * * @return Database * @deprecated - just call wfGetDB( DB_MASTER ) instead */ function getDB() { wfDeprecated( __METHOD__ ); return wfGetDB( DB_MASTER ); } /** * Get options for all SELECT statements * * @param $options Array: an optional options array which'll be appended to * the default * @return Array: options */ protected function getSelectOptions( $options = '' ) { if( $this->mForUpdate ) { if( is_array( $options ) ) { $options[] = 'FOR UPDATE'; } else { $options = 'FOR UPDATE'; } } return $options; } /** * @return int Page ID */ public function getID() { if( $this->mTitle ) { return $this->mTitle->getArticleID(); } else { return 0; } } /** * @return bool Whether or not the page exists in the database */ public function exists() { return $this->getId() > 0; } /** * Check if this page is something we're going to be showing * some sort of sensible content for. If we return false, page * views (plain action=view) will return an HTTP 404 response, * so spiders and robots can know they're following a bad link. * * @return bool */ public function hasViewableContent() { return $this->exists() || $this->mTitle->isAlwaysKnown(); } /** * @return int The view count for the page */ public function getCount() { if( -1 == $this->mCounter ) { $id = $this->getID(); if( $id == 0 ) { $this->mCounter = 0; } else { $dbr = wfGetDB( DB_SLAVE ); $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ), __METHOD__, $this->getSelectOptions() ); } } return $this->mCounter; } /** * Determine whether a page would be suitable for being counted as an * article in the site_stats table based on the title & its content * * @param $text String: text to analyze * @return bool */ public function isCountable( $text ) { global $wgUseCommaCount; $token = $wgUseCommaCount ? ',' : '[['; return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text); } /** * Tests if the article text represents a redirect * * @param $text String: FIXME * @return bool */ public function isRedirect( $text = false ) { if( $text === false ) { if( $this->mDataLoaded ) { return $this->mIsRedirect; } // Apparently loadPageData was never called $this->loadContent(); $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() ); } else { $titleObj = Title::newFromRedirect( $text ); } return $titleObj !== NULL; } /** * Returns true if the currently-referenced revision is the current edit * to this page (and it exists). * @return bool */ public function isCurrent() { # If no oldid, this is the current version. if( $this->getOldID() == 0 ) { return true; } return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent(); } /** * Loads everything except the text * This isn't necessary for all uses, so it's only done if needed. */ protected function loadLastEdit() { if( -1 != $this->mUser ) return; # New or non-existent articles have no user information $id = $this->getID(); if( 0 == $id ) return; $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id ); if( !is_null( $this->mLastRevision ) ) { $this->mUser = $this->mLastRevision->getUser(); $this->mUserText = $this->mLastRevision->getUserText(); $this->mTimestamp = $this->mLastRevision->getTimestamp(); $this->mComment = $this->mLastRevision->getComment(); $this->mMinorEdit = $this->mLastRevision->isMinor(); $this->mRevIdFetched = $this->mLastRevision->getId(); } } public function getTimestamp() { // Check if the field has been filled by ParserCache::get() if( !$this->mTimestamp ) { $this->loadLastEdit(); } return wfTimestamp(TS_MW, $this->mTimestamp); } public function getUser() { $this->loadLastEdit(); return $this->mUser; } public function getUserText() { $this->loadLastEdit(); return $this->mUserText; } public function getComment() { $this->loadLastEdit(); return $this->mComment; } public function getMinorEdit() { $this->loadLastEdit(); return $this->mMinorEdit; } /* Use this to fetch the rev ID used on page views */ public function getRevIdFetched() { $this->loadLastEdit(); return $this->mRevIdFetched; } /** * @param $limit Integer: default 0. * @param $offset Integer: default 0. */ public function getContributors($limit = 0, $offset = 0) { # XXX: this is expensive; cache this info somewhere. $contribs = array(); $dbr = wfGetDB( DB_SLAVE ); $revTable = $dbr->tableName( 'revision' ); $userTable = $dbr->tableName( 'user' ); $user = $this->getUser(); $pageId = $this->getId(); $hideBit = Revision::DELETED_USER; // username hidden? $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp FROM $revTable LEFT JOIN $userTable ON rev_user = user_id WHERE rev_page = $pageId AND rev_user != $user AND rev_deleted & $hideBit = 0 GROUP BY rev_user, rev_user_text, user_real_name ORDER BY timestamp DESC"; if($limit > 0) { $sql .= ' LIMIT '.$limit; } if($offset > 0) { $sql .= ' OFFSET '.$offset; } $sql .= ' '. $this->getSelectOptions(); $res = $dbr->query($sql, __METHOD__ ); return new UserArrayFromResult( $res ); } /** * This is the default action of the script: just view the page of * the given title. */ public function view() { global $wgUser, $wgOut, $wgRequest, $wgContLang; global $wgEnableParserCache, $wgStylePath, $wgParser; global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies; global $wgDefaultRobotPolicy; # Let the parser know if this is the printable version if( $wgOut->isPrintable() ) { $wgOut->parserOptions()->setIsPrintable( true ); } wfProfileIn( __METHOD__ ); # Get variables from query string $oldid = $this->getOldID(); # Try client and file cache if( $oldid === 0 && $this->checkTouched() ) { global $wgUseETag; if( $wgUseETag ) { $parserCache = ParserCache::singleton(); $wgOut->setETag( $parserCache->getETag($this, $wgOut->parserOptions()) ); } # Is is client cached? if( $wgOut->checkLastModified( $this->getTouched() ) ) { wfProfileOut( __METHOD__ ); return; # Try file cache } else if( $this->tryFileCache() ) { # tell wgOut that output is taken care of $wgOut->disable(); $this->viewUpdates(); wfProfileOut( __METHOD__ ); return; } } $ns = $this->mTitle->getNamespace(); # shortcut $sk = $wgUser->getSkin(); # getOldID may want us to redirect somewhere else if( $this->mRedirectUrl ) { $wgOut->redirect( $this->mRedirectUrl ); wfProfileOut( __METHOD__ ); return; } $diff = $wgRequest->getVal( 'diff' ); $rcid = $wgRequest->getVal( 'rcid' ); $rdfrom = $wgRequest->getVal( 'rdfrom' ); $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) ); $purge = $wgRequest->getVal( 'action' ) == 'purge'; $return404 = false; $wgOut->setArticleFlag( true ); # Discourage indexing of printable versions, but encourage following if( $wgOut->isPrintable() ) { $policy = 'noindex,follow'; } elseif( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) { $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()]; } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) { # Honour customised robot policies for this namespace $policy = $wgNamespaceRobotPolicies[$ns]; } else { $policy = $wgDefaultRobotPolicy; } $wgOut->setRobotPolicy( $policy ); # Allow admins to see deleted content if explicitly requested $delId = $diff ? $diff : $oldid; $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $delId ); # If we got diff and oldid in the query, we want to see a # diff page instead of the article. if( !is_null( $diff ) ) { $wgOut->setPageTitle( $this->mTitle->getPrefixedText() ); $htmldiff = $wgRequest->getVal( 'htmldiff' , false); $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide ); // DifferenceEngine directly fetched the revision: $this->mRevIdFetched = $de->mNewid; $de->showDiffPage( $diffOnly ); // Needed to get the page's current revision $this->loadPageData(); if( $diff == 0 || $diff == $this->mLatest ) { # Run view updates for current revision only $this->viewUpdates(); } wfProfileOut( __METHOD__ ); return; } if( $ns == NS_USER || $ns == NS_USER_TALK ) { # User/User_talk subpages are not modified. (bug 11443) if( !$this->mTitle->isSubpage() ) { $block = new Block(); if( $block->load( $this->mTitle->getBaseText() ) ) { $wgOut->setRobotpolicy( 'noindex,nofollow' ); } } } # Should the parser cache be used? $pcache = $this->useParserCache( $oldid ); wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" ); if( $wgUser->getOption( 'stubthreshold' ) ) { wfIncrStats( 'pcache_miss_stub' ); } $wasRedirected = false; if( isset( $this->mRedirectedFrom ) ) { // This is an internally redirected page view. // We'll need a backlink to the source page for navigation. if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) { $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' ); $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir ); $wgOut->setSubtitle( $s ); // Set the fragment if one was specified in the redirect if( strval( $this->mTitle->getFragment() ) != '' ) { $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() ); $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" ); } // Add a tag $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $this->mTitle->getLocalURL() ) ); $wasRedirected = true; } } elseif( !empty( $rdfrom ) ) { // This is an externally redirected view, from some other wiki. // If it was reported from a trusted site, supply a backlink. global $wgRedirectSources; if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) { $redir = $sk->makeExternalLink( $rdfrom, $rdfrom ); $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir ); $wgOut->setSubtitle( $s ); $wasRedirected = true; } } $outputDone = false; wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) ); if( $pcache && $wgOut->tryParserCache( $this ) ) { // Ensure that UI elements requiring revision ID have // the correct version information. $wgOut->setRevisionId( $this->mLatest ); $outputDone = true; } # Fetch content and check for errors if( !$outputDone ) { # If the article does not exist and was deleted, show the log if( $this->getID() == 0 ) { $this->showDeletionLog(); } $text = $this->getContent(); // For now, check also for ID until getContent actually returns // false for pages that do not exists if( $text === false || $this->getID() === 0 ) { # Failed to load, replace text with error message $t = $this->mTitle->getPrefixedText(); if( $oldid ) { $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid ); $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d ); // Always use page content for pages in the MediaWiki namespace // since it contains the default message } elseif ( $this->mTitle->getNamespace() != NS_MEDIAWIKI ) { $text = wfMsgExt( 'noarticletext', 'parsemag' ); } } # Non-existent pages if( $this->getID() === 0 ) { $wgOut->setRobotPolicy( 'noindex,nofollow' ); $text = "
\n$text\n
"; if( !$this->hasViewableContent() ) { // If there's no backing content, send a 404 Not Found // for better machine handling of broken links. $return404 = true; } } if( $return404 ) { $wgRequest->response()->header( "HTTP/1.x 404 Not Found" ); } # Another whitelist check in case oldid is altering the title if( !$this->mTitle->userCanRead() ) { $wgOut->loginToUse(); $wgOut->output(); $wgOut->disable(); wfProfileOut( __METHOD__ ); return; } # For ?curid=x urls, disallow indexing if( $wgRequest->getInt('curid') ) $wgOut->setRobotPolicy( 'noindex,follow' ); # We're looking at an old revision if( !empty( $oldid ) ) { $wgOut->setRobotPolicy( 'noindex,nofollow' ); if( is_null( $this->mRevision ) ) { // FIXME: This would be a nice place to load the 'no such page' text. } else { $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid ); # Allow admins to see deleted content if explicitly requested if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) { if( !$unhide || !$this->mRevision->userCan(Revision::DELETED_TEXT) ) { $wgOut->wrapWikiMsg( "\n", 'rev-deleted-text-permission' ); $wgOut->setPageTitle( $this->mTitle->getPrefixedText() ); wfProfileOut( __METHOD__ ); return; } else { $wgOut->wrapWikiMsg( "\n", 'rev-deleted-text-view' ); // and we are allowed to see... } } // Is this the current revision and otherwise cacheable? Try the parser cache... if( $oldid === $this->getLatest() && $this->useParserCache( false ) && $wgOut->tryParserCache( $this ) ) { $outputDone = true; } } } // Ensure that UI elements requiring revision ID have // the correct version information. $wgOut->setRevisionId( $this->getRevIdFetched() ); if( $outputDone ) { // do nothing... // Pages containing custom CSS or JavaScript get special treatment } else if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) { $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) ); // Give hooks a chance to customise the output if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) { // Wrap the whole lot in a
 and don't parse
					$m = array();
					preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
					$wgOut->addHTML( "
\n" );
					$wgOut->addHTML( htmlspecialchars( $this->mContent ) );
					$wgOut->addHTML( "\n
\n" ); } } else if( $rt = Title::newFromRedirectArray( $text ) ) { # get an array of redirect targets # Don't append the subtitle if this was an old revision $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) ); $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser)); $wgOut->addParserOutputNoText( $parseout ); } else if( $pcache ) { # Display content and save to parser cache $this->outputWikiText( $text ); } else { # Display content, don't attempt to save to parser cache # Don't show section-edit links on old revisions... this way lies madness. if( !$this->isCurrent() ) { $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false ); } # Display content and don't save to parser cache # With timing hack -- TS 2006-07-26 $time = -wfTime(); $this->outputWikiText( $text, false ); $time += wfTime(); # Timing hack if( $time > 3 ) { wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time, $this->mTitle->getPrefixedDBkey())); } if( !$this->isCurrent() ) { $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting ); } } } /* title may have been set from the cache */ $t = $wgOut->getPageTitle(); if( empty( $t ) ) { $wgOut->setPageTitle( $this->mTitle->getPrefixedText() ); # For the main page, overwrite the element with the con- # tents of 'pagetitle-view-mainpage' instead of the default (if # that's not empty). if( $this->mTitle->equals( Title::newMainPage() ) && wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) { $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) ); } } # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) { $wgOut->addWikiMsg('anontalkpagetext'); } # If we have been passed an &rcid= parameter, we want to give the user a # chance to mark this new article as patrolled. if( !empty($rcid) && $this->mTitle->exists() && $this->mTitle->quickUserCan('patrol') ) { $wgOut->addHTML( "<div class='patrollink'>" . wfMsgHtml( 'markaspatrolledlink', $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" ) ) . '</div>' ); } # Trackbacks if( $wgUseTrackbacks ) { $this->addTrackbacks(); } $this->viewUpdates(); wfProfileOut( __METHOD__ ); } protected function showDeletionLog() { global $wgUser, $wgOut; $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut ); $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() ); if( $pager->getNumRows() > 0 ) { $pager->mLimit = 10; $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' ); $wgOut->addWikiMsg( 'deleted-notice' ); $wgOut->addHTML( $loglist->beginLogEventsList() . $pager->getBody() . $loglist->endLogEventsList() ); if( $pager->getNumRows() > 10 ) { $wgOut->addHTML( $wgUser->getSkin()->link( SpecialPage::getTitleFor( 'Log' ), wfMsgHtml( 'deletelog-fulllog' ), array(), array( 'type' => 'delete', 'page' => $this->mTitle->getPrefixedText() ) ) ); } $wgOut->addHTML( '</div>' ); } } /* * Should the parser cache be used? */ protected function useParserCache( $oldid ) { global $wgUser, $wgEnableParserCache; return $wgEnableParserCache && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 && $this->exists() && empty( $oldid ) && !$this->mTitle->isCssOrJsPage() && !$this->mTitle->isCssJsSubpage(); } /** * View redirect * @param $target Title object or Array of destination(s) to redirect * @param $appendSubtitle Boolean [optional] * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence? */ public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) { global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser; # Display redirect if( !is_array( $target ) ) { $target = array( $target ); } $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr'; $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png'; $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png'; $alt2 = $wgContLang->isRTL() ? '←' : '→'; // should -> and <- be used instead of entities? if( $appendSubtitle ) { $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) ); } $sk = $wgUser->getSkin(); // the loop prepends the arrow image before the link, so the first case needs to be outside $title = array_shift( $target ); if( $forceKnown ) { $link = $sk->makeKnownLinkObj( $title, htmlspecialchars( $title->getFullText() ) ); } else { $link = $sk->makeLinkObj( $title, htmlspecialchars( $title->getFullText() ) ); } // automatically append redirect=no to each link, since most of them are redirect pages themselves foreach( $target as $rt ) { if( $forceKnown ) { $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />' . $sk->makeKnownLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) ); } else { $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />' . $sk->makeLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) ); } } return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' . '<span class="redirectText">'.$link.'</span>'; } public function addTrackbacks() { global $wgOut, $wgUser; $dbr = wfGetDB( DB_SLAVE ); $tbs = $dbr->select( 'trackbacks', array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'), array('tb_page' => $this->getID() ) ); if( !$dbr->numRows($tbs) ) return; $tbtext = ""; while( $o = $dbr->fetchObject($tbs) ) { $rmvtxt = ""; if( $wgUser->isAllowed( 'trackback' ) ) { $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) ); $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) ); } $tbtext .= "\n"; $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback', $o->tb_title, $o->tb_url, $o->tb_ex, $o->tb_name, $rmvtxt); } $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) ); $this->mTitle->invalidateCache(); } public function deletetrackback() { global $wgUser, $wgRequest, $wgOut, $wgTitle; if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) { $wgOut->addWikiMsg( 'sessionfailure' ); return; } $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser ); if( count($permission_errors) ) { $wgOut->showPermissionsErrorPage( $permission_errors ); return; } $db = wfGetDB( DB_MASTER ); $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) ); $wgOut->addWikiMsg( 'trackbackdeleteok' ); $this->mTitle->invalidateCache(); } public function render() { global $wgOut; $wgOut->setArticleBodyOnly(true); $this->view(); } /** * Handle action=purge */ public function purge() { global $wgUser, $wgRequest, $wgOut; if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) { if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) { $this->doPurge(); $this->view(); } } else { $action = htmlspecialchars( $wgRequest->getRequestURL() ); $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') ); $form = "<form method=\"post\" action=\"$action\">\n" . "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" . "</form>\n"; $top = wfMsgExt( 'confirm-purge-top', array('parse') ); $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') ); $wgOut->setPageTitle( $this->mTitle->getPrefixedText() ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $wgOut->addHTML( $top . $form . $bottom ); } } /** * Perform the actions of a page purging */ public function doPurge() { global $wgUseSquid; // Invalidate the cache $this->mTitle->invalidateCache(); if( $wgUseSquid ) { // Commit the transaction before the purge is sent $dbw = wfGetDB( DB_MASTER ); $dbw->immediateCommit(); // Send purge $update = SquidUpdate::newSimplePurge( $this->mTitle ); $update->doUpdate(); } if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) { global $wgMessageCache; if( $this->getID() == 0 ) { $text = false; } else { $text = $this->getRawText(); } $wgMessageCache->replace( $this->mTitle->getDBkey(), $text ); } } /** * Insert a new empty page record for this article. * This *must* be followed up by creating a revision * and running $this->updateToLatest( $rev_id ); * or else the record will be left in a funky state. * Best if all done inside a transaction. * * @param $dbw Database * @return int The newly created page_id key, or false if the title already existed * @private */ public function insertOn( $dbw ) { wfProfileIn( __METHOD__ ); $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' ); $dbw->insert( 'page', array( 'page_id' => $page_id, 'page_namespace' => $this->mTitle->getNamespace(), 'page_title' => $this->mTitle->getDBkey(), 'page_counter' => 0, 'page_restrictions' => '', 'page_is_redirect' => 0, # Will set this shortly... 'page_is_new' => 1, 'page_random' => wfRandom(), 'page_touched' => $dbw->timestamp(), 'page_latest' => 0, # Fill this in shortly... 'page_len' => 0, # Fill this in shortly... ), __METHOD__, 'IGNORE' ); $affected = $dbw->affectedRows(); if( $affected ) { $newid = $dbw->insertId(); $this->mTitle->resetArticleId( $newid ); } wfProfileOut( __METHOD__ ); return $affected ? $newid : false; } /** * Update the page record to point to a newly saved revision. * * @param $dbw Database object * @param $revision Revision: For ID number, and text used to set length and redirect status fields * @param $lastRevision Integer: if given, will not overwrite the page field * when different from the currently set value. * Giving 0 indicates the new page flag should be set * on. * @param $lastRevIsRedirect Boolean: if given, will optimize adding and * removing rows in redirect table. * @return bool true on success, false on failure * @private */ public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) { wfProfileIn( __METHOD__ ); $text = $revision->getText(); $rt = Title::newFromRedirect( $text ); $conditions = array( 'page_id' => $this->getId() ); if( !is_null( $lastRevision ) ) { # An extra check against threads stepping on each other $conditions['page_latest'] = $lastRevision; } $dbw->update( 'page', array( /* SET */ 'page_latest' => $revision->getId(), 'page_touched' => $dbw->timestamp(), 'page_is_new' => ($lastRevision === 0) ? 1 : 0, 'page_is_redirect' => $rt !== NULL ? 1 : 0, 'page_len' => strlen( $text ), ), $conditions, __METHOD__ ); $result = $dbw->affectedRows() != 0; if( $result ) { $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect ); } wfProfileOut( __METHOD__ ); return $result; } /** * Add row to the redirect table if this is a redirect, remove otherwise. * * @param $dbw Database * @param $redirectTitle a title object pointing to the redirect target, * or NULL if this is not a redirect * @param $lastRevIsRedirect If given, will optimize adding and * removing rows in redirect table. * @return bool true on success, false on failure * @private */ public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) { // Always update redirects (target link might have changed) // Update/Insert if we don't know if the last revision was a redirect or not // Delete if changing from redirect to non-redirect $isRedirect = !is_null($redirectTitle); if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) { wfProfileIn( __METHOD__ ); if( $isRedirect ) { // This title is a redirect, Add/Update row in the redirect table $set = array( /* SET */ 'rd_namespace' => $redirectTitle->getNamespace(), 'rd_title' => $redirectTitle->getDBkey(), 'rd_from' => $this->getId(), ); $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ ); } else { // This is not a redirect, remove row from redirect table $where = array( 'rd_from' => $this->getId() ); $dbw->delete( 'redirect', $where, __METHOD__); } if( $this->getTitle()->getNamespace() == NS_FILE ) { RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() ); } wfProfileOut( __METHOD__ ); return ( $dbw->affectedRows() != 0 ); } return true; } /** * If the given revision is newer than the currently set page_latest, * update the page record. Otherwise, do nothing. * * @param $dbw Database object * @param $revision Revision object */ public function updateIfNewerOn( &$dbw, $revision ) { wfProfileIn( __METHOD__ ); $row = $dbw->selectRow( array( 'revision', 'page' ), array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ), array( 'page_id' => $this->getId(), 'page_latest=rev_id' ), __METHOD__ ); if( $row ) { if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) { wfProfileOut( __METHOD__ ); return false; } $prev = $row->rev_id; $lastRevIsRedirect = (bool)$row->page_is_redirect; } else { # No or missing previous revision; mark the page as new $prev = 0; $lastRevIsRedirect = null; } $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect ); wfProfileOut( __METHOD__ ); return $ret; } /** * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...) * @return string Complete article text, or null if error */ public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) { wfProfileIn( __METHOD__ ); if( strval( $section ) == '' ) { // Whole-page edit; let the whole text through } else { if( is_null($edittime) ) { $rev = Revision::newFromTitle( $this->mTitle ); } else { $dbw = wfGetDB( DB_MASTER ); $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime ); } if( !$rev ) { wfDebug( "Article::replaceSection asked for bogus section (page: " . $this->getId() . "; section: $section; edittime: $edittime)\n" ); return null; } $oldtext = $rev->getText(); if( $section == 'new' ) { # Inserting a new section $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : ''; $text = strlen( trim( $oldtext ) ) > 0 ? "{$oldtext}\n\n{$subject}{$text}" : "{$subject}{$text}"; } else { # Replacing an existing section; roll out the big guns global $wgParser; $text = $wgParser->replaceSection( $oldtext, $section, $text ); } } wfProfileOut( __METHOD__ ); return $text; } /** * @deprecated use Article::doEdit() */ function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) { wfDeprecated( __METHOD__ ); $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY | ( $isminor ? EDIT_MINOR : 0 ) | ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) | ( $bot ? EDIT_FORCE_BOT : 0 ); # If this is a comment, add the summary as headline if( $comment && $summary != "" ) { $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text; } $this->doEdit( $text, $summary, $flags ); $dbw = wfGetDB( DB_MASTER ); if($watchthis) { if(!$this->mTitle->userIsWatching()) { $dbw->begin(); $this->doWatch(); $dbw->commit(); } } else { if( $this->mTitle->userIsWatching() ) { $dbw->begin(); $this->doUnwatch(); $dbw->commit(); } } $this->doRedirect( $this->isRedirect( $text ) ); } /** * @deprecated use Article::doEdit() */ function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) { wfDeprecated( __METHOD__ ); $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY | ( $minor ? EDIT_MINOR : 0 ) | ( $forceBot ? EDIT_FORCE_BOT : 0 ); $status = $this->doEdit( $text, $summary, $flags ); if( !$status->isOK() ) { return false; } $dbw = wfGetDB( DB_MASTER ); if( $watchthis ) { if(!$this->mTitle->userIsWatching()) { $dbw->begin(); $this->doWatch(); $dbw->commit(); } } else { if( $this->mTitle->userIsWatching() ) { $dbw->begin(); $this->doUnwatch(); $dbw->commit(); } } $extraQuery = ''; // Give extensions a chance to modify URL query on update wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) ); $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery ); return true; } /** * Article::doEdit() * * Change an existing article or create a new article. Updates RC and all necessary caches, * optionally via the deferred update array. * * $wgUser must be set before calling this function. * * @param $text String: new text * @param $summary String: edit summary * @param $flags Integer bitfield: * EDIT_NEW * Article is known or assumed to be non-existent, create a new one * EDIT_UPDATE * Article is known or assumed to be pre-existing, update it * EDIT_MINOR * Mark this edit minor, if the user is allowed to do so * EDIT_SUPPRESS_RC * Do not log the change in recentchanges * EDIT_FORCE_BOT * Mark the edit a "bot" edit regardless of user rights * EDIT_DEFER_UPDATES * Defer some of the updates until the end of index.php * EDIT_AUTOSUMMARY * Fill in blank summaries with generated text where possible * * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected. * If EDIT_UPDATE is specified and the article doesn't exist, the function will an * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an * edit-already-exists error will be returned. These two conditions are also possible with * auto-detection due to MediaWiki's performance-optimised locking strategy. * * @param $baseRevId the revision ID this edit was based off, if any * @param $user Optional user object, $wgUser will be used if not passed * * @return Status object. Possible errors: * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status * edit-gone-missing: In update mode, but the article didn't exist * edit-conflict: In update mode, the article changed unexpectedly * edit-no-change: Warning that the text was the same as before * edit-already-exists: In creation mode, but the article already exists * * Extensions may define additional errors. * * $return->value will contain an associative array with members as follows: * new: Boolean indicating if the function attempted to create a new article * revision: The revision object for the inserted revision, or null * * Compatibility note: this function previously returned a boolean value indicating success/failure */ public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries; # Low-level sanity check if( $this->mTitle->getText() == '' ) { throw new MWException( 'Something is trying to edit an article with an empty title' ); } wfProfileIn( __METHOD__ ); $user = is_null($user) ? $wgUser : $user; $status = Status::newGood( array() ); # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already $this->loadPageData(); if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) { $aid = $this->mTitle->getArticleID(); if( $aid ) { $flags |= EDIT_UPDATE; } else { $flags |= EDIT_NEW; } } if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary, $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) ) { wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" ); wfProfileOut( __METHOD__ ); if( $status->isOK() ) { $status->fatal( 'edit-hook-aborted'); } return $status; } # Silently ignore EDIT_MINOR if not allowed $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit'); $bot = $flags & EDIT_FORCE_BOT; $oldtext = $this->getRawText(); // current revision $oldsize = strlen( $oldtext ); # Provide autosummaries if one is not provided and autosummaries are enabled. if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) { $summary = $this->getAutosummary( $oldtext, $text, $flags ); } $editInfo = $this->prepareTextForEdit( $text ); $text = $editInfo->pst; $newsize = strlen( $text ); $dbw = wfGetDB( DB_MASTER ); $now = wfTimestampNow(); if( $flags & EDIT_UPDATE ) { # Update article, but only if changed. $status->value['new'] = false; # Make sure the revision is either completely inserted or not inserted at all if( !$wgDBtransactions ) { $userAbort = ignore_user_abort( true ); } $revisionId = 0; $changed = ( strcmp( $text, $oldtext ) != 0 ); if( $changed ) { $this->mGoodAdjustment = (int)$this->isCountable( $text ) - (int)$this->isCountable( $oldtext ); $this->mTotalAdjustment = 0; if( !$this->mLatest ) { # Article gone missing wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" ); $status->fatal( 'edit-gone-missing' ); wfProfileOut( __METHOD__ ); return $status; } $revision = new Revision( array( 'page' => $this->getId(), 'comment' => $summary, 'minor_edit' => $isminor, 'text' => $text, 'parent_id' => $this->mLatest, 'user' => $user->getId(), 'user_text' => $user->getName(), ) ); $dbw->begin(); $revisionId = $revision->insertOn( $dbw ); # Update page # # Note that we use $this->mLatest instead of fetching a value from the master DB # during the course of this function. This makes sure that EditPage can detect # edit conflicts reliably, either by $ok here, or by $article->getTimestamp() # before this function is called. A previous function used a separate query, this # creates a window where concurrent edits can cause an ignored edit conflict. $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest ); if( !$ok ) { /* Belated edit conflict! Run away!! */ $status->fatal( 'edit-conflict' ); # Delete the invalid revision if the DB is not transactional if( !$wgDBtransactions ) { $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ ); } $revisionId = 0; $dbw->rollback(); } else { global $wgUseRCPatrol; wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) ); # Update recentchanges if( !( $flags & EDIT_SUPPRESS_RC ) ) { # Mark as patrolled if the user can do so $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol'); # Add RC row to the DB $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary, $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize, $revisionId, $patrolled ); # Log auto-patrolled edits if( $patrolled ) { PatrolLog::record( $rc, true ); } } $user->incEditCount(); $dbw->commit(); } } else { $status->warning( 'edit-no-change' ); $revision = null; // Keep the same revision ID, but do some updates on it $revisionId = $this->getRevIdFetched(); // Update page_touched, this is usually implicit in the page update // Other cache updates are done in onArticleEdit() $this->mTitle->invalidateCache(); } if( !$wgDBtransactions ) { ignore_user_abort( $userAbort ); } // Now that ignore_user_abort is restored, we can respond to fatal errors if( !$status->isOK() ) { wfProfileOut( __METHOD__ ); return $status; } # Invalidate cache of this article and all pages using this article # as a template. Partly deferred. Article::onArticleEdit( $this->mTitle ); # Update links tables, site stats, etc. $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed ); } else { # Create new article $status->value['new'] = true; # Set statistics members # We work out if it's countable after PST to avoid counter drift # when articles are created with {{subst:}} $this->mGoodAdjustment = (int)$this->isCountable( $text ); $this->mTotalAdjustment = 1; $dbw->begin(); # Add the page record; stake our claim on this title! # This will return false if the article already exists $newid = $this->insertOn( $dbw ); if( $newid === false ) { $dbw->rollback(); $status->fatal( 'edit-already-exists' ); wfProfileOut( __METHOD__ ); return $status; } # Save the revision text... $revision = new Revision( array( 'page' => $newid, 'comment' => $summary, 'minor_edit' => $isminor, 'text' => $text, 'user' => $user->getId(), 'user_text' => $user->getName(), ) ); $revisionId = $revision->insertOn( $dbw ); $this->mTitle->resetArticleID( $newid ); # Update the page record with revision data $this->updateRevisionOn( $dbw, $revision, 0 ); wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) ); # Update recentchanges if( !( $flags & EDIT_SUPPRESS_RC ) ) { global $wgUseRCPatrol, $wgUseNPPatrol; # Mark as patrolled if the user can do so $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol'); # Add RC row to the DB $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot, '', strlen($text), $revisionId, $patrolled ); # Log auto-patrolled edits if( $patrolled ) { PatrolLog::record( $rc, true ); } } $user->incEditCount(); $dbw->commit(); # Update links, etc. $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true ); # Clear caches Article::onArticleCreate( $this->mTitle ); wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary, $flags & EDIT_MINOR, null, null, &$flags, $revision ) ); } # Do updates right now unless deferral was requested if( !( $flags & EDIT_DEFER_UPDATES ) ) { wfDoUpdates(); } // Return the new revision (or null) to the caller $status->value['revision'] = $revision; wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary, $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) ); wfProfileOut( __METHOD__ ); return $status; } /** * @deprecated wrapper for doRedirect */ public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) { wfDeprecated( __METHOD__ ); $this->doRedirect( $this->isRedirect( $text ), $sectionanchor ); } /** * Output a redirect back to the article. * This is typically used after an edit. * * @param $noRedir Boolean: add redirect=no * @param $sectionAnchor String: section to redirect to, including "#" * @param $extraQuery String: extra query params */ public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) { global $wgOut; if( $noRedir ) { $query = 'redirect=no'; if( $extraQuery ) $query .= "&$query"; } else { $query = $extraQuery; } $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor ); } /** * Mark this particular edit/page as patrolled */ public function markpatrolled() { global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser; $wgOut->setRobotPolicy( 'noindex,nofollow' ); # If we haven't been given an rc_id value, we can't do anything $rcid = (int) $wgRequest->getVal('rcid'); $rc = RecentChange::newFromId($rcid); if( is_null($rc) ) { $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' ); return; } #It would be nice to see where the user had actually come from, but for now just guess $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges'; $return = SpecialPage::getTitleFor( $returnto ); $dbw = wfGetDB( DB_MASTER ); $errors = $rc->doMarkPatrolled(); if( in_array(array('rcpatroldisabled'), $errors) ) { $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' ); return; } if( in_array(array('hookaborted'), $errors) ) { // The hook itself has handled any output return; } if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) { $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) ); $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' ); $wgOut->returnToMain( false, $return ); return; } if( !empty($errors) ) { $wgOut->showPermissionsErrorPage( $errors ); return; } # Inform the user $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) ); $wgOut->addWikiMsg( 'markedaspatrolledtext' ); $wgOut->returnToMain( false, $return ); } /** * User-interface handler for the "watch" action */ public function watch() { global $wgUser, $wgOut; if( $wgUser->isAnon() ) { $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' ); return; } if( wfReadOnly() ) { $wgOut->readOnlyPage(); return; } if( $this->doWatch() ) { $wgOut->setPagetitle( wfMsg( 'addedwatch' ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() ); } $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() ); } /** * Add this page to $wgUser's watchlist * @return bool true on successful watch operation */ public function doWatch() { global $wgUser; if( $wgUser->isAnon() ) { return false; } if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) { $wgUser->addWatch( $this->mTitle ); return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this)); } return false; } /** * User interface handler for the "unwatch" action. */ public function unwatch() { global $wgUser, $wgOut; if( $wgUser->isAnon() ) { $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' ); return; } if( wfReadOnly() ) { $wgOut->readOnlyPage(); return; } if( $this->doUnwatch() ) { $wgOut->setPagetitle( wfMsg( 'removedwatch' ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() ); } $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() ); } /** * Stop watching a page * @return bool true on successful unwatch */ public function doUnwatch() { global $wgUser; if( $wgUser->isAnon() ) { return false; } if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) { $wgUser->removeWatch( $this->mTitle ); return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this)); } return false; } /** * action=protect handler */ public function protect() { $form = new ProtectionForm( $this ); $form->execute(); } /** * action=unprotect handler (alias) */ public function unprotect() { $this->protect(); } /** * Update the article's restriction field, and leave a log entry. * * @param $limit Array: set of restriction keys * @param $reason String * @param &$cascade Integer. Set to false if cascading protection isn't allowed. * @param $expiry Array: per restriction type expiration * @return bool true on success */ public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) { global $wgUser, $wgRestrictionTypes, $wgContLang; $id = $this->mTitle->getArticleID(); if ( $id <= 0 ) { wfDebug( "updateRestrictions failed: $id <= 0\n" ); return false; } if ( wfReadOnly() ) { wfDebug( "updateRestrictions failed: read-only\n" ); return false; } if ( !$this->mTitle->userCan( 'protect' ) ) { wfDebug( "updateRestrictions failed: insufficient permissions\n" ); return false; } if( !$cascade ) { $cascade = false; } // Take this opportunity to purge out expired restrictions Title::purgeExpiredRestrictions(); # FIXME: Same limitations as described in ProtectionForm.php (line 37); # we expect a single selection, but the schema allows otherwise. $current = array(); $updated = Article::flattenRestrictions( $limit ); $changed = false; foreach( $wgRestrictionTypes as $action ) { if( isset( $expiry[$action] ) ) { # Get current restrictions on $action $aLimits = $this->mTitle->getRestrictions( $action ); $current[$action] = implode( '', $aLimits ); # Are any actual restrictions being dealt with here? $aRChanged = count($aLimits) || !empty($limit[$action]); # If something changed, we need to log it. Checking $aRChanged # assures that "unprotecting" a page that is not protected does # not log just because the expiry was "changed". if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) { $changed = true; } } } $current = Article::flattenRestrictions( $current ); $changed = ($changed || $current != $updated ); $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade); $protect = ( $updated != '' ); # If nothing's changed, do nothing if( $changed ) { if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) { $dbw = wfGetDB( DB_MASTER ); # Prepare a null revision to be added to the history $modified = $current != '' && $protect; if( $protect ) { $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle'; } else { $comment_type = 'unprotectedarticle'; } $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) ); # Only restrictions with the 'protect' right can cascade... # Otherwise, people who cannot normally protect can "protect" pages via transclusion $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' ); # The schema allows multiple restrictions if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction)) $cascade = false; $cascade_description = ''; if( $cascade ) { $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']'; } if( $reason ) $comment .= ": $reason"; $editComment = $comment; $encodedExpiry = array(); $protect_description = ''; foreach( $limit as $action => $restrictions ) { if ( !isset($expiry[$action]) ) $expiry[$action] = 'infinite'; $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw ); if( $restrictions != '' ) { $protect_description .= "[$action=$restrictions] ("; if( $encodedExpiry[$action] != 'infinity' ) { $protect_description .= wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry[$action], false, false ) , $wgContLang->date( $expiry[$action], false, false ) , $wgContLang->time( $expiry[$action], false, false ) ); } else { $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' ); } $protect_description .= ') '; } } $protect_description = trim($protect_description); if( $protect_description && $protect ) $editComment .= " ($protect_description)"; if( $cascade ) $editComment .= "$cascade_description"; # Update restrictions table foreach( $limit as $action => $restrictions ) { if($restrictions != '' ) { $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')), array( 'pr_page' => $id, 'pr_type' => $action, 'pr_level' => $restrictions, 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0, 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ ); } else { $dbw->delete( 'page_restrictions', array( 'pr_page' => $id, 'pr_type' => $action ), __METHOD__ ); } } # Insert a null revision $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true ); $nullRevId = $nullRevision->insertOn( $dbw ); $latest = $this->getLatest(); # Update page record $dbw->update( 'page', array( /* SET */ 'page_touched' => $dbw->timestamp(), 'page_restrictions' => '', 'page_latest' => $nullRevId ), array( /* WHERE */ 'page_id' => $id ), 'Article::protect' ); wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) ); wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) ); # Update the protection log $log = new LogPage( 'protect' ); if( $protect ) { $params = array($protect_description,$cascade ? 'cascade' : ''); $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params ); } else { $log->addEntry( 'unprotect', $this->mTitle, $reason ); } } # End hook } # End "changed" check return true; } /** * Take an array of page restrictions and flatten it to a string * suitable for insertion into the page_restrictions field. * @param $limit Array * @return String */ protected static function flattenRestrictions( $limit ) { if( !is_array( $limit ) ) { throw new MWException( 'Article::flattenRestrictions given non-array restriction set' ); } $bits = array(); ksort( $limit ); foreach( $limit as $action => $restrictions ) { if( $restrictions != '' ) { $bits[] = "$action=$restrictions"; } } return implode( ':', $bits ); } /** * Auto-generates a deletion reason * @param &$hasHistory Boolean: whether the page has a history */ public function generateReason( &$hasHistory ) { global $wgContLang; $dbw = wfGetDB( DB_MASTER ); // Get the last revision $rev = Revision::newFromTitle( $this->mTitle ); if( is_null( $rev ) ) return false; // Get the article's contents $contents = $rev->getText(); $blank = false; // If the page is blank, use the text from the previous revision, // which can only be blank if there's a move/import/protect dummy revision involved if( $contents == '' ) { $prev = $rev->getPrevious(); if( $prev ) { $contents = $prev->getText(); $blank = true; } } // Find out if there was only one contributor // Only scan the last 20 revisions $limit = 20; $res = $dbw->select( 'revision', 'rev_user_text', array( 'rev_page' => $this->getID() ), __METHOD__, array( 'LIMIT' => $limit ) ); if( $res === false ) // This page has no revisions, which is very weird return false; if( $res->numRows() > 1 ) $hasHistory = true; else $hasHistory = false; $row = $dbw->fetchObject( $res ); $onlyAuthor = $row->rev_user_text; // Try to find a second contributor foreach( $res as $row ) { if( $row->rev_user_text != $onlyAuthor ) { $onlyAuthor = false; break; } } $dbw->freeResult( $res ); // Generate the summary with a '$1' placeholder if( $blank ) { // The current revision is blank and the one before is also // blank. It's just not our lucky day $reason = wfMsgForContent( 'exbeforeblank', '$1' ); } else { if( $onlyAuthor ) $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor ); else $reason = wfMsgForContent( 'excontent', '$1' ); } if( $reason == '-' ) { // Allow these UI messages to be blanked out cleanly return ''; } // Replace newlines with spaces to prevent uglyness $contents = preg_replace( "/[\n\r]/", ' ', $contents ); // Calculate the maximum amount of chars to get // Max content length = max comment length - length of the comment (excl. $1) - '...' $maxLength = 255 - (strlen( $reason ) - 2) - 3; $contents = $wgContLang->truncate( $contents, $maxLength ); // Remove possible unfinished links $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents ); // Now replace the '$1' placeholder $reason = str_replace( '$1', $contents, $reason ); return $reason; } /* * UI entry point for page deletion */ public function delete() { global $wgUser, $wgOut, $wgRequest; $confirm = $wgRequest->wasPosted() && $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) ); $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' ); $this->DeleteReason = $wgRequest->getText( 'wpReason' ); $reason = $this->DeleteReasonList; if( $reason != 'other' && $this->DeleteReason != '' ) { // Entry from drop down menu + additional comment $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason; } elseif( $reason == 'other' ) { $reason = $this->DeleteReason; } # Flag to hide all contents of the archived revisions $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' ); # This code desperately needs to be totally rewritten # Read-only check... if( wfReadOnly() ) { $wgOut->readOnlyPage(); return; } # Check permissions $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser ); if( count( $permission_errors ) > 0 ) { $wgOut->showPermissionsErrorPage( $permission_errors ); return; } $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) ); # Better double-check that it hasn't been deleted yet! $dbw = wfGetDB( DB_MASTER ); $conds = $this->mTitle->pageCond(); $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ ); if( $latest === false ) { $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) ); $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) ); LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() ); return; } # Hack for big sites $bigHistory = $this->isBigDeletion(); if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) { global $wgLang, $wgDeleteRevisionsLimit; $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n", array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) ); return; } if( $confirm ) { $this->doDelete( $reason, $suppress ); if( $wgRequest->getCheck( 'wpWatch' ) ) { $this->doWatch(); } elseif( $this->mTitle->userIsWatching() ) { $this->doUnwatch(); } return; } // Generate deletion reason $hasHistory = false; if( !$reason ) $reason = $this->generateReason($hasHistory); // If the page has a history, insert a warning if( $hasHistory && !$confirm ) { $skin = $wgUser->getSkin(); $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' ); if( $bigHistory ) { global $wgLang, $wgDeleteRevisionsLimit; $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n", array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) ); } } return $this->confirmDelete( $reason ); } /** * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions */ public function isBigDeletion() { global $wgDeleteRevisionsLimit; if( $wgDeleteRevisionsLimit ) { $revCount = $this->estimateRevisionCount(); return $revCount > $wgDeleteRevisionsLimit; } return false; } /** * @return int approximate revision count */ public function estimateRevisionCount() { $dbr = wfGetDB( DB_SLAVE ); // For an exact count... //return $dbr->selectField( 'revision', 'COUNT(*)', // array( 'rev_page' => $this->getId() ), __METHOD__ ); return $dbr->estimateRowCount( 'revision', '*', array( 'rev_page' => $this->getId() ), __METHOD__ ); } /** * Get the last N authors * @param $num Integer: number of revisions to get * @param $revLatest String: the latest rev_id, selected from the master (optional) * @return array Array of authors, duplicates not removed */ public function getLastNAuthors( $num, $revLatest = 0 ) { wfProfileIn( __METHOD__ ); // First try the slave // If that doesn't have the latest revision, try the master $continue = 2; $db = wfGetDB( DB_SLAVE ); do { $res = $db->select( array( 'page', 'revision' ), array( 'rev_id', 'rev_user_text' ), array( 'page_namespace' => $this->mTitle->getNamespace(), 'page_title' => $this->mTitle->getDBkey(), 'rev_page = page_id' ), __METHOD__, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC', 'LIMIT' => $num ) ) ); if( !$res ) { wfProfileOut( __METHOD__ ); return array(); } $row = $db->fetchObject( $res ); if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) { $db = wfGetDB( DB_MASTER ); $continue--; } else { $continue = 0; } } while ( $continue ); $authors = array( $row->rev_user_text ); while ( $row = $db->fetchObject( $res ) ) { $authors[] = $row->rev_user_text; } wfProfileOut( __METHOD__ ); return $authors; } /** * Output deletion confirmation dialog * @param $reason String: prefilled reason */ public function confirmDelete( $reason ) { global $wgOut, $wgUser; wfDebug( "Article::confirmDelete\n" ); $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $wgOut->addWikiMsg( 'confirmdeletetext' ); if( $wgUser->isAllowed( 'suppressrevision' ) ) { $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"> <td></td> <td class='mw-input'>" . Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) . "</td> </tr>"; } else { $suppress = ''; } $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(); $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) . Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) . Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) . Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) . "<tr id=\"wpDeleteReasonListRow\"> <td class='mw-label'>" . Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) . "</td> <td class='mw-input'>" . Xml::listDropDown( 'wpDeleteReasonList', wfMsgForContent( 'deletereason-dropdown' ), wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) . "</td> </tr> <tr id=\"wpDeleteReasonRow\"> <td class='mw-label'>" . Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) . "</td> <td class='mw-input'>" . Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) . "</td> </tr> <tr> <td></td> <td class='mw-input'>" . Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) . "</td> </tr> $suppress <tr> <td></td> <td class='mw-submit'>" . Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) . "</td> </tr>" . Xml::closeElement( 'table' ) . Xml::closeElement( 'fieldset' ) . Xml::hidden( 'wpEditToken', $wgUser->editToken() ) . Xml::closeElement( 'form' ); if( $wgUser->isAllowed( 'editinterface' ) ) { $skin = $wgUser->getSkin(); $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) ); $form .= '<p class="mw-delete-editreasons">' . $link . '</p>'; } $wgOut->addHTML( $form ); LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() ); } /** * Perform a deletion and output success or failure messages */ public function doDelete( $reason, $suppress = false ) { global $wgOut, $wgUser; $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE ); $error = ''; if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) { if( $this->doDeleteArticle( $reason, $suppress, $id ) ) { $deleted = $this->mTitle->getPrefixedText(); $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]'; $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink ); $wgOut->returnToMain( false ); wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id)); } else { if( $error == '' ) { $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) ); $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) ); LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() ); } else { $wgOut->showFatalError( $error ); } } } } /** * Back-end article deletion * Deletes the article with database consistency, writes logs, purges caches * Returns success */ public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) { global $wgUseSquid, $wgDeferredUpdateList; global $wgUseTrackbacks; wfDebug( __METHOD__."\n" ); $dbw = wfGetDB( DB_MASTER ); $ns = $this->mTitle->getNamespace(); $t = $this->mTitle->getDBkey(); $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE ); if( $t == '' || $id == 0 ) { return false; } $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 ); array_push( $wgDeferredUpdateList, $u ); // Bitfields to further suppress the content if( $suppress ) { $bitfield = 0; // This should be 15... $bitfield |= Revision::DELETED_TEXT; $bitfield |= Revision::DELETED_COMMENT; $bitfield |= Revision::DELETED_USER; $bitfield |= Revision::DELETED_RESTRICTED; } else { $bitfield = 'rev_deleted'; } $dbw->begin(); // For now, shunt the revision data into the archive table. // Text is *not* removed from the text table; bulk storage // is left intact to avoid breaking block-compression or // immutable storage schemes. // // For backwards compatibility, note that some older archive // table entries will have ar_text and ar_flags fields still. // // In the future, we may keep revisions and mark them with // the rev_deleted field, which is reserved for this purpose. $dbw->insertSelect( 'archive', array( 'page', 'revision' ), array( 'ar_namespace' => 'page_namespace', 'ar_title' => 'page_title', 'ar_comment' => 'rev_comment', 'ar_user' => 'rev_user', 'ar_user_text' => 'rev_user_text', 'ar_timestamp' => 'rev_timestamp', 'ar_minor_edit' => 'rev_minor_edit', 'ar_rev_id' => 'rev_id', 'ar_text_id' => 'rev_text_id', 'ar_text' => '\'\'', // Be explicit to appease 'ar_flags' => '\'\'', // MySQL's "strict mode"... 'ar_len' => 'rev_len', 'ar_page_id' => 'page_id', 'ar_deleted' => $bitfield ), array( 'page_id' => $id, 'page_id = rev_page' ), __METHOD__ ); # Delete restrictions for it $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ ); # Now that it's safely backed up, delete it $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__); $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy if( !$ok ) { $dbw->rollback(); return false; } # Fix category table counts $cats = array(); $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ ); foreach( $res as $row ) { $cats []= $row->cl_to; } $this->updateCategoryCounts( array(), $cats ); # If using cascading deletes, we can skip some explicit deletes if( !$dbw->cascadingDeletes() ) { $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ ); if($wgUseTrackbacks) $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ ); # Delete outgoing links $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) ); $dbw->delete( 'imagelinks', array( 'il_from' => $id ) ); $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) ); $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) ); $dbw->delete( 'externallinks', array( 'el_from' => $id ) ); $dbw->delete( 'langlinks', array( 'll_from' => $id ) ); $dbw->delete( 'redirect', array( 'rd_from' => $id ) ); } # If using cleanup triggers, we can skip some manual deletes if( !$dbw->cleanupTriggers() ) { # Clean up recentchanges entries... $dbw->delete( 'recentchanges', array( 'rc_type != '.RC_LOG, 'rc_namespace' => $this->mTitle->getNamespace(), 'rc_title' => $this->mTitle->getDBKey() ), __METHOD__ ); $dbw->delete( 'recentchanges', array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ), __METHOD__ ); } # Clear caches Article::onArticleDelete( $this->mTitle ); # Clear the cached article id so the interface doesn't act like we exist $this->mTitle->resetArticleID( 0 ); # Log the deletion, if the page was suppressed, log it at Oversight instead $logtype = $suppress ? 'suppress' : 'delete'; $log = new LogPage( $logtype ); # Make sure logging got through $log->addEntry( 'delete', $this->mTitle, $reason, array() ); $dbw->commit(); return true; } /** * Roll back the most recent consecutive set of edits to a page * from the same user; fails if there are no eligible edits to * roll back to, e.g. user is the sole contributor. This function * performs permissions checks on $wgUser, then calls commitRollback() * to do the dirty work * * @param $fromP String: Name of the user whose edits to rollback. * @param $summary String: Custom summary. Set to default summary if empty. * @param $token String: Rollback token. * @param $bot Boolean: If true, mark all reverted edits as bot. * * @param $resultDetails Array: contains result-specific array of additional values * 'alreadyrolled' : 'current' (rev) * success : 'summary' (str), 'current' (rev), 'target' (rev) * * @return array of errors, each error formatted as * array(messagekey, param1, param2, ...). * On success, the array is empty. This array can also be passed to * OutputPage::showPermissionsErrorPage(). */ public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) { global $wgUser; $resultDetails = null; # Check permissions $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ); $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ); $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) ); if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) $errors[] = array( 'sessionfailure' ); if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) { $errors[] = array( 'actionthrottledtext' ); } # If there were errors, bail out now if( !empty( $errors ) ) return $errors; return $this->commitRollback($fromP, $summary, $bot, $resultDetails); } /** * Backend implementation of doRollback(), please refer there for parameter * and return value documentation * * NOTE: This function does NOT check ANY permissions, it just commits the * rollback to the DB Therefore, you should only call this function direct- * ly if you want to use custom permissions checks. If you don't, use * doRollback() instead. */ public function commitRollback($fromP, $summary, $bot, &$resultDetails) { global $wgUseRCPatrol, $wgUser, $wgLang; $dbw = wfGetDB( DB_MASTER ); if( wfReadOnly() ) { return array( array( 'readonlytext' ) ); } # Get the last editor $current = Revision::newFromTitle( $this->mTitle ); if( is_null( $current ) ) { # Something wrong... no page? return array(array('notanarticle')); } $from = str_replace( '_', ' ', $fromP ); if( $from != $current->getUserText() ) { $resultDetails = array( 'current' => $current ); return array(array('alreadyrolled', htmlspecialchars($this->mTitle->getPrefixedText()), htmlspecialchars($fromP), htmlspecialchars($current->getUserText()) )); } # Get the last edit not by this guy $user = intval( $current->getUser() ); $user_text = $dbw->addQuotes( $current->getUserText() ); $s = $dbw->selectRow( 'revision', array( 'rev_id', 'rev_timestamp', 'rev_deleted' ), array( 'rev_page' => $current->getPage(), "rev_user != {$user} OR rev_user_text != {$user_text}" ), __METHOD__, array( 'USE INDEX' => 'page_timestamp', 'ORDER BY' => 'rev_timestamp DESC' ) ); if( $s === false ) { # No one else ever edited this page return array(array('cantrollback')); } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) { # Only admins can see this text return array(array('notvisiblerev')); } $set = array(); if( $bot && $wgUser->isAllowed('markbotedits') ) { # Mark all reverted edits as bot $set['rc_bot'] = 1; } if( $wgUseRCPatrol ) { # Mark all reverted edits as patrolled $set['rc_patrolled'] = 1; } if( $set ) { $dbw->update( 'recentchanges', $set, array( /* WHERE */ 'rc_cur_id' => $current->getPage(), 'rc_user_text' => $current->getUserText(), "rc_timestamp > '{$s->rev_timestamp}'", ), __METHOD__ ); } # Generate the edit summary if necessary $target = Revision::newFromId( $s->rev_id ); if( empty( $summary ) ){ $summary = wfMsgForContent( 'revertpage' ); } # Allow the custom summary to use the same args as the default message $args = array( $target->getUserText(), $from, $s->rev_id, $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true), $current->getId(), $wgLang->timeanddate($current->getTimestamp()) ); $summary = wfMsgReplaceArgs( $summary, $args ); # Save $flags = EDIT_UPDATE; if( $wgUser->isAllowed('minoredit') ) $flags |= EDIT_MINOR; if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) ) $flags |= EDIT_FORCE_BOT; # Actually store the edit $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() ); if( !empty( $status->value['revision'] ) ) { $revId = $status->value['revision']->getId(); } else { $revId = false; } wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) ); $resultDetails = array( 'summary' => $summary, 'current' => $current, 'target' => $target, 'newid' => $revId ); return array(); } /** * User interface for rollback operations */ public function rollback() { global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol; $details = null; $result = $this->doRollback( $wgRequest->getVal( 'from' ), $wgRequest->getText( 'summary' ), $wgRequest->getVal( 'token' ), $wgRequest->getBool( 'bot' ), $details ); if( in_array( array( 'actionthrottledtext' ), $result ) ) { $wgOut->rateLimited(); return; } if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) { $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) ); $errArray = $result[0]; $errMsg = array_shift( $errArray ); $wgOut->addWikiMsgArray( $errMsg, $errArray ); if( isset( $details['current'] ) ){ $current = $details['current']; if( $current->getComment() != '' ) { $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) ); } } return; } # Display permissions errors before read-only message -- there's no # point in misleading the user into thinking the inability to rollback # is only temporary. if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) { # array_diff is completely broken for arrays of arrays, sigh. Re- # move any 'readonlytext' error manually. $out = array(); foreach( $result as $error ) { if( $error != array( 'readonlytext' ) ) { $out []= $error; } } $wgOut->showPermissionsErrorPage( $out ); return; } if( $result == array( array( 'readonlytext' ) ) ) { $wgOut->readOnlyPage(); return; } $current = $details['current']; $target = $details['target']; $newId = $details['newid']; $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() ) . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() ); $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() ) . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() ); $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) ); $wgOut->returnToMain( false, $this->mTitle ); if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) { $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true ); $de->showDiff( '', '' ); } } /** * Do standard deferred updates after page view */ public function viewUpdates() { global $wgDeferredUpdateList, $wgDisableCounters, $wgUser; # Don't update page view counters on views from bot users (bug 14044) if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) { Article::incViewCount( $this->getID() ); $u = new SiteStatsUpdate( 1, 0, 0 ); array_push( $wgDeferredUpdateList, $u ); } # Update newtalk / watchlist notification status $wgUser->clearNotification( $this->mTitle ); } /** * Prepare text which is about to be saved. * Returns a stdclass with source, pst and output members */ public function prepareTextForEdit( $text, $revid=null ) { if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) { // Already prepared return $this->mPreparedEdit; } global $wgParser; $edit = (object)array(); $edit->revid = $revid; $edit->newText = $text; $edit->pst = $this->preSaveTransform( $text ); $options = new ParserOptions; $options->setTidy( true ); $options->enableLimitReport(); $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid ); $edit->oldText = $this->getContent(); $this->mPreparedEdit = $edit; return $edit; } /** * Do standard deferred updates after page edit. * Update links tables, site stats, search index and message cache. * Purges pages that include this page if the text was changed here. * Every 100th edit, prune the recent changes table. * * @private * @param $text New text of the article * @param $summary Edit summary * @param $minoredit Minor edit * @param $timestamp_of_pagechange Timestamp associated with the page change * @param $newid rev_id value of the new revision * @param $changed Whether or not the content actually changed */ public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) { global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache; wfProfileIn( __METHOD__ ); # Parse the text # Be careful not to double-PST: $text is usually already PST-ed once if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) { wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" ); $editInfo = $this->prepareTextForEdit( $text, $newid ); } else { wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" ); $editInfo = $this->mPreparedEdit; } # Save it to the parser cache if( $wgEnableParserCache ) { $popts = new ParserOptions; $popts->setTidy( true ); $popts->enableLimitReport(); $parserCache = ParserCache::singleton(); $parserCache->save( $editInfo->output, $this, $popts ); } # Update the links tables $u = new LinksUpdate( $this->mTitle, $editInfo->output ); $u->doUpdate(); wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) ); if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) { if( 0 == mt_rand( 0, 99 ) ) { // Flush old entries from the `recentchanges` table; we do this on // random requests so as to avoid an increase in writes for no good reason global $wgRCMaxAge; $dbw = wfGetDB( DB_MASTER ); $cutoff = $dbw->timestamp( time() - $wgRCMaxAge ); $recentchanges = $dbw->tableName( 'recentchanges' ); $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'"; $dbw->query( $sql ); } } $id = $this->getID(); $title = $this->mTitle->getPrefixedDBkey(); $shortTitle = $this->mTitle->getDBkey(); if( 0 == $id ) { wfProfileOut( __METHOD__ ); return; } $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment ); array_push( $wgDeferredUpdateList, $u ); $u = new SearchUpdate( $id, $title, $text ); array_push( $wgDeferredUpdateList, $u ); # If this is another user's talk page, update newtalk # Don't do this if $changed = false otherwise some idiot can null-edit a # load of user talk pages and piss people off, nor if it's a minor edit # by a properly-flagged bot. if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) { if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) { $other = User::newFromName( $shortTitle, false ); if( !$other ) { wfDebug( __METHOD__.": invalid username\n" ); } elseif( User::isIP( $shortTitle ) ) { // An anonymous user $other->setNewtalk( true ); } elseif( $other->isLoggedIn() ) { $other->setNewtalk( true ); } else { wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" ); } } } if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) { $wgMessageCache->replace( $shortTitle, $text ); } wfProfileOut( __METHOD__ ); } /** * Perform article updates on a special page creation. * * @param $rev Revision object * * @todo This is a shitty interface function. Kill it and replace the * other shitty functions like editUpdates and such so it's not needed * anymore. */ public function createUpdates( $rev ) { $this->mGoodAdjustment = $this->isCountable( $rev->getText() ); $this->mTotalAdjustment = 1; $this->editUpdates( $rev->getText(), $rev->getComment(), $rev->isMinor(), wfTimestamp(), $rev->getId(), true ); } /** * Generate the navigation links when browsing through an article revisions * It shows the information as: * Revision as of \<date\>; view current revision * \<- Previous version | Next Version -\> * * @param $oldid String: revision ID of this article revision */ public function setOldSubtitle( $oldid = 0 ) { global $wgLang, $wgOut, $wgUser, $wgRequest; if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) { return; } $revision = Revision::newFromId( $oldid ); $current = ( $oldid == $this->mLatest ); $td = $wgLang->timeanddate( $this->mTimestamp, true ); $sk = $wgUser->getSkin(); $lnk = $current ? wfMsgHtml( 'currentrevisionlink' ) : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'currentrevisionlink' ) ); $curdiff = $current ? wfMsgHtml( 'diff' ) : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid ); $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ; $prevlink = $prev ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid ) : wfMsgHtml( 'previousrevision' ); $prevdiff = $prev ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid ) : wfMsgHtml( 'diff' ); $nextlink = $current ? wfMsgHtml( 'nextrevision' ) : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid ); $nextdiff = $current ? wfMsgHtml( 'diff' ) : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid ); $cdel=''; if( $wgUser->isAllowed( 'deleterevision' ) ) { $revdel = SpecialPage::getTitleFor( 'Revisiondelete' ); if( $revision->isCurrent() ) { // We don't handle top deleted edits too well $cdel = wfMsgHtml( 'rev-delundel' ); } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) { // If revision was hidden from sysops $cdel = wfMsgHtml( 'rev-delundel' ); } else { $cdel = $sk->makeKnownLinkObj( $revdel, wfMsgHtml('rev-delundel'), 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) . '&oldid=' . urlencode( $oldid ) ); // Bolden oversighted content if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) ) $cdel = "<strong>$cdel</strong>"; } $cdel = "(<small>$cdel</small>) "; } $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid ); # Show user links if allowed to see them. If hidden, then show them only if requested... $userlinks = $sk->revUserTools( $revision, !$unhide ); $m = wfMsg( 'revision-info-current' ); $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-' ? 'revision-info-current' : 'revision-info'; $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" . "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ), $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t"; $wgOut->setSubtitle( $r ); } /** * This function is called right before saving the wikitext, * so we can do things like signatures and links-in-context. * * @param $text String */ public function preSaveTransform( $text ) { global $wgParser, $wgUser; return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) ); } /* Caching functions */ /** * checkLastModified returns true if it has taken care of all * output to the client that is necessary for this request. * (that is, it has sent a cached version of the page) */ protected function tryFileCache() { static $called = false; if( $called ) { wfDebug( "Article::tryFileCache(): called twice!?\n" ); return false; } $called = true; if( $this->isFileCacheable() ) { $cache = new HTMLFileCache( $this->mTitle ); if( $cache->isFileCacheGood( $this->mTouched ) ) { wfDebug( "Article::tryFileCache(): about to load file\n" ); $cache->loadFromFileCache(); return true; } else { wfDebug( "Article::tryFileCache(): starting buffer\n" ); ob_start( array(&$cache, 'saveToFileCache' ) ); } } else { wfDebug( "Article::tryFileCache(): not cacheable\n" ); } return false; } /** * Check if the page can be cached * @return bool */ public function isFileCacheable() { $cacheable = false; if( HTMLFileCache::useFileCache() ) { $cacheable = $this->getID() && !$this->mRedirectedFrom; // Extension may have reason to disable file caching on some pages. if( $cacheable ) { $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) ); } } return $cacheable; } /** * Loads page_touched and returns a value indicating if it should be used * */ public function checkTouched() { if( !$this->mDataLoaded ) { $this->loadPageData(); } return !$this->mIsRedirect; } /** * Get the page_touched field */ public function getTouched() { # Ensure that page data has been loaded if( !$this->mDataLoaded ) { $this->loadPageData(); } return $this->mTouched; } /** * Get the page_latest field */ public function getLatest() { if( !$this->mDataLoaded ) { $this->loadPageData(); } return (int)$this->mLatest; } /** * Edit an article without doing all that other stuff * The article must already exist; link tables etc * are not updated, caches are not flushed. * * @param $text String: text submitted * @param $comment String: comment submitted * @param $minor Boolean: whereas it's a minor modification */ public function quickEdit( $text, $comment = '', $minor = 0 ) { wfProfileIn( __METHOD__ ); $dbw = wfGetDB( DB_MASTER ); $revision = new Revision( array( 'page' => $this->getId(), 'text' => $text, 'comment' => $comment, 'minor_edit' => $minor ? 1 : 0, ) ); $revision->insertOn( $dbw ); $this->updateRevisionOn( $dbw, $revision ); wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) ); wfProfileOut( __METHOD__ ); } /** * Used to increment the view counter * * @param $id Integer: article id */ public static function incViewCount( $id ) { $id = intval( $id ); global $wgHitcounterUpdateFreq, $wgDBtype; $dbw = wfGetDB( DB_MASTER ); $pageTable = $dbw->tableName( 'page' ); $hitcounterTable = $dbw->tableName( 'hitcounter' ); $acchitsTable = $dbw->tableName( 'acchits' ); if( $wgHitcounterUpdateFreq <= 1 ) { $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" ); return; } # Not important enough to warrant an error page in case of failure $oldignore = $dbw->ignoreErrors( true ); $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" ); $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 ); if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){ # Most of the time (or on SQL errors), skip row count check $dbw->ignoreErrors( $oldignore ); return; } $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable"); $row = $dbw->fetchObject( $res ); $rown = intval( $row->n ); if( $rown >= $wgHitcounterUpdateFreq ){ wfProfileIn( 'Article::incViewCount-collect' ); $old_user_abort = ignore_user_abort( true ); if($wgDBtype == 'mysql') $dbw->query("LOCK TABLES $hitcounterTable WRITE"); $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : ''; $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ". "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ". 'GROUP BY hc_id'); $dbw->query("DELETE FROM $hitcounterTable"); if($wgDBtype == 'mysql') { $dbw->query('UNLOCK TABLES'); $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ". 'WHERE page_id = hc_id'); } else { $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ". "FROM $acchitsTable WHERE page_id = hc_id"); } $dbw->query("DROP TABLE $acchitsTable"); ignore_user_abort( $old_user_abort ); wfProfileOut( 'Article::incViewCount-collect' ); } $dbw->ignoreErrors( $oldignore ); } /**#@+ * The onArticle*() functions are supposed to be a kind of hooks * which should be called whenever any of the specified actions * are done. * * This is a good place to put code to clear caches, for instance. * * This is called on page move and undelete, as well as edit * * @param $title a title object */ public static function onArticleCreate( $title ) { # Update existence markers on article/talk tabs... if( $title->isTalkPage() ) { $other = $title->getSubjectPage(); } else { $other = $title->getTalkPage(); } $other->invalidateCache(); $other->purgeSquid(); $title->touchLinks(); $title->purgeSquid(); $title->deleteTitleProtection(); } public static function onArticleDelete( $title ) { global $wgMessageCache; # Update existence markers on article/talk tabs... if( $title->isTalkPage() ) { $other = $title->getSubjectPage(); } else { $other = $title->getTalkPage(); } $other->invalidateCache(); $other->purgeSquid(); $title->touchLinks(); $title->purgeSquid(); # File cache HTMLFileCache::clearFileCache( $title ); # Messages if( $title->getNamespace() == NS_MEDIAWIKI ) { $wgMessageCache->replace( $title->getDBkey(), false ); } # Images if( $title->getNamespace() == NS_FILE ) { $update = new HTMLCacheUpdate( $title, 'imagelinks' ); $update->doUpdate(); } # User talk pages if( $title->getNamespace() == NS_USER_TALK ) { $user = User::newFromName( $title->getText(), false ); $user->setNewtalk( false ); } # Image redirects RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title ); } /** * Purge caches on page update etc */ public static function onArticleEdit( $title, $flags = '' ) { global $wgDeferredUpdateList; // Invalidate caches of articles which include this page $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' ); // Invalidate the caches of all pages which redirect here $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' ); # Purge squid for this page only $title->purgeSquid(); # Clear file cache for this page only HTMLFileCache::clearFileCache( $title ); } /**#@-*/ /** * Overriden by ImagePage class, only present here to avoid a fatal error * Called for ?action=revert */ public function revert() { global $wgOut; $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' ); } /** * Info about this page * Called for ?action=info when $wgAllowPageInfo is on. */ public function info() { global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser; if( !$wgAllowPageInfo ) { $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' ); return; } $page = $this->mTitle->getSubjectPage(); $wgOut->setPagetitle( $page->getPrefixedText() ); $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) ); $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) ); if( !$this->mTitle->exists() ) { $wgOut->addHTML( '<div class="noarticletext">' ); if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) { // This doesn't quite make sense; the user is asking for // information about the _page_, not the message... -- RC $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) ); } else { $msg = $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon'; $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) ); } $wgOut->addHTML( '</div>' ); } else { $dbr = wfGetDB( DB_SLAVE ); $wl_clause = array( 'wl_title' => $page->getDBkey(), 'wl_namespace' => $page->getNamespace() ); $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, __METHOD__, $this->getSelectOptions() ); $pageInfo = $this->pageCountInfo( $page ); $talkInfo = $this->pageCountInfo( $page->getTalkPage() ); $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' ); $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>'); if( $talkInfo ) { $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>'); } $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' ); if( $talkInfo ) { $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' ); } $wgOut->addHTML( '</ul>' ); } } /** * Return the total number of edits and number of unique editors * on a given page. If page does not exist, returns false. * * @param $title Title object * @return array */ protected function pageCountInfo( $title ) { $id = $title->getArticleId(); if( $id == 0 ) { return false; } $dbr = wfGetDB( DB_SLAVE ); $rev_clause = array( 'rev_page' => $id ); $edits = $dbr->selectField( 'revision', 'COUNT(rev_page)', $rev_clause, __METHOD__, $this->getSelectOptions() ); $authors = $dbr->selectField( 'revision', 'COUNT(DISTINCT rev_user_text)', $rev_clause, __METHOD__, $this->getSelectOptions() ); return array( 'edits' => $edits, 'authors' => $authors ); } /** * Return a list of templates used by this article. * Uses the templatelinks table * * @return Array of Title objects */ public function getUsedTemplates() { $result = array(); $id = $this->mTitle->getArticleID(); if( $id == 0 ) { return array(); } $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( array( 'templatelinks' ), array( 'tl_namespace', 'tl_title' ), array( 'tl_from' => $id ), __METHOD__ ); if( $res !== false ) { foreach( $res as $row ) { $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title ); } } $dbr->freeResult( $res ); return $result; } /** * Returns a list of hidden categories this page is a member of. * Uses the page_props and categorylinks tables. * * @return Array of Title objects */ public function getHiddenCategories() { $result = array(); $id = $this->mTitle->getArticleID(); if( $id == 0 ) { return array(); } $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ), array( 'cl_to' ), array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat', 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'), __METHOD__ ); if( $res !== false ) { foreach( $res as $row ) { $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to ); } } $dbr->freeResult( $res ); return $result; } /** * Return an applicable autosummary if one exists for the given edit. * @param $oldtext String: the previous text of the page. * @param $newtext String: The submitted text of the page. * @param $flags Bitmask: a bitmask of flags submitted for the edit. * @return string An appropriate autosummary, or an empty string. */ public static function getAutosummary( $oldtext, $newtext, $flags ) { # Decide what kind of autosummary is needed. # Redirect autosummaries $ot = Title::newFromRedirect( $oldtext ); $rt = Title::newFromRedirect( $newtext ); if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) { return wfMsgForContent( 'autoredircomment', $rt->getFullText() ); } # New page autosummaries if( $flags & EDIT_NEW && strlen( $newtext ) ) { # If they're making a new article, give its text, truncated, in the summary. global $wgContLang; $truncatedtext = $wgContLang->truncate( str_replace("\n", ' ', $newtext), max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) ); return wfMsgForContent( 'autosumm-new', $truncatedtext ); } # Blanking autosummaries if( $oldtext != '' && $newtext == '' ) { return wfMsgForContent( 'autosumm-blank' ); } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) { # Removing more than 90% of the article global $wgContLang; $truncatedtext = $wgContLang->truncate( $newtext, max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) ); return wfMsgForContent( 'autosumm-replace', $truncatedtext ); } # If we reach this point, there's no applicable autosummary for our case, so our # autosummary is empty. return ''; } /** * Add the primary page-view wikitext to the output buffer * Saves the text into the parser cache if possible. * Updates templatelinks if it is out of date. * * @param $text String * @param $cache Boolean */ public function outputWikiText( $text, $cache = true ) { global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache; $popts = $wgOut->parserOptions(); $popts->setTidy(true); $popts->enableLimitReport(); $parserOutput = $wgParser->parse( $text, $this->mTitle, $popts, true, true, $this->getRevIdFetched() ); $popts->setTidy(false); $popts->enableLimitReport( false ); if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) { $parserCache = ParserCache::singleton(); $parserCache->save( $parserOutput, $this, $popts ); } // Make sure file cache is not used on uncacheable content. // Output that has magic words in it can still use the parser cache // (if enabled), though it will generally expire sooner. if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) { $wgUseFileCache = false; } if( $this->isCurrent() && !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) { // templatelinks table may have become out of sync, // especially if using variable-based transclusions. // For paranoia, check if things have changed and if // so apply updates to the database. This will ensure // that cascaded protections apply as soon as the changes // are visible. # Get templates from templatelinks $id = $this->mTitle->getArticleID(); $tlTemplates = array(); $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( array( 'templatelinks' ), array( 'tl_namespace', 'tl_title' ), array( 'tl_from' => $id ), __METHOD__ ); global $wgContLang; foreach( $res as $row ) { $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true; } # Get templates from parser output. $poTemplates = array(); foreach ( $parserOutput->getTemplates() as $ns => $templates ) { foreach ( $templates as $dbk => $id ) { $key = $row->tl_namespace . ':'. $row->tl_title; $poTemplates["$ns:$dbk"] = true; } } # Get the diff # Note that we simulate array_diff_key in PHP <5.0.x $templates_diff = array_diff_key( $poTemplates, $tlTemplates ); if( count( $templates_diff ) > 0 ) { # Whee, link updates time. $u = new LinksUpdate( $this->mTitle, $parserOutput, false ); $u->doUpdate(); } } $wgOut->addParserOutput( $parserOutput ); } /** * Update all the appropriate counts in the category table, given that * we've added the categories $added and deleted the categories $deleted. * * @param $added array The names of categories that were added * @param $deleted array The names of categories that were deleted * @return null */ public function updateCategoryCounts( $added, $deleted ) { $ns = $this->mTitle->getNamespace(); $dbw = wfGetDB( DB_MASTER ); # First make sure the rows exist. If one of the "deleted" ones didn't # exist, we might legitimately not create it, but it's simpler to just # create it and then give it a negative value, since the value is bogus # anyway. # # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE. $insertCats = array_merge( $added, $deleted ); if( !$insertCats ) { # Okay, nothing to do return; } $insertRows = array(); foreach( $insertCats as $cat ) { $insertRows[] = array( 'cat_title' => $cat ); } $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' ); $addFields = array( 'cat_pages = cat_pages + 1' ); $removeFields = array( 'cat_pages = cat_pages - 1' ); if( $ns == NS_CATEGORY ) { $addFields[] = 'cat_subcats = cat_subcats + 1'; $removeFields[] = 'cat_subcats = cat_subcats - 1'; } elseif( $ns == NS_FILE ) { $addFields[] = 'cat_files = cat_files + 1'; $removeFields[] = 'cat_files = cat_files - 1'; } if( $added ) { $dbw->update( 'category', $addFields, array( 'cat_title' => $added ), __METHOD__ ); } if( $deleted ) { $dbw->update( 'category', $removeFields, array( 'cat_title' => $deleted ), __METHOD__ ); } } /** * Create a new Title from text, such as what one would find in a link. De- * codes any HTML entities in the text. * * @param $text string The link text; spaces, prefixes, and an * initial ':' indicating the main namespace are accepted. * @param $defaultNamespace int The namespace to use if none is speci- * fied by a prefix. If you want to force a specific namespace even if * $text might begin with a namespace prefix, use makeTitle() or * makeTitleSafe(). * @return Title The new object, or null on an error. */ public static function newFromText( $text, $defaultNamespace = NS_MAIN ) { if( is_object( $text ) ) { throw new MWException( 'Title::newFromText given an object' ); } /** * Wiki pages often contain multiple links to the same page. * Title normalization and parsing can become expensive on * pages with many links, so we can save a little time by * caching them. * * In theory these are value objects and won't get changed... */ if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) { return Title::$titleCache[$text]; } /** * Convert things like é ā or 〗 into real text... */ $filteredText = Sanitizer::decodeCharReferences( $text ); $t = new Title(); $t->mDbkeyform = str_replace( ' ', '_', $filteredText ); $t->mDefaultNamespace = $defaultNamespace; static $cachedcount = 0 ; if( $t->secureAndSplit() ) { if( $defaultNamespace == NS_MAIN ) { if( $cachedcount >= self::CACHE_MAX ) { # Avoid memory leaks on mass operations... Title::$titleCache = array(); $cachedcount=0; } $cachedcount++; Title::$titleCache[$text] =& $t; } return $t; } else { $ret = NULL; return $ret; } } /** * Create a new Title from URL-encoded text. Ensures that * the given title's length does not exceed the maximum. * @param $url \type{\string} the title, as might be taken from a URL * @return \type{Title} the new object, or NULL on an error */ public static function newFromURL( $url ) { global $wgLegalTitleChars; $t = new Title(); # For compatibility with old buggy URLs. "+" is usually not valid in titles, # but some URLs used it as a space replacement and they still come # from some external search tools. if ( strpos( $wgLegalTitleChars, '+' ) === false ) { $url = str_replace( '+', ' ', $url ); } $t->mDbkeyform = str_replace( ' ', '_', $url ); if( $t->secureAndSplit() ) { return $t; } else { return NULL; } } /** * Create a new Title from an article ID * * @todo This is inefficiently implemented, the page row is requested * but not used for anything else * * @param $id \type{\int} the page_id corresponding to the Title to create * @param $flags \type{\int} use GAID_FOR_UPDATE to use master * @return \type{Title} the new object, or NULL on an error */ public static function newFromID( $id, $flags = 0 ) { $fname = 'Title::newFromID'; $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ), array( 'page_id' => $id ), $fname ); if ( $row !== false ) { $title = Title::makeTitle( $row->page_namespace, $row->page_title ); } else { $title = NULL; } return $title; } /** * Make an array of titles from an array of IDs * @param $ids \type{\arrayof{\int}} Array of IDs * @return \type{\arrayof{Title}} Array of Titles */ public static function newFromIDs( $ids ) { if ( !count( $ids ) ) { return array(); } $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ), 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ ); $titles = array(); foreach( $res as $row ) { $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title ); } return $titles; } /** * Make a Title object from a DB row * @param $row \type{Row} (needs at least page_title,page_namespace) * @return \type{Title} corresponding Title */ public static function newFromRow( $row ) { $t = self::makeTitle( $row->page_namespace, $row->page_title ); $t->mArticleID = isset($row->page_id) ? intval($row->page_id) : -1; $t->mLength = isset($row->page_len) ? intval($row->page_len) : -1; $t->mRedirect = isset($row->page_is_redirect) ? (bool)$row->page_is_redirect : NULL; $t->mLatestID = isset($row->page_latest) ? $row->page_latest : false; return $t; } /** * Create a new Title from a namespace index and a DB key. * It's assumed that $ns and $title are *valid*, for instance when * they came directly from the database or a special page name. * For convenience, spaces are converted to underscores so that * eg user_text fields can be used directly. * * @param $ns \type{\int} the namespace of the article * @param $title \type{\string} the unprefixed database key form * @param $fragment \type{\string} The link fragment (after the "#") * @return \type{Title} the new object */ public static function &makeTitle( $ns, $title, $fragment = '' ) { $t = new Title(); $t->mInterwiki = ''; $t->mFragment = $fragment; $t->mNamespace = $ns = intval( $ns ); $t->mDbkeyform = str_replace( ' ', '_', $title ); $t->mArticleID = ( $ns >= 0 ) ? -1 : 0; $t->mUrlform = wfUrlencode( $t->mDbkeyform ); $t->mTextform = str_replace( '_', ' ', $title ); return $t; } /** * Create a new Title from a namespace index and a DB key. * The parameters will be checked for validity, which is a bit slower * than makeTitle() but safer for user-provided data. * * @param $ns \type{\int} the namespace of the article * @param $title \type{\string} the database key form * @param $fragment \type{\string} The link fragment (after the "#") * @return \type{Title} the new object, or NULL on an error */ public static function makeTitleSafe( $ns, $title, $fragment = '' ) { $t = new Title(); $t->mDbkeyform = Title::makeName( $ns, $title, $fragment ); if( $t->secureAndSplit() ) { return $t; } else { return NULL; } } /** * Create a new Title for the Main Page * @return \type{Title} the new object */ public static function newMainPage() { $title = Title::newFromText( wfMsgForContent( 'mainpage' ) ); // Don't give fatal errors if the message is broken if ( !$title ) { $title = Title::newFromText( 'Main Page' ); } return $title; } /** * Extract a redirect destination from a string and return the * Title, or null if the text doesn't contain a valid redirect * This will only return the very next target, useful for * the redirect table and other checks that don't need full recursion * * @param $text \type{\string} Text with possible redirect * @return \type{Title} The corresponding Title */ public static function newFromRedirect( $text ) { return self::newFromRedirectInternal( $text ); } /** * Extract a redirect destination from a string and return the * Title, or null if the text doesn't contain a valid redirect * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit * in order to provide (hopefully) the Title of the final destination instead of another redirect * * @param $text \type{\string} Text with possible redirect * @return \type{Title} The corresponding Title */ public static function newFromRedirectRecurse( $text ) { $titles = self::newFromRedirectArray( $text ); return $titles ? array_pop( $titles ) : null; } /** * Extract a redirect destination from a string and return an * array of Titles, or null if the text doesn't contain a valid redirect * The last element in the array is the final destination after all redirects * have been resolved (up to $wgMaxRedirects times) * * @param $text \type{\string} Text with possible redirect * @return \type{\array} Array of Titles, with the destination last */ public static function newFromRedirectArray( $text ) { global $wgMaxRedirects; // are redirects disabled? if( $wgMaxRedirects < 1 ) return null; $title = self::newFromRedirectInternal( $text ); if( is_null( $title ) ) return null; // recursive check to follow double redirects $recurse = $wgMaxRedirects; $titles = array( $title ); while( --$recurse > 0 ) { if( $title->isRedirect() ) { $article = new Article( $title, 0 ); $newtitle = $article->getRedirectTarget(); } else { break; } // Redirects to some special pages are not permitted if( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) { // the new title passes the checks, so make that our current title so that further recursion can be checked $title = $newtitle; $titles[] = $newtitle; } else { break; } } return $titles; } /** * Really extract the redirect destination * Do not call this function directly, use one of the newFromRedirect* functions above * * @param $text \type{\string} Text with possible redirect * @return \type{Title} The corresponding Title */ protected static function newFromRedirectInternal( $text ) { $redir = MagicWord::get( 'redirect' ); $text = trim($text); if( $redir->matchStartAndRemove( $text ) ) { // Extract the first link and see if it's usable // Ensure that it really does come directly after #REDIRECT // Some older redirects included a colon, so don't freak about that! $m = array(); if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) { // Strip preceding colon used to "escape" categories, etc. // and URL-decode links if( strpos( $m[1], '%' ) !== false ) { // Match behavior of inline link parsing here; // don't interpret + as " " most of the time! // It might be safe to just use rawurldecode instead, though. $m[1] = urldecode( ltrim( $m[1], ':' ) ); } $title = Title::newFromText( $m[1] ); // If the title is a redirect to bad special pages or is invalid, return null if( !$title instanceof Title || !$title->isValidRedirectTarget() ) { return null; } return $title; } } return null; } #---------------------------------------------------------------------------- # Static functions #---------------------------------------------------------------------------- /** * Get the prefixed DB key associated with an ID * @param $id \type{\int} the page_id of the article * @return \type{Title} an object representing the article, or NULL * if no such article was found */ public static function nameOf( $id ) { $dbr = wfGetDB( DB_SLAVE ); $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__ ); if ( $s === false ) { return NULL; } $n = self::makeName( $s->page_namespace, $s->page_title ); return $n; } /** * Get a regex character class describing the legal characters in a link * @return \type{\string} the list of characters, not delimited */ public static function legalChars() { global $wgLegalTitleChars; return $wgLegalTitleChars; } /** * Get a string representation of a title suitable for * including in a search index * * @param $ns \type{\int} a namespace index * @param $title \type{\string} text-form main part * @return \type{\string} a stripped-down title string ready for the * search index */ public static function indexTitle( $ns, $title ) { global $wgContLang; $lc = SearchEngine::legalSearchChars() . '&#;'; $t = $wgContLang->stripForSearch( $title ); $t = preg_replace( "/[^{$lc}]+/", ' ', $t ); $t = $wgContLang->lc( $t ); # Handle 's, s' $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t ); $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t ); $t = preg_replace( "/\\s+/", ' ', $t ); if ( $ns == NS_FILE ) { $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t ); } return trim( $t ); } /* * Make a prefixed DB key from a DB key and a namespace index * @param $ns \type{\int} numerical representation of the namespace * @param $title \type{\string} the DB key form the title * @param $fragment \type{\string} The link fragment (after the "#") * @return \type{\string} the prefixed form of the title */ public static function makeName( $ns, $title, $fragment = '' ) { global $wgContLang; $namespace = $wgContLang->getNsText( $ns ); $name = $namespace == '' ? $title : "$namespace:$title"; if ( strval( $fragment ) != '' ) { $name .= '#' . $fragment; } return $name; } /** * Returns the URL associated with an interwiki prefix * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall") * @return \type{\string} the associated URL, containing "$1", * which should be replaced by an article title * @static (arguably) * @deprecated See Interwiki class */ public function getInterwikiLink( $key ) { return Interwiki::fetch( $key )->getURL( ); } /** * Determine whether the object refers to a page within * this project. * * @return \type{\bool} TRUE if this is an in-project interwiki link * or a wikilink, FALSE otherwise */ public function isLocal() { if ( $this->mInterwiki != '' ) { return Interwiki::fetch( $this->mInterwiki )->isLocal(); } else { return true; } } /** * Determine whether the object refers to a page within * this project and is transcludable. * * @return \type{\bool} TRUE if this is transcludable */ public function isTrans() { if ($this->mInterwiki == '') return false; return Interwiki::fetch( $this->mInterwiki )->isTranscludable(); } /** * Escape a text fragment, say from a link, for a URL */ static function escapeFragmentForURL( $fragment ) { global $wgEnforceHtmlIds; # Note that we don't urlencode the fragment. urlencoded Unicode # fragments appear not to work in IE (at least up to 7) or in at least # one version of Opera 9.x. The W3C validator, for one, doesn't seem # to care if they aren't encoded. return Sanitizer::escapeId( $fragment, $wgEnforceHtmlIds ? 'noninitial' : 'xml' ); } #---------------------------------------------------------------------------- # Other stuff #---------------------------------------------------------------------------- /** Simple accessors */ /** * Get the text form (spaces not underscores) of the main part * @return \type{\string} Main part of the title */ public function getText() { return $this->mTextform; } /** * Get the URL-encoded form of the main part * @return \type{\string} Main part of the title, URL-encoded */ public function getPartialURL() { return $this->mUrlform; } /** * Get the main part with underscores * @return \type{\string} Main part of the title, with underscores */ public function getDBkey() { return $this->mDbkeyform; } /** * Get the namespace index, i.e.\ one of the NS_xxxx constants. * @return \type{\int} Namespace index */ public function getNamespace() { return $this->mNamespace; } /** * Get the namespace text * @return \type{\string} Namespace text */ public function getNsText() { global $wgContLang, $wgCanonicalNamespaceNames; if ( '' != $this->mInterwiki ) { // This probably shouldn't even happen. ohh man, oh yuck. // But for interwiki transclusion it sometimes does. // Shit. Shit shit shit. // // Use the canonical namespaces if possible to try to // resolve a foreign namespace. if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) { return $wgCanonicalNamespaceNames[$this->mNamespace]; } } return $wgContLang->getNsText( $this->mNamespace ); } /** * Get the DB key with the initial letter case as specified by the user * @return \type{\string} DB key */ function getUserCaseDBKey() { return $this->mUserCaseDBKey; } /** * Get the namespace text of the subject (rather than talk) page * @return \type{\string} Namespace text */ public function getSubjectNsText() { global $wgContLang; return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) ); } /** * Get the namespace text of the talk page * @return \type{\string} Namespace text */ public function getTalkNsText() { global $wgContLang; return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) ); } /** * Could this title have a corresponding talk page? * @return \type{\bool} TRUE or FALSE */ public function canTalk() { return( MWNamespace::canTalk( $this->mNamespace ) ); } /** * Get the interwiki prefix (or null string) * @return \type{\string} Interwiki prefix */ public function getInterwiki() { return $this->mInterwiki; } /** * Get the Title fragment (i.e.\ the bit after the #) in text form * @return \type{\string} Title fragment */ public function getFragment() { return $this->mFragment; } /** * Get the fragment in URL form, including the "#" character if there is one * @return \type{\string} Fragment in URL form */ public function getFragmentForURL() { if ( $this->mFragment == '' ) { return ''; } else { return '#' . Title::escapeFragmentForURL( $this->mFragment ); } } /** * Get the default namespace index, for when there is no namespace * @return \type{\int} Default namespace index */ public function getDefaultNamespace() { return $this->mDefaultNamespace; } /** * Get title for search index * @return \type{\string} a stripped-down title string ready for the * search index */ public function getIndexTitle() { return Title::indexTitle( $this->mNamespace, $this->mTextform ); } /** * Get the prefixed database key form * @return \type{\string} the prefixed title, with underscores and * any interwiki and namespace prefixes */ public function getPrefixedDBkey() { $s = $this->prefix( $this->mDbkeyform ); $s = str_replace( ' ', '_', $s ); return $s; } /** * Get the prefixed title with spaces. * This is the form usually used for display * @return \type{\string} the prefixed title, with spaces */ public function getPrefixedText() { if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ? $s = $this->prefix( $this->mTextform ); $s = str_replace( '_', ' ', $s ); $this->mPrefixedText = $s; } return $this->mPrefixedText; } /** * Get the prefixed title with spaces, plus any fragment * (part beginning with '#') * @return \type{\string} the prefixed title, with spaces and * the fragment, including '#' */ public function getFullText() { $text = $this->getPrefixedText(); if( '' != $this->mFragment ) { $text .= '#' . $this->mFragment; } return $text; } /** * Get the base name, i.e. the leftmost parts before the / * @return \type{\string} Base name */ public function getBaseText() { if( !MWNamespace::hasSubpages( $this->mNamespace ) ) { return $this->getText(); } $parts = explode( '/', $this->getText() ); # Don't discard the real title if there's no subpage involved if( count( $parts ) > 1 ) unset( $parts[ count( $parts ) - 1 ] ); return implode( '/', $parts ); } /** * Get the lowest-level subpage name, i.e. the rightmost part after / * @return \type{\string} Subpage name */ public function getSubpageText() { if( !MWNamespace::hasSubpages( $this->mNamespace ) ) { return( $this->mTextform ); } $parts = explode( '/', $this->mTextform ); return( $parts[ count( $parts ) - 1 ] ); } /** * Get a URL-encoded form of the subpage text * @return \type{\string} URL-encoded subpage name */ public function getSubpageUrlForm() { $text = $this->getSubpageText(); $text = wfUrlencode( str_replace( ' ', '_', $text ) ); return( $text ); } /** * Get a URL-encoded title (not an actual URL) including interwiki * @return \type{\string} the URL-encoded form */ public function getPrefixedURL() { $s = $this->prefix( $this->mDbkeyform ); $s = wfUrlencode( str_replace( ' ', '_', $s ) ); return $s; } /** * Get a real URL referring to this title, with interwiki link and * fragment * * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki * links. Can be specified as an associative array as well, e.g., * array( 'action' => 'edit' ) (keys and values will be URL-escaped). * @param $variant \type{\string} language variant of url (for sr, zh..) * @return \type{\string} the URL */ public function getFullURL( $query = '', $variant = false ) { global $wgContLang, $wgServer, $wgRequest; if( is_array( $query ) ) { $query = wfArrayToCGI( $query ); } $interwiki = Interwiki::fetch( $this->mInterwiki ); if ( !$interwiki ) { $url = $this->getLocalUrl( $query, $variant ); // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc) // Correct fix would be to move the prepending elsewhere. if ($wgRequest->getVal('action') != 'render') { $url = $wgServer . $url; } } else { $baseUrl = $interwiki->getURL( ); $namespace = wfUrlencode( $this->getNsText() ); if ( '' != $namespace ) { # Can this actually happen? Interwikis shouldn't be parsed. # Yes! It can in interwiki transclusion. But... it probably shouldn't. $namespace .= ':'; } $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl ); $url = wfAppendQuery( $url, $query ); } # Finally, add the fragment. $url .= $this->getFragmentForURL(); wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) ); return $url; } /** * Get a URL with no fragment or server name. If this page is generated * with action=render, $wgServer is prepended. * @param mixed $query an optional query string; if not specified, * $wgArticlePath will be used. Can be specified as an associative array * as well, e.g., array( 'action' => 'edit' ) (keys and values will be * URL-escaped). * @param $variant \type{\string} language variant of url (for sr, zh..) * @return \type{\string} the URL */ public function getLocalURL( $query = '', $variant = false ) { global $wgArticlePath, $wgScript, $wgServer, $wgRequest; global $wgVariantArticlePath, $wgContLang, $wgUser; if( is_array( $query ) ) { $query = wfArrayToCGI( $query ); } // internal links should point to same variant as current page (only anonymous users) if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){ $pref = $wgContLang->getPreferredVariant(false); if($pref != $wgContLang->getCode()) $variant = $pref; } if ( $this->isExternal() ) { $url = $this->getFullURL(); if ( $query ) { // This is currently only used for edit section links in the // context of interwiki transclusion. In theory we should // append the query to the end of any existing query string, // but interwiki transclusion is already broken in that case. $url .= "?$query"; } } else { $dbkey = wfUrlencode( $this->getPrefixedDBkey() ); if ( $query == '' ) { if( $variant != false && $wgContLang->hasVariants() ) { if( $wgVariantArticlePath == false ) { $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default } else { $variantArticlePath = $wgVariantArticlePath; } $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath ); $url = str_replace( '$1', $dbkey, $url ); } else { $url = str_replace( '$1', $dbkey, $wgArticlePath ); } } else { global $wgActionPaths; $url = false; $matches = array(); if( !empty( $wgActionPaths ) && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) { $action = urldecode( $matches[2] ); if( isset( $wgActionPaths[$action] ) ) { $query = $matches[1]; if( isset( $matches[4] ) ) $query .= $matches[4]; $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] ); if( $query != '' ) { $url = wfAppendQuery( $url, $query ); } } } if ( $url === false ) { if ( $query == '-' ) { $query = ''; } $url = "{$wgScript}?title={$dbkey}&{$query}"; } } // FIXME: this causes breakage in various places when we // actually expected a local URL and end up with dupe prefixes. if ($wgRequest->getVal('action') == 'render') { $url = $wgServer . $url; } } wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) ); return $url; } /** * Get a URL that's the simplest URL that will be valid to link, locally, * to the current Title. It includes the fragment, but does not include * the server unless action=render is used (or the link is external). If * there's a fragment but the prefixed text is empty, we just return a link * to the fragment. * * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the * query string. Keys and values will be escaped. * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored * for external links. Default is "false" (same variant as current page, * for anonymous users). * @return \type{\string} the URL */ public function getLinkUrl( $query = array(), $variant = false ) { wfProfileIn( __METHOD__ ); if( !is_array( $query ) ) { wfProfileOut( __METHOD__ ); throw new MWException( 'Title::getLinkUrl passed a non-array for '. '$query' ); } if( $this->isExternal() ) { $ret = $this->getFullURL( $query ); } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) { $ret = $this->getFragmentForURL(); } else { $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL(); } wfProfileOut( __METHOD__ ); return $ret; } /** * Get an HTML-escaped version of the URL form, suitable for * using in a link, without a server name or fragment * @param $query \type{\string} an optional query string * @return \type{\string} the URL */ public function escapeLocalURL( $query = '' ) { return htmlspecialchars( $this->getLocalURL( $query ) ); } /** * Get an HTML-escaped version of the URL form, suitable for * using in a link, including the server name and fragment * * @param $query \type{\string} an optional query string * @return \type{\string} the URL */ public function escapeFullURL( $query = '' ) { return htmlspecialchars( $this->getFullURL( $query ) ); } /** * Get the URL form for an internal link. * - Used in various Squid-related code, in case we have a different * internal hostname for the server from the exposed one. * * @param $query \type{\string} an optional query string * @param $variant \type{\string} language variant of url (for sr, zh..) * @return \type{\string} the URL */ public function getInternalURL( $query = '', $variant = false ) { global $wgInternalServer; $url = $wgInternalServer . $this->getLocalURL( $query, $variant ); wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) ); return $url; } /** * Get the edit URL for this Title * @return \type{\string} the URL, or a null string if this is an * interwiki link */ public function getEditURL() { if ( '' != $this->mInterwiki ) { return ''; } $s = $this->getLocalURL( 'action=edit' ); return $s; } /** * Get the HTML-escaped displayable text form. * Used for the title field in <a> tags. * @return \type{\string} the text, including any prefixes */ public function getEscapedText() { return htmlspecialchars( $this->getPrefixedText() ); } /** * Is this Title interwiki? * @return \type{\bool} */ public function isExternal() { return ( '' != $this->mInterwiki ); } /** * Is this page "semi-protected" - the *only* protection is autoconfirm? * * @param @action \type{\string} Action to check (default: edit) * @return \type{\bool} */ public function isSemiProtected( $action = 'edit' ) { if( $this->exists() ) { $restrictions = $this->getRestrictions( $action ); if( count( $restrictions ) > 0 ) { foreach( $restrictions as $restriction ) { if( strtolower( $restriction ) != 'autoconfirmed' ) return false; } } else { # Not protected return false; } return true; } else { # If it doesn't exist, it can't be protected return false; } } /** * Does the title correspond to a protected article? * @param $what \type{\string} the action the page is protected from, * by default checks move and edit * @return \type{\bool} */ public function isProtected( $action = '' ) { global $wgRestrictionLevels, $wgRestrictionTypes; # Special pages have inherent protection if( $this->getNamespace() == NS_SPECIAL ) return true; # Check regular protection levels foreach( $wgRestrictionTypes as $type ){ if( $action == $type || $action == '' ) { $r = $this->getRestrictions( $type ); foreach( $wgRestrictionLevels as $level ) { if( in_array( $level, $r ) && $level != '' ) { return true; } } } } return false; } /** * Is $wgUser watching this page? * @return \type{\bool} */ public function userIsWatching() { global $wgUser; if ( is_null( $this->mWatched ) ) { if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) { $this->mWatched = false; } else { $this->mWatched = $wgUser->isWatched( $this ); } } return $this->mWatched; } /** * Can $wgUser perform $action on this page? * This skips potentially expensive cascading permission checks. * * Suitable for use for nonessential UI controls in common cases, but * _not_ for functional access control. * * May provide false positives, but should never provide a false negative. * * @param $action \type{\string} action that permission needs to be checked for * @return \type{\bool} */ public function quickUserCan( $action ) { return $this->userCan( $action, false ); } /** * Determines if $wgUser is unable to edit this page because it has been protected * by $wgNamespaceProtection. * * @return \type{\bool} */ public function isNamespaceProtected() { global $wgNamespaceProtection, $wgUser; if( isset( $wgNamespaceProtection[ $this->mNamespace ] ) ) { foreach( (array)$wgNamespaceProtection[ $this->mNamespace ] as $right ) { if( $right != '' && !$wgUser->isAllowed( $right ) ) return true; } } return false; } /** * Can $wgUser perform $action on this page? * @param $action \type{\string} action that permission needs to be checked for * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries. * @return \type{\bool} */ public function userCan( $action, $doExpensiveQueries = true ) { global $wgUser; return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array()); } /** * Can $user perform $action on this page? * * FIXME: This *does not* check throttles (User::pingLimiter()). * * @param $action \type{\string}action that permission needs to be checked for * @param $user \type{User} user to check * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries. * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored. * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems. */ public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) { if( !StubObject::isRealObject( $user ) ) { //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser global $wgUser; $wgUser->_unstub( '', 5 ); $user = $wgUser; } $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries ); global $wgContLang; global $wgLang; global $wgEmailConfirmToEdit; if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) { $errors[] = array( 'confirmedittext' ); } // Edit blocks should not affect reading. Account creation blocks handled at userlogin. if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) { $block = $user->mBlock; // This is from OutputPage::blockedPage // Copied at r23888 by werdna $id = $user->blockedBy(); $reason = $user->blockedFor(); if( $reason == '' ) { $reason = wfMsg( 'blockednoreason' ); } $ip = wfGetIP(); if ( is_numeric( $id ) ) { $name = User::whoIs( $id ); } else { $name = $id; } $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]"; $blockid = $block->mId; $blockExpiry = $user->mBlock->mExpiry; $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true ); if ( $blockExpiry == 'infinity' ) { // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite' $scBlockExpiryOptions = wfMsg( 'ipboptions' ); foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) { if ( strpos( $option, ':' ) == false ) continue; list ($show, $value) = explode( ":", $option ); if ( $value == 'infinite' || $value == 'indefinite' ) { $blockExpiry = $show; break; } } } else { $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true ); } $intended = $user->mBlock->mAddress; $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp ); } // Remove the errors being ignored. foreach( $errors as $index => $error ) { $error_key = is_array($error) ? $error[0] : $error; if (in_array( $error_key, $ignoreErrors )) { unset($errors[$index]); } } return $errors; } /** * Can $user perform $action on this page? This is an internal function, * which checks ONLY that previously checked by userCan (i.e. it leaves out * checks on wfReadOnly() and blocks) * * @param $action \type{\string} action that permission needs to be checked for * @param $user \type{User} user to check * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries. * @param $short \type{\bool} Set this to true to stop after the first permission error. * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems. */ private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) { wfProfileIn( __METHOD__ ); $errors = array(); // First stop is permissions checks, which fail most often, and which are easiest to test. if ( $action == 'move' ) { if( !$user->isAllowed( 'move-rootuserpages' ) && $this->getNamespace() == NS_USER && !$this->isSubpage() ) { // Show user page-specific message only if the user can move other pages $errors[] = array( 'cant-move-user-page' ); } // Check if user is allowed to move files if it's a file if( $this->getNamespace() == NS_FILE && !$user->isAllowed( 'movefile' ) ) { $errors[] = array( 'movenotallowedfile' ); } if( !$user->isAllowed( 'move' ) ) { // User can't move anything $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed'); } } elseif ( $action == 'create' ) { if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) || ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) { $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin'); } } elseif( $action == 'move-target' ) { if( !$user->isAllowed( 'move' ) ) { // User can't move anything $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed'); } elseif( !$user->isAllowed( 'move-rootuserpages' ) && $this->getNamespace() == NS_USER && !$this->isSubpage() ) { // Show user page-specific message only if the user can move other pages $errors[] = array( 'cant-move-to-user-page' ); } } elseif( !$user->isAllowed( $action ) ) { $return = null; $groups = array_map( array( 'User', 'makeGroupLinkWiki' ), User::getGroupsWithPermission( $action ) ); if( $groups ) { $return = array( 'badaccess-groups', array( implode( ', ', $groups ), count( $groups ) ) ); } else { $return = array( "badaccess-group0" ); } $errors[] = $return; } # Short-circuit point if( $short && count($errors) > 0 ) { wfProfileOut( __METHOD__ ); return $errors; } // Use getUserPermissionsErrors instead if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) { wfProfileOut( __METHOD__ ); return $result ? array() : array( array( 'badaccess-group0' ) ); } // Check getUserPermissionsErrors hook if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) { if( is_array($result) && count($result) && !is_array($result[0]) ) $errors[] = $result; # A single array representing an error else if( is_array($result) && is_array($result[0]) ) $errors = array_merge( $errors, $result ); # A nested array representing multiple errors else if( $result !== '' && is_string($result) ) $errors[] = array($result); # A string representing a message-id else if( $result === false ) $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that" } # Short-circuit point if( $short && count($errors) > 0 ) { wfProfileOut( __METHOD__ ); return $errors; } // Check getUserPermissionsErrorsExpensive hook if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) { if( is_array($result) && count($result) && !is_array($result[0]) ) $errors[] = $result; # A single array representing an error else if( is_array($result) && is_array($result[0]) ) $errors = array_merge( $errors, $result ); # A nested array representing multiple errors else if( $result !== '' && is_string($result) ) $errors[] = array($result); # A string representing a message-id else if( $result === false ) $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that" } # Short-circuit point if( $short && count($errors) > 0 ) { wfProfileOut( __METHOD__ ); return $errors; } # Only 'createaccount' and 'execute' can be performed on # special pages, which don't actually exist in the DB. $specialOKActions = array( 'createaccount', 'execute' ); if( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions) ) { $errors[] = array('ns-specialprotected'); } # Check $wgNamespaceProtection for restricted namespaces if( $this->isNamespaceProtected() ) { $ns = $this->getNamespace() == NS_MAIN ? wfMsg( 'nstab-main' ) : $this->getNsText(); $errors[] = NS_MEDIAWIKI == $this->mNamespace ? array('protectedinterface') : array( 'namespaceprotected', $ns ); } # Protect css/js subpages of user pages # XXX: this might be better using restrictions # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working if( $this->isCssJsSubpage() && !$user->isAllowed('editusercssjs') && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) { $errors[] = array('customcssjsprotected'); } # Check against page_restrictions table requirements on this # page. The user must possess all required rights for this action. foreach( $this->getRestrictions($action) as $right ) { // Backwards compatibility, rewrite sysop -> protect if( $right == 'sysop' ) { $right = 'protect'; } if( '' != $right && !$user->isAllowed( $right ) ) { // Users with 'editprotected' permission can edit protected pages if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) { // Users with 'editprotected' permission cannot edit protected pages // with cascading option turned on. if( $this->mCascadeRestriction ) { $errors[] = array( 'protectedpagetext', $right ); } } else { $errors[] = array( 'protectedpagetext', $right ); } } } # Short-circuit point if( $short && count($errors) > 0 ) { wfProfileOut( __METHOD__ ); return $errors; } if( $doExpensiveQueries && !$this->isCssJsSubpage() ) { # We /could/ use the protection level on the source page, but it's fairly ugly # as we have to establish a precedence hierarchy for pages included by multiple # cascade-protected pages. So just restrict it to people with 'protect' permission, # as they could remove the protection anyway. list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources(); # Cascading protection depends on more than this page... # Several cascading protected pages may include this page... # Check each cascading level # This is only for protection restrictions, not for all actions if( $cascadingSources > 0 && isset($restrictions[$action]) ) { foreach( $restrictions[$action] as $right ) { $right = ( $right == 'sysop' ) ? 'protect' : $right; if( '' != $right && !$user->isAllowed( $right ) ) { $pages = ''; foreach( $cascadingSources as $page ) $pages .= '* [[:' . $page->getPrefixedText() . "]]\n"; $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages ); } } } } # Short-circuit point if( $short && count($errors) > 0 ) { wfProfileOut( __METHOD__ ); return $errors; } if( $action == 'protect' ) { if( $this->getUserPermissionsErrors('edit', $user) != array() ) { $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect. } } if( $action == 'create' ) { $title_protection = $this->getTitleProtection(); if( is_array($title_protection) ) { extract($title_protection); // is this extract() really needed? if( $pt_create_perm == 'sysop' ) { $pt_create_perm = 'protect'; // B/C } if( $pt_create_perm == '' || !$user->isAllowed($pt_create_perm) ) { $errors[] = array( 'titleprotected', User::whoIs($pt_user), $pt_reason ); } } } elseif( $action == 'move' ) { // Check for immobile pages if( !MWNamespace::isMovable( $this->getNamespace() ) ) { // Specific message for this case $errors[] = array( 'immobile-source-namespace', $this->getNsText() ); } elseif( !$this->isMovable() ) { // Less specific message for rarer cases $errors[] = array( 'immobile-page' ); } } elseif( $action == 'move-target' ) { if( !MWNamespace::isMovable( $this->getNamespace() ) ) { $errors[] = array( 'immobile-target-namespace', $this->getNsText() ); } elseif( !$this->isMovable() ) { $errors[] = array( 'immobile-target-page' ); } } wfProfileOut( __METHOD__ ); return $errors; } /** * Is this title subject to title protection? * @return \type{\mixed} An associative array representing any existent title * protection, or false if there's none. */ private function getTitleProtection() { // Can't protect pages in special namespaces if ( $this->getNamespace() < 0 ) { return false; } $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( 'protected_titles', '*', array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ), __METHOD__ ); if ($row = $dbr->fetchRow( $res )) { return $row; } else { return false; } } /** * Update the title protection status * @param $create_perm \type{\string} Permission required for creation * @param $reason \type{\string} Reason for protection * @param $expiry \type{\string} Expiry timestamp */ public function updateTitleProtection( $create_perm, $reason, $expiry ) { global $wgUser,$wgContLang; if ($create_perm == implode(',',$this->getRestrictions('create')) && $expiry == $this->mRestrictionsExpiry['create']) { // No change return true; } list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() ); $dbw = wfGetDB( DB_MASTER ); $encodedExpiry = Block::encodeExpiry($expiry, $dbw ); $expiry_description = ''; if ( $encodedExpiry != 'infinity' ) { $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) , $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')'; } else { $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')'; } # Update protection table if ($create_perm != '' ) { $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')), array( 'pt_namespace' => $namespace, 'pt_title' => $title , 'pt_create_perm' => $create_perm , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw) , 'pt_expiry' => $encodedExpiry , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ ); } else { $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace, 'pt_title' => $title ), __METHOD__ ); } # Update the protection log $log = new LogPage( 'protect' ); if( $create_perm ) { $params = array("[create=$create_perm] $expiry_description",''); $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason ), $params ); } else { $log->addEntry( 'unprotect', $this, $reason ); } return true; } /** * Remove any title protection due to page existing */ public function deleteTitleProtection() { $dbw = wfGetDB( DB_MASTER ); $dbw->delete( 'protected_titles', array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ), __METHOD__ ); } /** * Can $wgUser edit this page? * @return \type{\bool} TRUE or FALSE * @deprecated use userCan('edit') */ public function userCanEdit( $doExpensiveQueries = true ) { return $this->userCan( 'edit', $doExpensiveQueries ); } /** * Can $wgUser create this page? * @return \type{\bool} TRUE or FALSE * @deprecated use userCan('create') */ public function userCanCreate( $doExpensiveQueries = true ) { return $this->userCan( 'create', $doExpensiveQueries ); } /** * Can $wgUser move this page? * @return \type{\bool} TRUE or FALSE * @deprecated use userCan('move') */ public function userCanMove( $doExpensiveQueries = true ) { return $this->userCan( 'move', $doExpensiveQueries ); } /** * Would anybody with sufficient privileges be able to move this page? * Some pages just aren't movable. * * @return \type{\bool} TRUE or FALSE */ public function isMovable() { return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == ''; } /** * Can $wgUser read this page? * @return \type{\bool} TRUE or FALSE * @todo fold these checks into userCan() */ public function userCanRead() { global $wgUser, $wgGroupPermissions; $result = null; wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) ); if ( $result !== null ) { return $result; } # Shortcut for public wikis, allows skipping quite a bit of code if ( !empty( $wgGroupPermissions['*']['read'] ) ) return true; if( $wgUser->isAllowed( 'read' ) ) { return true; } else { global $wgWhitelistRead; /** * Always grant access to the login page. * Even anons need to be able to log in. */ if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) { return true; } /** * Bail out if there isn't whitelist */ if( !is_array($wgWhitelistRead) ) { return false; } /** * Check for explicit whitelisting */ $name = $this->getPrefixedText(); $dbName = $this->getPrefixedDBKey(); // Check with and without underscores if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) ) return true; /** * Old settings might have the title prefixed with * a colon for main-namespace pages */ if( $this->getNamespace() == NS_MAIN ) { if( in_array( ':' . $name, $wgWhitelistRead ) ) return true; } /** * If it's a special page, ditch the subpage bit * and check again */ if( $this->getNamespace() == NS_SPECIAL ) { $name = $this->getDBkey(); list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name ); if ( $name === false ) { # Invalid special page, but we show standard login required message return false; } $pure = SpecialPage::getTitleFor( $name )->getPrefixedText(); if( in_array( $pure, $wgWhitelistRead, true ) ) return true; } } return false; } /** * Is this a talk page of some sort? * @return \type{\bool} TRUE or FALSE */ public function isTalkPage() { return MWNamespace::isTalk( $this->getNamespace() ); } /** * Is this a subpage? * @return \type{\bool} TRUE or FALSE */ public function isSubpage() { return MWNamespace::hasSubpages( $this->mNamespace ) ? strpos( $this->getText(), '/' ) !== false : false; } /** * Does this have subpages? (Warning, usually requires an extra DB query.) * @return \type{\bool} TRUE or FALSE */ public function hasSubpages() { if( !MWNamespace::hasSubpages( $this->mNamespace ) ) { # Duh return false; } # We dynamically add a member variable for the purpose of this method # alone to cache the result. There's no point in having it hanging # around uninitialized in every Title object; therefore we only add it # if needed and don't declare it statically. if( isset( $this->mHasSubpages ) ) { return $this->mHasSubpages; } $subpages = $this->getSubpages( 1 ); if( $subpages instanceof TitleArray ) return $this->mHasSubpages = (bool)$subpages->count(); return $this->mHasSubpages = false; } /** * Get all subpages of this page. * @param $limit Maximum number of subpages to fetch; -1 for no limit * @return mixed TitleArray, or empty array if this page's namespace * doesn't allow subpages */ public function getSubpages( $limit = -1 ) { if( !MWNamespace::hasSubpages( $this->getNamespace() ) ) return array(); $dbr = wfGetDB( DB_SLAVE ); $conds['page_namespace'] = $this->getNamespace(); $conds[] = 'page_title LIKE ' . $dbr->addQuotes( $dbr->escapeLike( $this->getDBkey() ) . '/%' ); $options = array(); if( $limit > -1 ) $options['LIMIT'] = $limit; return $this->mSubpages = TitleArray::newFromResult( $dbr->select( 'page', array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ), $conds, __METHOD__, $options ) ); } /** * Could this page contain custom CSS or JavaScript, based * on the title? * * @return \type{\bool} TRUE or FALSE */ public function isCssOrJsPage() { return $this->mNamespace == NS_MEDIAWIKI && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0; } /** * Is this a .css or .js subpage of a user page? * @return \type{\bool} TRUE or FALSE */ public function isCssJsSubpage() { return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) ); } /** * Is this a *valid* .css or .js subpage of a user page? * Check that the corresponding skin exists * @return \type{\bool} TRUE or FALSE */ public function isValidCssJsSubpage() { if ( $this->isCssJsSubpage() ) { $skinNames = Skin::getSkinNames(); return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames ); } else { return false; } } /** * Trim down a .css or .js subpage title to get the corresponding skin name */ public function getSkinFromCssJsSubpage() { $subpage = explode( '/', $this->mTextform ); $subpage = $subpage[ count( $subpage ) - 1 ]; return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) ); } /** * Is this a .css subpage of a user page? * @return \type{\bool} TRUE or FALSE */ public function isCssSubpage() { return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) ); } /** * Is this a .js subpage of a user page? * @return \type{\bool} TRUE or FALSE */ public function isJsSubpage() { return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) ); } /** * Protect css/js subpages of user pages: can $wgUser edit * this page? * * @return \type{\bool} TRUE or FALSE * @todo XXX: this might be better using restrictions */ public function userCanEditCssJsSubpage() { global $wgUser; return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ); } /** * Cascading protection: Return true if cascading restrictions apply to this page, false if not. * * @return \type{\bool} If the page is subject to cascading restrictions. */ public function isCascadeProtected() { list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false ); return ( $sources > 0 ); } /** * Cascading protection: Get the source of any cascading restrictions on this page. * * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from. * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set. * The restriction array is an array of each type, each of which contains an array of unique groups. */ public function getCascadeProtectionSources( $get_pages = true ) { global $wgRestrictionTypes; # Define our dimension of restrictions types $pagerestrictions = array(); foreach( $wgRestrictionTypes as $action ) $pagerestrictions[$action] = array(); if ( isset( $this->mCascadeSources ) && $get_pages ) { return array( $this->mCascadeSources, $this->mCascadingRestrictions ); } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) { return array( $this->mHasCascadingRestrictions, $pagerestrictions ); } wfProfileIn( __METHOD__ ); $dbr = wfGetDB( DB_SLAVE ); if ( $this->getNamespace() == NS_FILE ) { $tables = array ('imagelinks', 'page_restrictions'); $where_clauses = array( 'il_to' => $this->getDBkey(), 'il_from=pr_page', 'pr_cascade' => 1 ); } else { $tables = array ('templatelinks', 'page_restrictions'); $where_clauses = array( 'tl_namespace' => $this->getNamespace(), 'tl_title' => $this->getDBkey(), 'tl_from=pr_page', 'pr_cascade' => 1 ); } if ( $get_pages ) { $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' ); $where_clauses[] = 'page_id=pr_page'; $tables[] = 'page'; } else { $cols = array( 'pr_expiry' ); } $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ ); $sources = $get_pages ? array() : false; $now = wfTimestampNow(); $purgeExpired = false; foreach( $res as $row ) { $expiry = Block::decodeExpiry( $row->pr_expiry ); if( $expiry > $now ) { if ($get_pages) { $page_id = $row->pr_page; $page_ns = $row->page_namespace; $page_title = $row->page_title; $sources[$page_id] = Title::makeTitle($page_ns, $page_title); # Add groups needed for each restriction type if its not already there # Make sure this restriction type still exists if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) { $pagerestrictions[$row->pr_type][]=$row->pr_level; } } else { $sources = true; } } else { // Trigger lazy purge of expired restrictions from the db $purgeExpired = true; } } if( $purgeExpired ) { Title::purgeExpiredRestrictions(); } wfProfileOut( __METHOD__ ); if ( $get_pages ) { $this->mCascadeSources = $sources; $this->mCascadingRestrictions = $pagerestrictions; } else { $this->mHasCascadingRestrictions = $sources; } return array( $sources, $pagerestrictions ); } function areRestrictionsCascading() { if (!$this->mRestrictionsLoaded) { $this->loadRestrictions(); } return $this->mCascadeRestriction; } /** * Loads a string into mRestrictions array * @param $res \type{Resource} restrictions as an SQL result. */ private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) { global $wgRestrictionTypes; $dbr = wfGetDB( DB_SLAVE ); foreach( $wgRestrictionTypes as $type ){ $this->mRestrictions[$type] = array(); $this->mRestrictionsExpiry[$type] = Block::decodeExpiry(''); } $this->mCascadeRestriction = false; # Backwards-compatibility: also load the restrictions from the page record (old format). if ( $oldFashionedRestrictions === NULL ) { $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ ); } if ($oldFashionedRestrictions != '') { foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) { $temp = explode( '=', trim( $restrict ) ); if(count($temp) == 1) { // old old format should be treated as edit/move restriction $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) ); $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) ); } else { $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) ); } } $this->mOldRestrictions = true; } if( $dbr->numRows( $res ) ) { # Current system - load second to make them override. $now = wfTimestampNow(); $purgeExpired = false; foreach( $res as $row ) { # Cycle through all the restrictions. // Don't take care of restrictions types that aren't in $wgRestrictionTypes if( !in_array( $row->pr_type, $wgRestrictionTypes ) ) continue; // This code should be refactored, now that it's being used more generally, // But I don't really see any harm in leaving it in Block for now -werdna $expiry = Block::decodeExpiry( $row->pr_expiry ); // Only apply the restrictions if they haven't expired! if ( !$expiry || $expiry > $now ) { $this->mRestrictionsExpiry[$row->pr_type] = $expiry; $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) ); $this->mCascadeRestriction |= $row->pr_cascade; } else { // Trigger a lazy purge of expired restrictions $purgeExpired = true; } } if( $purgeExpired ) { Title::purgeExpiredRestrictions(); } } $this->mRestrictionsLoaded = true; } /** * Load restrictions from the page_restrictions table */ public function loadRestrictions( $oldFashionedRestrictions = NULL ) { if( !$this->mRestrictionsLoaded ) { if ($this->exists()) { $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( 'page_restrictions', '*', array ( 'pr_page' => $this->getArticleId() ), __METHOD__ ); $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions ); } else { $title_protection = $this->getTitleProtection(); if (is_array($title_protection)) { extract($title_protection); $now = wfTimestampNow(); $expiry = Block::decodeExpiry($pt_expiry); if (!$expiry || $expiry > $now) { // Apply the restrictions $this->mRestrictionsExpiry['create'] = $expiry; $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) ); } else { // Get rid of the old restrictions Title::purgeExpiredRestrictions(); } } else { $this->mRestrictionsExpiry['create'] = Block::decodeExpiry(''); } $this->mRestrictionsLoaded = true; } } } /** * Purge expired restrictions from the page_restrictions table */ static function purgeExpiredRestrictions() { $dbw = wfGetDB( DB_MASTER ); $dbw->delete( 'page_restrictions', array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ ); $dbw->delete( 'protected_titles', array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ ); } /** * Accessor/initialisation for mRestrictions * * @param $action \type{\string} action that permission needs to be checked for * @return \type{\arrayof{\string}} the array of groups allowed to edit this article */ public function getRestrictions( $action ) { if( !$this->mRestrictionsLoaded ) { $this->loadRestrictions(); } return isset( $this->mRestrictions[$action] ) ? $this->mRestrictions[$action] : array(); } /** * Get the expiry time for the restriction against a given action * @return 14-char timestamp, or 'infinity' if the page is protected forever * or not protected at all, or false if the action is not recognised. */ public function getRestrictionExpiry( $action ) { if( !$this->mRestrictionsLoaded ) { $this->loadRestrictions(); } return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false; } /** * Is there a version of this page in the deletion archive? * @return \type{\int} the number of archived revisions */ public function isDeleted() { if( $this->getNamespace() < 0 ) { $n = 0; } else { $dbr = wfGetDB( DB_SLAVE ); $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ), __METHOD__ ); if( $this->getNamespace() == NS_FILE ) { $n += $dbr->selectField( 'filearchive', 'COUNT(*)', array( 'fa_name' => $this->getDBkey() ), __METHOD__ ); } } return (int)$n; } /** * Is there a version of this page in the deletion archive? * @return bool */ public function isDeletedQuick() { if( $this->getNamespace() < 0 ) { return false; } $dbr = wfGetDB( DB_SLAVE ); $deleted = (bool)$dbr->selectField( 'archive', '1', array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ), __METHOD__ ); if( !$deleted && $this->getNamespace() == NS_FILE ) { $deleted = (bool)$dbr->selectField( 'filearchive', '1', array( 'fa_name' => $this->getDBkey() ), __METHOD__ ); } return $deleted; } /** * Get the article ID for this Title from the link cache, * adding it if necessary * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select * for update * @return \type{\int} the ID */ public function getArticleID( $flags = 0 ) { if( $this->getNamespace() < 0 ) { return $this->mArticleID = 0; } $linkCache = LinkCache::singleton(); if( $flags & GAID_FOR_UPDATE ) { $oldUpdate = $linkCache->forUpdate( true ); $linkCache->clearLink( $this ); $this->mArticleID = $linkCache->addLinkObj( $this ); $linkCache->forUpdate( $oldUpdate ); } else { if( -1 == $this->mArticleID ) { $this->mArticleID = $linkCache->addLinkObj( $this ); } } return $this->mArticleID; } /** * Is this an article that is a redirect page? * Uses link cache, adding it if necessary * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update * @return \type{\bool} */ public function isRedirect( $flags = 0 ) { if( !is_null($this->mRedirect) ) return $this->mRedirect; # Calling getArticleID() loads the field from cache as needed if( !$this->getArticleID($flags) ) { return $this->mRedirect = false; } $linkCache = LinkCache::singleton(); $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' ); return $this->mRedirect; } /** * What is the length of this page? * Uses link cache, adding it if necessary * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update * @return \type{\bool} */ public function getLength( $flags = 0 ) { if( $this->mLength != -1 ) return $this->mLength; # Calling getArticleID() loads the field from cache as needed if( !$this->getArticleID($flags) ) { return $this->mLength = 0; } $linkCache = LinkCache::singleton(); $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) ); return $this->mLength; } /** * What is the page_latest field for this page? * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update * @return \type{\int} */ public function getLatestRevID( $flags = 0 ) { if( $this->mLatestID !== false ) return $this->mLatestID; $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE); $this->mLatestID = $db->selectField( 'page', 'page_latest', $this->pageCond(), __METHOD__ ); return $this->mLatestID; } /** * This clears some fields in this object, and clears any associated * keys in the "bad links" section of the link cache. * * - This is called from Article::insertNewArticle() to allow * loading of the new page_id. It's also called from * Article::doDeleteArticle() * * @param $newid \type{\int} the new Article ID */ public function resetArticleID( $newid ) { $linkCache = LinkCache::singleton(); $linkCache->clearBadLink( $this->getPrefixedDBkey() ); if ( $newid === false ) { $this->mArticleID = -1; } else { $this->mArticleID = $newid; } $this->mRestrictionsLoaded = false; $this->mRestrictions = array(); } /** * Updates page_touched for this page; called from LinksUpdate.php * @return \type{\bool} true if the update succeded */ public function invalidateCache() { if( wfReadOnly() ) { return; } $dbw = wfGetDB( DB_MASTER ); $success = $dbw->update( 'page', array( 'page_touched' => $dbw->timestamp() ), $this->pageCond(), __METHOD__ ); HTMLFileCache::clearFileCache( $this ); return $success; } /** * Prefix some arbitrary text with the namespace or interwiki prefix * of this object * * @param $name \type{\string} the text * @return \type{\string} the prefixed text * @private */ /* private */ function prefix( $name ) { $p = ''; if ( '' != $this->mInterwiki ) { $p = $this->mInterwiki . ':'; } if ( 0 != $this->mNamespace ) { $p .= $this->getNsText() . ':'; } return $p . $name; } /** * Secure and split - main initialisation function for this object * * Assumes that mDbkeyform has been set, and is urldecoded * and uses underscores, but not otherwise munged. This function * removes illegal characters, splits off the interwiki and * namespace prefixes, sets the other forms, and canonicalizes * everything. * @return \type{\bool} true on success */ private function secureAndSplit() { global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks; # Initialisation static $rxTc = false; if( !$rxTc ) { # Matching titles will be held as illegal. $rxTc = '/' . # Any character not allowed is forbidden... '[^' . Title::legalChars() . ']' . # URL percent encoding sequences interfere with the ability # to round-trip titles -- you can't link to them consistently. '|%[0-9A-Fa-f]{2}' . # XML/HTML character references produce similar issues. '|&[A-Za-z0-9\x80-\xff]+;' . '|&#[0-9]+;' . '|&#x[0-9A-Fa-f]+;' . '/S'; } $this->mInterwiki = $this->mFragment = ''; $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN $dbkey = $this->mDbkeyform; # Strip Unicode bidi override characters. # Sometimes they slip into cut-n-pasted page titles, where the # override chars get included in list displays. $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey ); # Clean up whitespace # $dbkey = preg_replace( '/[ _]+/', '_', $dbkey ); $dbkey = trim( $dbkey, '_' ); if ( '' == $dbkey ) { return false; } if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) { # Contained illegal UTF-8 sequences or forbidden Unicode chars. return false; } $this->mDbkeyform = $dbkey; # Initial colon indicates main namespace rather than specified default # but should not create invalid {ns,title} pairs such as {0,Project:Foo} if ( ':' == $dbkey{0} ) { $this->mNamespace = NS_MAIN; $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace } # Namespace or interwiki prefix $firstPass = true; $prefixRegexp = "/^(.+?)_*:_*(.*)$/S"; do { $m = array(); if ( preg_match( $prefixRegexp, $dbkey, $m ) ) { $p = $m[1]; if ( $ns = $wgContLang->getNsIndex( $p ) ) { # Ordinary namespace $dbkey = $m[2]; $this->mNamespace = $ns; # For Talk:X pages, check if X has a "namespace" prefix if( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) { if( $wgContLang->getNsIndex( $x[1] ) ) return false; # Disallow Talk:File:x type titles... else if( Interwiki::isValidInterwiki( $x[1] ) ) return false; # Disallow Talk:Interwiki:x type titles... } } elseif( Interwiki::isValidInterwiki( $p ) ) { if( !$firstPass ) { # Can't make a local interwiki link to an interwiki link. # That's just crazy! return false; } # Interwiki link $dbkey = $m[2]; $this->mInterwiki = $wgContLang->lc( $p ); # Redundant interwiki prefix to the local wiki if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) { if( $dbkey == '' ) { # Can't have an empty self-link return false; } $this->mInterwiki = ''; $firstPass = false; # Do another namespace split... continue; } # If there's an initial colon after the interwiki, that also # resets the default namespace if ( $dbkey !== '' && $dbkey[0] == ':' ) { $this->mNamespace = NS_MAIN; $dbkey = substr( $dbkey, 1 ); } } # If there's no recognized interwiki or namespace, # then let the colon expression be part of the title. } break; } while( true ); # We already know that some pages won't be in the database! # if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) { $this->mArticleID = 0; } $fragment = strstr( $dbkey, '#' ); if ( false !== $fragment ) { $this->setFragment( $fragment ); $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) ); # remove whitespace again: prevents "Foo_bar_#" # becoming "Foo_bar_" $dbkey = preg_replace( '/_*$/', '', $dbkey ); } # Reject illegal characters. # if( preg_match( $rxTc, $dbkey ) ) { return false; } /** * Pages with "/./" or "/../" appearing in the URLs will often be un- * reachable due to the way web browsers deal with 'relative' URLs. * Also, they conflict with subpage syntax. Forbid them explicitly. */ if ( strpos( $dbkey, '.' ) !== false && ( $dbkey === '.' || $dbkey === '..' || strpos( $dbkey, './' ) === 0 || strpos( $dbkey, '../' ) === 0 || strpos( $dbkey, '/./' ) !== false || strpos( $dbkey, '/../' ) !== false || substr( $dbkey, -2 ) == '/.' || substr( $dbkey, -3 ) == '/..' ) ) { return false; } /** * Magic tilde sequences? Nu-uh! */ if( strpos( $dbkey, '~~~' ) !== false ) { return false; } /** * Limit the size of titles to 255 bytes. * This is typically the size of the underlying database field. * We make an exception for special pages, which don't need to be stored * in the database, and may edge over 255 bytes due to subpage syntax * for long titles, e.g. [[Special:Block/Long name]] */ if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) || strlen( $dbkey ) > 512 ) { return false; } /** * Normally, all wiki links are forced to have * an initial capital letter so [[foo]] and [[Foo]] * point to the same place. * * Don't force it for interwikis, since the other * site might be case-sensitive. */ $this->mUserCaseDBKey = $dbkey; if( $wgCapitalLinks && $this->mInterwiki == '') { $dbkey = $wgContLang->ucfirst( $dbkey ); } /** * Can't make a link to a namespace alone... * "empty" local links can only be self-links * with a fragment identifier. */ if( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) { return false; } // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles. // IP names are not allowed for accounts, and can only be referring to // edits from the IP. Given '::' abbreviations and caps/lowercaps, // there are numerous ways to present the same IP. Having sp:contribs scan // them all is silly and having some show the edits and others not is // inconsistent. Same for talk/userpages. Keep them normalized instead. $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ? IP::sanitizeIP( $dbkey ) : $dbkey; // Any remaining initial :s are illegal. if ( $dbkey !== '' && ':' == $dbkey{0} ) { return false; } # Fill fields $this->mDbkeyform = $dbkey; $this->mUrlform = wfUrlencode( $dbkey ); $this->mTextform = str_replace( '_', ' ', $dbkey ); return true; } /** * Set the fragment for this title. Removes the first character from the * specified fragment before setting, so it assumes you're passing it with * an initial "#". * * Deprecated for public use, use Title::makeTitle() with fragment parameter. * Still in active use privately. * * @param $fragment \type{\string} text */ public function setFragment( $fragment ) { $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) ); } /** * Get a Title object associated with the talk page of this article * @return \type{Title} the object for the talk page */ public function getTalkPage() { return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() ); } /** * Get a title object associated with the subject page of this * talk page * * @return \type{Title} the object for the subject page */ public function getSubjectPage() { // Is this the same title? $subjectNS = MWNamespace::getSubject( $this->getNamespace() ); if( $this->getNamespace() == $subjectNS ) { return $this; } return Title::makeTitle( $subjectNS, $this->getDBkey() ); } /** * Get an array of Title objects linking to this Title * Also stores the IDs in the link cache. * * WARNING: do not use this function on arbitrary user-supplied titles! * On heavily-used templates it will max out the memory. * * @param array $options may be FOR UPDATE * @return \type{\arrayof{Title}} the Title objects linking here */ public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) { $linkCache = LinkCache::singleton(); if ( count( $options ) > 0 ) { $db = wfGetDB( DB_MASTER ); } else { $db = wfGetDB( DB_SLAVE ); } $res = $db->select( array( 'page', $table ), array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ), array( "{$prefix}_from=page_id", "{$prefix}_namespace" => $this->getNamespace(), "{$prefix}_title" => $this->getDBkey() ), __METHOD__, $options ); $retVal = array(); if ( $db->numRows( $res ) ) { foreach( $res as $row ) { if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) { $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect ); $retVal[] = $titleObj; } } } $db->freeResult( $res ); return $retVal; } /** * Get an array of Title objects using this Title as a template * Also stores the IDs in the link cache. * * WARNING: do not use this function on arbitrary user-supplied titles! * On heavily-used templates it will max out the memory. * * @param array $options may be FOR UPDATE * @return \type{\arrayof{Title}} the Title objects linking here */ public function getTemplateLinksTo( $options = array() ) { return $this->getLinksTo( $options, 'templatelinks', 'tl' ); } /** * Get an array of Title objects referring to non-existent articles linked from this page * * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case) * @return \type{\arrayof{Title}} the Title objects */ public function getBrokenLinksFrom() { if ( $this->getArticleId() == 0 ) { # All links from article ID 0 are false positives return array(); } $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( array( 'page', 'pagelinks' ), array( 'pl_namespace', 'pl_title' ), array( 'pl_from' => $this->getArticleId(), 'page_namespace IS NULL' ), __METHOD__, array(), array( 'page' => array( 'LEFT JOIN', array( 'pl_namespace=page_namespace', 'pl_title=page_title' ) ) ) ); $retVal = array(); foreach( $res as $row ) { $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title ); } return $retVal; } /** * Get a list of URLs to purge from the Squid cache when this * page changes * * @return \type{\arrayof{\string}} the URLs */ public function getSquidURLs() { global $wgContLang; $urls = array( $this->getInternalURL(), $this->getInternalURL( 'action=history' ) ); // purge variant urls as well if($wgContLang->hasVariants()){ $variants = $wgContLang->getVariants(); foreach($variants as $vCode){ if($vCode==$wgContLang->getCode()) continue; // we don't want default variant $urls[] = $this->getInternalURL('',$vCode); } } return $urls; } /** * Purge all applicable Squid URLs */ public function purgeSquid() { global $wgUseSquid; if ( $wgUseSquid ) { $urls = $this->getSquidURLs(); $u = new SquidUpdate( $urls ); $u->doUpdate(); } } /** * Move this page without authentication * @param &$nt \type{Title} the new page Title */ public function moveNoAuth( &$nt ) { return $this->moveTo( $nt, false ); } /** * Check whether a given move operation would be valid. * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise * @param &$nt \type{Title} the new title * @param $auth \type{\bool} indicates whether $wgUser's permissions * should be checked * @param $reason \type{\string} is the log summary of the move, used for spam checking * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure */ public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) { global $wgUser; $errors = array(); if( !$nt ) { // Normally we'd add this to $errors, but we'll get // lots of syntax errors if $nt is not an object return array(array('badtitletext')); } if( $this->equals( $nt ) ) { $errors[] = array('selfmove'); } if( !$this->isMovable() ) { $errors[] = array( 'immobile-source-namespace', $this->getNsText() ); } if ( $nt->getInterwiki() != '' ) { $errors[] = array( 'immobile-target-namespace-iw' ); } if ( !$nt->isMovable() ) { $errors[] = array('immobile-target-namespace', $nt->getNsText() ); } $oldid = $this->getArticleID(); $newid = $nt->getArticleID(); if ( strlen( $nt->getDBkey() ) < 1 ) { $errors[] = array('articleexists'); } if ( ( '' == $this->getDBkey() ) || ( !$oldid ) || ( '' == $nt->getDBkey() ) ) { $errors[] = array('badarticleerror'); } // Image-specific checks if( $this->getNamespace() == NS_FILE ) { $file = wfLocalFile( $this ); if( $file->exists() ) { if( $nt->getNamespace() != NS_FILE ) { $errors[] = array('imagenocrossnamespace'); } if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) { $errors[] = array('imageinvalidfilename'); } if( !File::checkExtensionCompatibility( $file, $nt->getDBKey() ) ) { $errors[] = array('imagetypemismatch'); } } } if ( $auth ) { $errors = wfMergeErrorArrays( $errors, $this->getUserPermissionsErrors('move', $wgUser), $this->getUserPermissionsErrors('edit', $wgUser), $nt->getUserPermissionsErrors('move-target', $wgUser), $nt->getUserPermissionsErrors('edit', $wgUser) ); } $match = EditPage::matchSummarySpamRegex( $reason ); if( $match !== false ) { // This is kind of lame, won't display nice $errors[] = array('spamprotectiontext'); } $err = null; if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) { $errors[] = array('hookaborted', $err); } # The move is allowed only if (1) the target doesn't exist, or # (2) the target is a redirect to the source, and has no history # (so we can undo bad moves right after they're done). if ( 0 != $newid ) { # Target exists; check for validity if ( ! $this->isValidMoveTarget( $nt ) ) { $errors[] = array('articleexists'); } } else { $tp = $nt->getTitleProtection(); $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm']; if ( $tp and !$wgUser->isAllowed( $right ) ) { $errors[] = array('cantmove-titleprotected'); } } if(empty($errors)) return true; return $errors; } /** * Move a title to a new location * @param &$nt \type{Title} the new title * @param $auth \type{\bool} indicates whether $wgUser's permissions * should be checked * @param $reason \type{\string} The reason for the move * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title. * Ignored if the user doesn't have the suppressredirect right. * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure */ public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) { $err = $this->isValidMoveOperation( $nt, $auth, $reason ); if( is_array( $err ) ) { return $err; } $pageid = $this->getArticleID(); $protected = $this->isProtected(); if( $nt->exists() ) { $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect ); $pageCountChange = ($createRedirect ? 0 : -1); } else { # Target didn't exist, do normal move. $err = $this->moveToNewTitle( $nt, $reason, $createRedirect ); $pageCountChange = ($createRedirect ? 1 : 0); } if( is_array( $err ) ) { return $err; } $redirid = $this->getArticleID(); // Category memberships include a sort key which may be customized. // If it's left as the default (the page title), we need to update // the sort key to match the new title. // // Be careful to avoid resetting cl_timestamp, which may disturb // time-based lists on some sites. // // Warning -- if the sort key is *explicitly* set to the old title, // we can't actually distinguish it from a default here, and it'll // be set to the new title even though it really shouldn't. // It'll get corrected on the next edit, but resetting cl_timestamp. $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'categorylinks', array( 'cl_sortkey' => $nt->getPrefixedText(), 'cl_timestamp=cl_timestamp' ), array( 'cl_from' => $pageid, 'cl_sortkey' => $this->getPrefixedText() ), __METHOD__ ); if( $protected ) { # Protect the redirect title as the title used to be... $dbw->insertSelect( 'page_restrictions', 'page_restrictions', array( 'pr_page' => $redirid, 'pr_type' => 'pr_type', 'pr_level' => 'pr_level', 'pr_cascade' => 'pr_cascade', 'pr_user' => 'pr_user', 'pr_expiry' => 'pr_expiry' ), array( 'pr_page' => $pageid ), __METHOD__, array( 'IGNORE' ) ); # Update the protection log $log = new LogPage( 'protect' ); $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ); if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason; $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params? } # Update watchlists $oldnamespace = $this->getNamespace() & ~1; $newnamespace = $nt->getNamespace() & ~1; $oldtitle = $this->getDBkey(); $newtitle = $nt->getDBkey(); if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) { WatchedItem::duplicateEntries( $this, $nt ); } # Update search engine $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() ); $u->doUpdate(); $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' ); $u->doUpdate(); # Update site_stats if( $this->isContentPage() && !$nt->isContentPage() ) { # No longer a content page # Not viewed, edited, removing $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange ); } elseif( !$this->isContentPage() && $nt->isContentPage() ) { # Now a content page # Not viewed, edited, adding $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange ); } elseif( $pageCountChange ) { # Redirect added $u = new SiteStatsUpdate( 0, 0, 0, 1 ); } else { # Nothing special $u = false; } if( $u ) $u->doUpdate(); # Update message cache for interface messages if( $nt->getNamespace() == NS_MEDIAWIKI ) { global $wgMessageCache; # @bug 17860: old article can be deleted, if this the case, # delete it from message cache if ( $this->getArticleID === 0 ) { $wgMessageCache->replace( $this->getDBkey(), false ); } else { $oldarticle = new Article( $this ); $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() ); } $newarticle = new Article( $nt ); $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() ); } global $wgUser; wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) ); return true; } /** * Move page to a title which is at present a redirect to the * source page * * @param &$nt \type{Title} the page to move to, which should currently * be a redirect * @param $reason \type{\string} The reason for the move * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title. * Ignored if the user doesn't have the suppressredirect right */ private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) { global $wgUseSquid, $wgUser; $fname = 'Title::moveOverExistingRedirect'; $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() ); if ( $reason ) { $comment .= ": $reason"; } $now = wfTimestampNow(); $newid = $nt->getArticleID(); $oldid = $this->getArticleID(); $latest = $this->getLatestRevID(); $dbw = wfGetDB( DB_MASTER ); # Delete the old redirect. We don't save it to history since # by definition if we've got here it's rather uninteresting. # We have to remove it so that the next step doesn't trigger # a conflict on the unique namespace+title index... $dbw->delete( 'page', array( 'page_id' => $newid ), $fname ); if ( !$dbw->cascadingDeletes() ) { $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ ); global $wgUseTrackbacks; if ($wgUseTrackbacks) $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ ); $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ ); $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ ); $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ ); $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ ); $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ ); $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ ); $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ ); } # Save a null revision in the page's history notifying of the move $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true ); $nullRevId = $nullRevision->insertOn( $dbw ); $article = new Article( $this ); wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) ); # Change the name of the target page: $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp($now), 'page_namespace' => $nt->getNamespace(), 'page_title' => $nt->getDBkey(), 'page_latest' => $nullRevId, ), /* WHERE */ array( 'page_id' => $oldid ), $fname ); $nt->resetArticleID( $oldid ); # Recreate the redirect, this time in the other direction. if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) { $mwRedir = MagicWord::get( 'redirect' ); $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n"; $redirectArticle = new Article( $this ); $newid = $redirectArticle->insertOn( $dbw ); $redirectRevision = new Revision( array( 'page' => $newid, 'comment' => $comment, 'text' => $redirectText ) ); $redirectRevision->insertOn( $dbw ); $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 ); wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) ); # Now, we record the link from the redirect to the new title. # It should have no other outgoing links... $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname ); $dbw->insert( 'pagelinks', array( 'pl_from' => $newid, 'pl_namespace' => $nt->getNamespace(), 'pl_title' => $nt->getDBkey() ), $fname ); $redirectSuppressed = false; } else { $this->resetArticleID( 0 ); $redirectSuppressed = true; } # Move an image if this is a file if( $this->getNamespace() == NS_FILE ) { $file = wfLocalFile( $this ); if( $file->exists() ) { $status = $file->move( $nt ); if( !$status->isOk() ) { $dbw->rollback(); return $status->getErrorsArray(); } } } # Log the move $log = new LogPage( 'move' ); $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) ); # Purge squid if ( $wgUseSquid ) { $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() ); $u = new SquidUpdate( $urls ); $u->doUpdate(); } } /** * Move page to non-existing title. * @param &$nt \type{Title} the new Title * @param $reason \type{\string} The reason for the move * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title * Ignored if the user doesn't have the suppressredirect right */ private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) { global $wgUseSquid, $wgUser; $fname = 'MovePageForm::moveToNewTitle'; $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ); if ( $reason ) { $comment .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) ); $comment .= $reason; } $newid = $nt->getArticleID(); $oldid = $this->getArticleID(); $latest = $this->getLatestRevId(); $dbw = wfGetDB( DB_MASTER ); $now = $dbw->timestamp(); # Save a null revision in the page's history notifying of the move $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true ); $nullRevId = $nullRevision->insertOn( $dbw ); $article = new Article( $this ); wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) ); # Rename page entry $dbw->update( 'page', /* SET */ array( 'page_touched' => $now, 'page_namespace' => $nt->getNamespace(), 'page_title' => $nt->getDBkey(), 'page_latest' => $nullRevId, ), /* WHERE */ array( 'page_id' => $oldid ), $fname ); $nt->resetArticleID( $oldid ); if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) { # Insert redirect $mwRedir = MagicWord::get( 'redirect' ); $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n"; $redirectArticle = new Article( $this ); $newid = $redirectArticle->insertOn( $dbw ); $redirectRevision = new Revision( array( 'page' => $newid, 'comment' => $comment, 'text' => $redirectText ) ); $redirectRevision->insertOn( $dbw ); $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 ); wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) ); # Record the just-created redirect's linking to the page $dbw->insert( 'pagelinks', array( 'pl_from' => $newid, 'pl_namespace' => $nt->getNamespace(), 'pl_title' => $nt->getDBkey() ), $fname ); $redirectSuppressed = false; } else { $this->resetArticleID( 0 ); $redirectSuppressed = true; } # Move an image if this is a file if( $this->getNamespace() == NS_FILE ) { $file = wfLocalFile( $this ); if( $file->exists() ) { $status = $file->move( $nt ); if( !$status->isOk() ) { $dbw->rollback(); return $status->getErrorsArray(); } } } # Log the move $log = new LogPage( 'move' ); $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) ); # Purge caches as per article creation Article::onArticleCreate( $nt ); # Purge old title from squid # The new title, and links to the new title, are purged in Article::onArticleCreate() $this->purgeSquid(); } /** * Move this page's subpages to be subpages of $nt * @param $nt Title Move target * @param $auth bool Whether $wgUser's permissions should be checked * @param $reason string The reason for the move * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones * Ignored if the user doesn't have the 'suppressredirect' right * @return mixed array with old page titles as keys, and strings (new page titles) or * arrays (errors) as values, or an error array with numeric indices if no pages were moved */ public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) { global $wgUser, $wgMaximumMovedPages; // Check permissions if( !$this->userCan( 'move-subpages' ) ) return array( 'cant-move-subpages' ); // Do the source and target namespaces support subpages? if( !MWNamespace::hasSubpages( $this->getNamespace() ) ) return array( 'namespace-nosubpages', MWNamespace::getCanonicalName( $this->getNamespace() ) ); if( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) return array( 'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ); $subpages = $this->getSubpages($wgMaximumMovedPages + 1); $retval = array(); $count = 0; foreach( $subpages as $oldSubpage ) { $count++; if( $count > $wgMaximumMovedPages ) { $retval[$oldSubpage->getPrefixedTitle()] = array( 'movepage-max-pages', $wgMaximumMovedPages ); break; } if( $oldSubpage->getArticleId() == $this->getArticleId() ) // When moving a page to a subpage of itself, // don't move it twice continue; $newPageName = preg_replace( '#^'.preg_quote( $this->getDBKey(), '#' ).'#', $nt->getDBKey(), $oldSubpage->getDBKey() ); if( $oldSubpage->isTalkPage() ) { $newNs = $nt->getTalkPage()->getNamespace(); } else { $newNs = $nt->getSubjectPage()->getNamespace(); } # Bug 14385: we need makeTitleSafe because the new page names may # be longer than 255 characters. $newSubpage = Title::makeTitleSafe( $newNs, $newPageName ); $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect ); if( $success === true ) { $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText(); } else { $retval[$oldSubpage->getPrefixedText()] = $success; } } return $retval; } /** * Checks if this page is just a one-rev redirect. * Adds lock, so don't use just for light purposes. * * @return \type{\bool} TRUE or FALSE */ public function isSingleRevRedirect() { $dbw = wfGetDB( DB_MASTER ); # Is it a redirect? $row = $dbw->selectRow( 'page', array( 'page_is_redirect', 'page_latest', 'page_id' ), $this->pageCond(), __METHOD__, array( 'FOR UPDATE' ) ); # Cache some fields we may want $this->mArticleID = $row ? intval($row->page_id) : 0; $this->mRedirect = $row ? (bool)$row->page_is_redirect : false; $this->mLatestID = $row ? intval($row->page_latest) : false; if( !$this->mRedirect ) { return false; } # Does the article have a history? $row = $dbw->selectField( array( 'page', 'revision'), 'rev_id', array( 'page_namespace' => $this->getNamespace(), 'page_title' => $this->getDBkey(), 'page_id=rev_page', 'page_latest != rev_id' ), __METHOD__, array( 'FOR UPDATE' ) ); # Return true if there was no history return ($row === false); } /** * Checks if $this can be moved to a given Title * - Selects for update, so don't call it unless you mean business * * @param &$nt \type{Title} the new title to check * @return \type{\bool} TRUE or FALSE */ public function isValidMoveTarget( $nt ) { $dbw = wfGetDB( DB_MASTER ); # Is it an existsing file? if( $nt->getNamespace() == NS_FILE ) { $file = wfLocalFile( $nt ); if( $file->exists() ) { wfDebug( __METHOD__ . ": file exists\n" ); return false; } } # Is it a redirect with no history? if( !$nt->isSingleRevRedirect() ) { wfDebug( __METHOD__ . ": not a one-rev redirect\n" ); return false; } # Get the article text $rev = Revision::newFromTitle( $nt ); $text = $rev->getText(); # Does the redirect point to the source? # Or is it a broken self-redirect, usually caused by namespace collisions? $m = array(); if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) { $redirTitle = Title::newFromText( $m[1] ); if( !is_object( $redirTitle ) || ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() && $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) { wfDebug( __METHOD__ . ": redirect points to other page\n" ); return false; } } else { # Fail safe wfDebug( __METHOD__ . ": failsafe\n" ); return false; } return true; } /** * Can this title be added to a user's watchlist? * * @return \type{\bool} TRUE or FALSE */ public function isWatchable() { return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() ); } /** * Get categories to which this Title belongs and return an array of * categories' names. * * @return \type{\array} array an array of parents in the form: * $parent => $currentarticle */ public function getParentCategories() { global $wgContLang; $titlekey = $this->getArticleId(); $dbr = wfGetDB( DB_SLAVE ); $categorylinks = $dbr->tableName( 'categorylinks' ); # NEW SQL $sql = "SELECT * FROM $categorylinks" ." WHERE cl_from='$titlekey'" ." AND cl_from <> '0'" ." ORDER BY cl_sortkey"; $res = $dbr->query( $sql ); if( $dbr->numRows( $res ) > 0 ) { foreach( $res as $row ) //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to); $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText(); $dbr->freeResult( $res ); } else { $data = array(); } return $data; } /** * Get a tree of parent categories * @param $children \type{\array} an array with the children in the keys, to check for circular refs * @return \type{\array} Tree of parent categories */ public function getParentCategoryTree( $children = array() ) { $stack = array(); $parents = $this->getParentCategories(); if( $parents ) { foreach( $parents as $parent => $current ) { if ( array_key_exists( $parent, $children ) ) { # Circular reference $stack[$parent] = array(); } else { $nt = Title::newFromText($parent); if ( $nt ) { $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) ); } } } return $stack; } else { return array(); } } /** * Get an associative array for selecting this title from * the "page" table * * @return \type{\array} Selection array */ public function pageCond() { if( $this->mArticleID > 0 ) { // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs return array( 'page_id' => $this->mArticleID ); } else { return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ); } } /** * Get the revision ID of the previous revision * * @param $revId \type{\int} Revision ID. Get the revision that was before this one. * @param $flags \type{\int} GAID_FOR_UPDATE * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists */ public function getPreviousRevisionID( $revId, $flags=0 ) { $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); return $db->selectField( 'revision', 'rev_id', array( 'rev_page' => $this->getArticleId($flags), 'rev_id < ' . intval( $revId ) ), __METHOD__, array( 'ORDER BY' => 'rev_id DESC' ) ); } /** * Get the revision ID of the next revision * * @param $revId \type{\int} Revision ID. Get the revision that was after this one. * @param $flags \type{\int} GAID_FOR_UPDATE * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists */ public function getNextRevisionID( $revId, $flags=0 ) { $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); return $db->selectField( 'revision', 'rev_id', array( 'rev_page' => $this->getArticleId($flags), 'rev_id > ' . intval( $revId ) ), __METHOD__, array( 'ORDER BY' => 'rev_id' ) ); } /** * Get the first revision of the page * * @param $flags \type{\int} GAID_FOR_UPDATE * @return Revision (or NULL if page doesn't exist) */ public function getFirstRevision( $flags=0 ) { $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); $pageId = $this->getArticleId($flags); if( !$pageId ) return NULL; $row = $db->selectRow( 'revision', '*', array( 'rev_page' => $pageId ), __METHOD__, array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ) ); if( !$row ) { return NULL; } else { return new Revision( $row ); } } /** * Check if this is a new page * * @return bool */ public function isNewPage() { $dbr = wfGetDB( DB_SLAVE ); return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ ); } /** * Get the oldest revision timestamp of this page * * @return string, MW timestamp */ public function getEarliestRevTime() { $dbr = wfGetDB( DB_SLAVE ); if( $this->exists() ) { $min = $dbr->selectField( 'revision', 'MIN(rev_timestamp)', array( 'rev_page' => $this->getArticleId() ), __METHOD__ ); return wfTimestampOrNull( TS_MW, $min ); } return null; } /** * Get the number of revisions between the given revision IDs. * Used for diffs and other things that really need it. * * @param $old \type{\int} Revision ID. * @param $new \type{\int} Revision ID. * @return \type{\int} Number of revisions between these IDs. */ public function countRevisionsBetween( $old, $new ) { $dbr = wfGetDB( DB_SLAVE ); return $dbr->selectField( 'revision', 'count(*)', 'rev_page = ' . intval( $this->getArticleId() ) . ' AND rev_id > ' . intval( $old ) . ' AND rev_id < ' . intval( $new ), __METHOD__ ); } /** * Compare with another title. * * @param \type{Title} $title * @return \type{\bool} TRUE or FALSE */ public function equals( Title $title ) { // Note: === is necessary for proper matching of number-like titles. return $this->getInterwiki() === $title->getInterwiki() && $this->getNamespace() == $title->getNamespace() && $this->getDBkey() === $title->getDBkey(); } /** * Callback for usort() to do title sorts by (namespace, title) */ public static function compare( $a, $b ) { if( $a->getNamespace() == $b->getNamespace() ) { return strcmp( $a->getText(), $b->getText() ); } else { return $a->getNamespace() - $b->getNamespace(); } } /** * Return a string representation of this title * * @return \type{\string} String representation of this title */ public function __toString() { return $this->getPrefixedText(); } /** * Check if page exists. For historical reasons, this function simply * checks for the existence of the title in the page table, and will * thus return false for interwiki links, special pages and the like. * If you want to know if a title can be meaningfully viewed, you should * probably call the isKnown() method instead. * * @return \type{\bool} TRUE or FALSE */ public function exists() { return $this->getArticleId() != 0; } /** * Should links to this title be shown as potentially viewable (i.e. as * "bluelinks"), even if there's no record by this title in the page * table? * * This function is semi-deprecated for public use, as well as somewhat * misleadingly named. You probably just want to call isKnown(), which * calls this function internally. * * (ISSUE: Most of these checks are cheap, but the file existence check * can potentially be quite expensive. Including it here fixes a lot of * existing code, but we might want to add an optional parameter to skip * it and any other expensive checks.) * * @return \type{\bool} TRUE or FALSE */ public function isAlwaysKnown() { if( $this->mInterwiki != '' ) { return true; // any interwiki link might be viewable, for all we know } switch( $this->mNamespace ) { case NS_MEDIA: case NS_FILE: return wfFindFile( $this ); // file exists, possibly in a foreign repo case NS_SPECIAL: return SpecialPage::exists( $this->getDBKey() ); // valid special page case NS_MAIN: return $this->mDbkeyform == ''; // selflink, possibly with fragment case NS_MEDIAWIKI: // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes // the full l10n of that language to be loaded. That takes much memory and // isn't needed. So we strip the language part away. // Also, extension messages which are not loaded, are shown as red, because // we don't call MessageCache::loadAllMessages. list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 ); return wfMsgWeirdKey( $basename ); // known system message default: return false; } } /** * Does this title refer to a page that can (or might) be meaningfully * viewed? In particular, this function may be used to determine if * links to the title should be rendered as "bluelinks" (as opposed to * "redlinks" to non-existent pages). * * @return \type{\bool} TRUE or FALSE */ public function isKnown() { return $this->exists() || $this->isAlwaysKnown(); } /** * Is this in a namespace that allows actual pages? * * @return \type{\bool} TRUE or FALSE */ public function canExist() { return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA; } /** * Update page_touched timestamps and send squid purge messages for * pages linking to this title. May be sent to the job queue depending * on the number of links. Typically called on create and delete. */ public function touchLinks() { $u = new HTMLCacheUpdate( $this, 'pagelinks' ); $u->doUpdate(); if ( $this->getNamespace() == NS_CATEGORY ) { $u = new HTMLCacheUpdate( $this, 'categorylinks' ); $u->doUpdate(); } } /** * Get the last touched timestamp * @param Database $db, optional db * @return \type{\string} Last touched timestamp */ public function getTouched( $db = NULL ) { $db = isset($db) ? $db : wfGetDB( DB_SLAVE ); $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ ); return $touched; } /** * Get the timestamp when this page was updated since the user last saw it. * @param User $user * @return mixed string/NULL */ public function getNotificationTimestamp( $user = NULL ) { global $wgUser, $wgShowUpdatedMarker; // Assume current user if none given if( !$user ) $user = $wgUser; // Check cache first $uid = $user->getId(); if( isset($this->mNotificationTimestamp[$uid]) ) { return $this->mNotificationTimestamp[$uid]; } if( !$uid || !$wgShowUpdatedMarker ) { return $this->mNotificationTimestamp[$uid] = false; } // Don't cache too much! if( count($this->mNotificationTimestamp) >= self::CACHE_MAX ) { $this->mNotificationTimestamp = array(); } $dbr = wfGetDB( DB_SLAVE ); $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist', 'wl_notificationtimestamp', array( 'wl_namespace' => $this->getNamespace(), 'wl_title' => $this->getDBkey(), 'wl_user' => $user->getId() ), __METHOD__ ); return $this->mNotificationTimestamp[$uid]; } /** * Get the trackback URL for this page * @return \type{\string} Trackback URL */ public function trackbackURL() { global $wgScriptPath, $wgServer, $wgScriptExtension; return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article=" . htmlspecialchars(urlencode($this->getPrefixedDBkey())); } /** * Get the trackback RDF for this page * @return \type{\string} Trackback RDF */ public function trackbackRDF() { $url = htmlspecialchars($this->getFullURL()); $title = htmlspecialchars($this->getText()); $tburl = $this->trackbackURL(); // Autodiscovery RDF is placed in comments so HTML validator // won't barf. This is a rather icky workaround, but seems // frequently used by this kind of RDF thingy. // // Spec: http://www.sixapart.com/pronet/docs/trackback_spec return "<!-- <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\"> <rdf:Description rdf:about=\"$url\" dc:identifier=\"$url\" dc:title=\"$title\" trackback:ping=\"$tburl\" /> </rdf:RDF> -->"; } /** * Generate strings used for xml 'id' names in monobook tabs * @return \type{\string} XML 'id' name */ public function getNamespaceKey() { global $wgContLang; switch ($this->getNamespace()) { case NS_MAIN: case NS_TALK: return 'nstab-main'; case NS_USER: case NS_USER_TALK: return 'nstab-user'; case NS_MEDIA: return 'nstab-media'; case NS_SPECIAL: return 'nstab-special'; case NS_PROJECT: case NS_PROJECT_TALK: return 'nstab-project'; case NS_FILE: case NS_FILE_TALK: return 'nstab-image'; case NS_MEDIAWIKI: case NS_MEDIAWIKI_TALK: return 'nstab-mediawiki'; case NS_TEMPLATE: case NS_TEMPLATE_TALK: return 'nstab-template'; case NS_HELP: case NS_HELP_TALK: return 'nstab-help'; case NS_CATEGORY: case NS_CATEGORY_TALK: return 'nstab-category'; default: return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() ); } } /** * Returns true if this title resolves to the named special page * @param $name \type{\string} The special page name */ public function isSpecial( $name ) { if ( $this->getNamespace() == NS_SPECIAL ) { list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() ); if ( $name == $thisName ) { return true; } } return false; } /** * If the Title refers to a special page alias which is not the local default, * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this. */ public function fixSpecialName() { if ( $this->getNamespace() == NS_SPECIAL ) { $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform ); if ( $canonicalName ) { $localName = SpecialPage::getLocalNameFor( $canonicalName ); if ( $localName != $this->mDbkeyform ) { return Title::makeTitle( NS_SPECIAL, $localName ); } } } return $this; } /** * Is this Title in a namespace which contains content? * In other words, is this a content page, for the purposes of calculating * statistics, etc? * * @return \type{\bool} TRUE or FALSE */ public function isContentPage() { return MWNamespace::isContent( $this->getNamespace() ); } /** * Get all extant redirects to this Title * * @param $ns \twotypes{\int,\null} Single namespace to consider; * NULL to consider all namespaces * @return \type{\arrayof{Title}} Redirects to this title */ public function getRedirectsHere( $ns = null ) { $redirs = array(); $dbr = wfGetDB( DB_SLAVE ); $where = array( 'rd_namespace' => $this->getNamespace(), 'rd_title' => $this->getDBkey(), 'rd_from = page_id' ); if ( !is_null($ns) ) $where['page_namespace'] = $ns; $res = $dbr->select( array( 'redirect', 'page' ), array( 'page_namespace', 'page_title' ), $where, __METHOD__ ); foreach( $res as $row ) { $redirs[] = self::newFromRow( $row ); } return $redirs; } /** * Check if this Title is a valid redirect target * * @return \type{\bool} TRUE or FALSE */ public function isValidRedirectTarget() { global $wgInvalidRedirectTargets; // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here if( $this->isSpecial( 'Userlogout' ) ) { return false; } foreach( $wgInvalidRedirectTargets as $target ) { if( $this->isSpecial( $target ) ) { return false; } } return true; } /** * Get a backlink cache object */ function getBacklinkCache() { if ( is_null( $this->mBacklinkCache ) ) { $this->mBacklinkCache = new BacklinkCache( $this ); } return $this->mBacklinkCache; } /** * Load the user table data for this object from the source given by mFrom. */ function load() { if ( $this->mDataLoaded ) { return; } wfProfileIn( __METHOD__ ); # Set it now to avoid infinite recursion in accessors $this->mDataLoaded = true; switch ( $this->mFrom ) { case 'defaults': $this->loadDefaults(); break; case 'name': $this->mId = self::idFromName( $this->mName ); if ( !$this->mId ) { # Nonexistent user placeholder object $this->loadDefaults( $this->mName ); } else { $this->loadFromId(); } break; case 'id': $this->loadFromId(); break; case 'session': $this->loadFromSession(); wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) ); break; default: throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" ); } wfProfileOut( __METHOD__ ); } /** * Load user table data, given mId has already been set. * @return \bool false if the ID does not exist, true otherwise * @private */ function loadFromId() { global $wgMemc; if ( $this->mId == 0 ) { $this->loadDefaults(); return false; } # Try cache $key = wfMemcKey( 'user', 'id', $this->mId ); $data = $wgMemc->get( $key ); if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) { # Object is expired, load from DB $data = false; } if ( !$data ) { wfDebug( "Cache miss for user {$this->mId}\n" ); # Load from DB if ( !$this->loadFromDatabase() ) { # Can't load from ID, user is anonymous return false; } $this->saveToCache(); } else { wfDebug( "Got user {$this->mId} from cache\n" ); # Restore from cache foreach ( self::$mCacheVars as $name ) { $this->$name = $data[$name]; } } return true; } /** * Save user data to the shared cache */ function saveToCache() { $this->load(); $this->loadGroups(); if ( $this->isAnon() ) { // Anonymous users are uncached return; } $data = array(); foreach ( self::$mCacheVars as $name ) { $data[$name] = $this->$name; } $data['mVersion'] = MW_USER_VERSION; $key = wfMemcKey( 'user', 'id', $this->mId ); global $wgMemc; $wgMemc->set( $key, $data ); } /** @name newFrom*() static factory methods */ //@{ /** * Static factory method for creation from username. * * This is slightly less efficient than newFromId(), so use newFromId() if * you have both an ID and a name handy. * * @param $name \string Username, validated by Title::newFromText() * @param $validate \mixed Validate username. Takes the same parameters as * User::getCanonicalName(), except that true is accepted as an alias * for 'valid', for BC. * * @return \type{User} The User object, or null if the username is invalid. If the * username is not present in the database, the result will be a user object * with a name, zero user ID and default settings. */ static function newFromName( $name, $validate = 'valid' ) { if ( $validate === true ) { $validate = 'valid'; } $name = self::getCanonicalName( $name, $validate ); if ( $name === false ) { return null; } else { # Create unloaded user object $u = new User; $u->mName = $name; $u->mFrom = 'name'; return $u; } } /** * Static factory method for creation from a given user ID. * * @param $id \int Valid user ID * @return \type{User} The corresponding User object */ static function newFromId( $id ) { $u = new User; $u->mId = $id; $u->mFrom = 'id'; return $u; } /** * Factory method to fetch whichever user has a given email confirmation code. * This code is generated when an account is created or its e-mail address * has changed. * * If the code is invalid or has expired, returns NULL. * * @param $code \string Confirmation code * @return \type{User} */ static function newFromConfirmationCode( $code ) { $dbr = wfGetDB( DB_SLAVE ); $id = $dbr->selectField( 'user', 'user_id', array( 'user_email_token' => md5( $code ), 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ), ) ); if( $id !== false ) { return User::newFromId( $id ); } else { return null; } } /** * Create a new user object using data from session or cookies. If the * login credentials are invalid, the result is an anonymous user. * * @return \type{User} */ static function newFromSession() { $user = new User; $user->mFrom = 'session'; return $user; } /** * Create a new user object from a user row. * The row should have all fields from the user table in it. * @param $row array A row from the user table * @return \type{User} */ static function newFromRow( $row ) { $user = new User; $user->loadFromRow( $row ); return $user; } //@} /** * Get the username corresponding to a given user ID * @param $id \int User ID * @return \string The corresponding username */ static function whoIs( $id ) { $dbr = wfGetDB( DB_SLAVE ); return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' ); } /** * Get the real name of a user given their user ID * * @param $id \int User ID * @return \string The corresponding user's real name */ static function whoIsReal( $id ) { $dbr = wfGetDB( DB_SLAVE ); return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ ); } /** * Get database id given a user name * @param $name \string Username * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent */ static function idFromName( $name ) { $nt = Title::makeTitleSafe( NS_USER, $name ); if( is_null( $nt ) ) { # Illegal name return null; } $dbr = wfGetDB( DB_SLAVE ); $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ ); if ( $s === false ) { return 0; } else { return $s->user_id; } } /** * Does the string match an anonymous IPv4 address? * * This function exists for username validation, in order to reject * usernames which are similar in form to IP addresses. Strings such * as 300.300.300.300 will return true because it looks like an IP * address, despite not being strictly valid. * * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP * address because the usemod software would "cloak" anonymous IP * addresses like this, if we allowed accounts like this to be created * new users could get the old edits of these anonymous users. * * @param $name \string String to match * @return \bool True or false */ static function isIP( $name ) { return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name); } /** * Is the input a valid username? * * Checks if the input is a valid username, we don't want an empty string, * an IP address, anything that containins slashes (would mess up subpages), * is longer than the maximum allowed username size or doesn't begin with * a capital letter. * * @param $name \string String to match * @return \bool True or false */ static function isValidUserName( $name ) { global $wgContLang, $wgMaxNameChars; if ( $name == '' || User::isIP( $name ) || strpos( $name, '/' ) !== false || strlen( $name ) > $wgMaxNameChars || $name != $wgContLang->ucfirst( $name ) ) { wfDebugLog( 'username', __METHOD__ . ": '$name' invalid due to empty, IP, slash, length, or lowercase" ); return false; } // Ensure that the name can't be misresolved as a different title, // such as with extra namespace keys at the start. $parsed = Title::newFromText( $name ); if( is_null( $parsed ) || $parsed->getNamespace() || strcmp( $name, $parsed->getPrefixedText() ) ) { wfDebugLog( 'username', __METHOD__ . ": '$name' invalid due to ambiguous prefixes" ); return false; } // Check an additional blacklist of troublemaker characters. // Should these be merged into the title char list? $unicodeBlacklist = '/[' . '\x{0080}-\x{009f}' . # iso-8859-1 control chars '\x{00a0}' . # non-breaking space '\x{2000}-\x{200f}' . # various whitespace '\x{2028}-\x{202f}' . # breaks and control chars '\x{3000}' . # ideographic space '\x{e000}-\x{f8ff}' . # private use ']/u'; if( preg_match( $unicodeBlacklist, $name ) ) { wfDebugLog( 'username', __METHOD__ . ": '$name' invalid due to blacklisted characters" ); return false; } return true; } /** * Usernames which fail to pass this function will be blocked * from user login and new account registrations, but may be used * internally by batch processes. * * If an account already exists in this form, login will be blocked * by a failure to pass this function. * * @param $name \string String to match * @return \bool True or false */ static function isUsableName( $name ) { global $wgReservedUsernames; // Must be a valid username, obviously ;) if ( !self::isValidUserName( $name ) ) { return false; } static $reservedUsernames = false; if ( !$reservedUsernames ) { $reservedUsernames = $wgReservedUsernames; wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) ); } // Certain names may be reserved for batch processes. foreach ( $reservedUsernames as $reserved ) { if ( substr( $reserved, 0, 4 ) == 'msg:' ) { $reserved = wfMsgForContent( substr( $reserved, 4 ) ); } if ( $reserved == $name ) { return false; } } return true; } /** * Usernames which fail to pass this function will be blocked * from new account registrations, but may be used internally * either by batch processes or by user accounts which have * already been created. * * Additional character blacklisting may be added here * rather than in isValidUserName() to avoid disrupting * existing accounts. * * @param $name \string String to match * @return \bool True or false */ static function isCreatableName( $name ) { global $wgInvalidUsernameCharacters; return self::isUsableName( $name ) && // Registration-time character blacklisting... !preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ); } /** * Is the input a valid password for this user? * * @param $password \string Desired password * @return \bool True or false */ function isValidPassword( $password ) { global $wgMinimalPasswordLength, $wgContLang; $result = null; if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) return $result; if( $result === false ) return false; // Password needs to be long enough, and can't be the same as the username return strlen( $password ) >= $wgMinimalPasswordLength && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName ); } /** * Does a string look like an e-mail address? * * There used to be a regular expression here, it got removed because it * rejected valid addresses. Actually just check if there is '@' somewhere * in the given address. * * @todo Check for RFC 2822 compilance (bug 959) * * @param $addr \string E-mail address * @return \bool True or false */ public static function isValidEmailAddr( $addr ) { $result = null; if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) { return $result; } return strpos( $addr, '@' ) !== false; } /** * Given unvalidated user input, return a canonical username, or false if * the username is invalid. * @param $name \string User input * @param $validate \types{\string,\bool} Type of validation to use: * - false No validation * - 'valid' Valid for batch processes * - 'usable' Valid for batch processes and login * - 'creatable' Valid for batch processes, login and account creation */ static function getCanonicalName( $name, $validate = 'valid' ) { # Force usernames to capital global $wgContLang; $name = $wgContLang->ucfirst( $name ); # Reject names containing '#'; these will be cleaned up # with title normalisation, but then it's too late to # check elsewhere if( strpos( $name, '#' ) !== false ) return false; # Clean up name according to title rules $t = ($validate === 'valid') ? Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name ); # Check for invalid titles if( is_null( $t ) ) { return false; } # Reject various classes of invalid names $name = $t->getText(); global $wgAuth; $name = $wgAuth->getCanonicalName( $t->getText() ); switch ( $validate ) { case false: break; case 'valid': if ( !User::isValidUserName( $name ) ) { $name = false; } break; case 'usable': if ( !User::isUsableName( $name ) ) { $name = false; } break; case 'creatable': if ( !User::isCreatableName( $name ) ) { $name = false; } break; default: throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ ); } return $name; } /** * Count the number of edits of a user * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas * * @param $uid \int User ID to check * @return \int The user's edit count */ static function edits( $uid ) { wfProfileIn( __METHOD__ ); $dbr = wfGetDB( DB_SLAVE ); // check if the user_editcount field has been initialized $field = $dbr->selectField( 'user', 'user_editcount', array( 'user_id' => $uid ), __METHOD__ ); if( $field === null ) { // it has not been initialized. do so. $dbw = wfGetDB( DB_MASTER ); $count = $dbr->selectField( 'revision', 'count(*)', array( 'rev_user' => $uid ), __METHOD__ ); $dbw->update( 'user', array( 'user_editcount' => $count ), array( 'user_id' => $uid ), __METHOD__ ); } else { $count = $field; } wfProfileOut( __METHOD__ ); return $count; } /** * Return a random password. Sourced from mt_rand, so it's not particularly secure. * @todo hash random numbers to improve security, like generateToken() * * @return \string New random password */ static function randomPassword() { global $wgMinimalPasswordLength; $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz'; $l = strlen( $pwchars ) - 1; $pwlength = max( 7, $wgMinimalPasswordLength ); $digit = mt_rand(0, $pwlength - 1); $np = ''; for ( $i = 0; $i < $pwlength; $i++ ) { $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)}; } return $np; } /** * Set cached properties to default. * * @note This no longer clears uncached lazy-initialised properties; * the constructor does that instead. * @private */ function loadDefaults( $name = false ) { wfProfileIn( __METHOD__ ); global $wgCookiePrefix; $this->mId = 0; $this->mName = $name; $this->mRealName = ''; $this->mPassword = $this->mNewpassword = ''; $this->mNewpassTime = null; $this->mEmail = ''; $this->mOptions = null; # Defer init if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) { $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] ); } else { $this->mTouched = '0'; # Allow any pages to be cached } $this->setToken(); # Random $this->mEmailAuthenticated = null; $this->mEmailToken = ''; $this->mEmailTokenExpires = null; $this->mRegistration = wfTimestamp( TS_MW ); $this->mGroups = array(); wfRunHooks( 'UserLoadDefaults', array( $this, $name ) ); wfProfileOut( __METHOD__ ); } /** * @deprecated Use wfSetupSession(). */ function SetupSession() { wfDeprecated( __METHOD__ ); wfSetupSession(); } /** * Load user data from the session or login cookie. If there are no valid * credentials, initialises the user as an anonymous user. * @return \bool True if the user is logged in, false otherwise. */ private function loadFromSession() { global $wgMemc, $wgCookiePrefix; $result = null; wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) ); if ( $result !== null ) { return $result; } if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) { $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] ); if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) { $this->loadDefaults(); // Possible collision! wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and cookie user ID ($sId) don't match!" ); return false; } $_SESSION['wsUserID'] = $sId; } else if ( isset( $_SESSION['wsUserID'] ) ) { if ( $_SESSION['wsUserID'] != 0 ) { $sId = $_SESSION['wsUserID']; } else { $this->loadDefaults(); return false; } } else { $this->loadDefaults(); return false; } if ( isset( $_SESSION['wsUserName'] ) ) { $sName = $_SESSION['wsUserName']; } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) { $sName = $_COOKIE["{$wgCookiePrefix}UserName"]; $_SESSION['wsUserName'] = $sName; } else { $this->loadDefaults(); return false; } $passwordCorrect = FALSE; $this->mId = $sId; if ( !$this->loadFromId() ) { # Not a valid ID, loadFromId has switched the object to anon for us return false; } if ( isset( $_SESSION['wsToken'] ) ) { $passwordCorrect = $_SESSION['wsToken'] == $this->mToken; $from = 'session'; } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) { $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"]; $from = 'cookie'; } else { # No session or persistent login cookie $this->loadDefaults(); return false; } if ( ( $sName == $this->mName ) && $passwordCorrect ) { $_SESSION['wsToken'] = $this->mToken; wfDebug( "Logged in from $from\n" ); return true; } else { # Invalid credentials wfDebug( "Can't log in from $from, invalid credentials\n" ); $this->loadDefaults(); return false; } } /** * Load user and user_group data from the database. * $this::mId must be set, this is how the user is identified. * * @return \bool True if the user exists, false if the user is anonymous * @private */ function loadFromDatabase() { # Paranoia $this->mId = intval( $this->mId ); /** Anonymous user */ if( !$this->mId ) { $this->loadDefaults(); return false; } $dbr = wfGetDB( DB_MASTER ); $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ ); wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) ); if ( $s !== false ) { # Initialise user table data $this->loadFromRow( $s ); $this->mGroups = null; // deferred $this->getEditCount(); // revalidation for nulls return true; } else { # Invalid user_id $this->mId = 0; $this->loadDefaults(); return false; } } /** * Initialize this object from a row from the user table. * * @param $row \type{\arrayof{\mixed}} Row from the user table to load. */ function loadFromRow( $row ) { $this->mDataLoaded = true; if ( isset( $row->user_id ) ) { $this->mId = intval( $row->user_id ); } $this->mName = $row->user_name; $this->mRealName = $row->user_real_name; $this->mPassword = $row->user_password; $this->mNewpassword = $row->user_newpassword; $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time ); $this->mEmail = $row->user_email; $this->decodeOptions( $row->user_options ); $this->mTouched = wfTimestamp(TS_MW,$row->user_touched); $this->mToken = $row->user_token; $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated ); $this->mEmailToken = $row->user_email_token; $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires ); $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration ); $this->mEditCount = $row->user_editcount; } /** * Load the groups from the database if they aren't already loaded. * @private */ function loadGroups() { if ( is_null( $this->mGroups ) ) { $dbr = wfGetDB( DB_MASTER ); $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ), __METHOD__ ); $this->mGroups = array(); while( $row = $dbr->fetchObject( $res ) ) { $this->mGroups[] = $row->ug_group; } } } /** * Clear various cached data stored in this object. * @param $reloadFrom \string Reload user and user_groups table data from a * given source. May be "name", "id", "defaults", "session", or false for * no reload. */ function clearInstanceCache( $reloadFrom = false ) { $this->mNewtalk = -1; $this->mDatePreference = null; $this->mBlockedby = -1; # Unset $this->mHash = false; $this->mSkin = null; $this->mRights = null; $this->mEffectiveGroups = null; if ( $reloadFrom ) { $this->mDataLoaded = false; $this->mFrom = $reloadFrom; } } /** * Combine the language default options with any site-specific options * and add the default language variants. * * @return \type{\arrayof{\string}} Array of options */ static function getDefaultOptions() { global $wgNamespacesToBeSearchedDefault; /** * Site defaults will override the global/language defaults */ global $wgDefaultUserOptions, $wgContLang; $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides(); /** * default language setting */ $variant = $wgContLang->getPreferredVariant( false ); $defOpt['variant'] = $variant; $defOpt['language'] = $variant; foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) { $defOpt['searchNs'.$nsnum] = $val; } return $defOpt; } /** * Get a given default option value. * * @param $opt \string Name of option to retrieve * @return \string Default option value */ public static function getDefaultOption( $opt ) { $defOpts = self::getDefaultOptions(); if( isset( $defOpts[$opt] ) ) { return $defOpts[$opt]; } else { return ''; } } /** * Get a list of user toggle names * @return \type{\arrayof{\string}} Array of user toggle names */ static function getToggles() { global $wgContLang, $wgUseRCPatrol; $extraToggles = array(); wfRunHooks( 'UserToggles', array( &$extraToggles ) ); if( $wgUseRCPatrol ) { $extraToggles[] = 'hidepatrolled'; $extraToggles[] = 'newpageshidepatrolled'; $extraToggles[] = 'watchlisthidepatrolled'; } return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() ); } /** * Get blocking information * @private * @param $bFromSlave \bool Whether to check the slave database first. To * improve performance, non-critical checks are done * against slaves. Check when actually saving should be * done against master. */ function getBlockedStatus( $bFromSlave = true ) { global $wgEnableSorbs, $wgProxyWhitelist; if ( -1 != $this->mBlockedby ) { wfDebug( "User::getBlockedStatus: already loaded.\n" ); return; } wfProfileIn( __METHOD__ ); wfDebug( __METHOD__.": checking...\n" ); // Initialize data... // Otherwise something ends up stomping on $this->mBlockedby when // things get lazy-loaded later, causing false positive block hits // due to -1 !== 0. Probably session-related... Nothing should be // overwriting mBlockedby, surely? $this->load(); $this->mBlockedby = 0; $this->mHideName = 0; $this->mAllowUsertalk = 0; $ip = wfGetIP(); if ($this->isAllowed( 'ipblock-exempt' ) ) { # Exempt from all types of IP-block $ip = ''; } # User/IP blocking $this->mBlock = new Block(); $this->mBlock->fromMaster( !$bFromSlave ); if ( $this->mBlock->load( $ip , $this->mId ) ) { wfDebug( __METHOD__.": Found block.\n" ); $this->mBlockedby = $this->mBlock->mBy; $this->mBlockreason = $this->mBlock->mReason; $this->mHideName = $this->mBlock->mHideName; $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk; if ( $this->isLoggedIn() ) { $this->spreadBlock(); } } else { // Bug 13611: don't remove mBlock here, to allow account creation blocks to // apply to users. Note that the existence of $this->mBlock is not used to // check for edit blocks, $this->mBlockedby is instead. } # Proxy blocking if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) { # Local list if ( wfIsLocallyBlockedProxy( $ip ) ) { $this->mBlockedby = wfMsg( 'proxyblocker' ); $this->mBlockreason = wfMsg( 'proxyblockreason' ); } # DNSBL if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) { if ( $this->inSorbsBlacklist( $ip ) ) { $this->mBlockedby = wfMsg( 'sorbs' ); $this->mBlockreason = wfMsg( 'sorbsreason' ); } } } # Extensions wfRunHooks( 'GetBlockedStatus', array( &$this ) ); wfProfileOut( __METHOD__ ); } /** * Whether the given IP is in the SORBS blacklist. * * @param $ip \string IP to check * @return \bool True if blacklisted. */ function inSorbsBlacklist( $ip ) { global $wgEnableSorbs, $wgSorbsUrl; return $wgEnableSorbs && $this->inDnsBlacklist( $ip, $wgSorbsUrl ); } /** * Whether the given IP is in a given DNS blacklist. * * @param $ip \string IP to check * @param $base \string URL of the DNS blacklist * @return \bool True if blacklisted. */ function inDnsBlacklist( $ip, $base ) { wfProfileIn( __METHOD__ ); $found = false; $host = ''; // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170) if( IP::isIPv4($ip) ) { # Make hostname $host = "$ip.$base"; # Send query $ipList = gethostbynamel( $host ); if( $ipList ) { wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" ); $found = true; } else { wfDebug( "Requested $host, not found in $base.\n" ); } } wfProfileOut( __METHOD__ ); return $found; } /** * Is this user subject to rate limiting? * * @return \bool True if rate limited */ public function isPingLimitable() { global $wgRateLimitsExcludedGroups; global $wgRateLimitsExcludedIPs; if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) { // Deprecated, but kept for backwards-compatibility config return false; } if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) { // No other good way currently to disable rate limits // for specific IPs. :P // But this is a crappy hack and should die. return false; } return !$this->isAllowed('noratelimit'); } /** * Primitive rate limits: enforce maximum actions per time period * to put a brake on flooding. * * @note When using a shared cache like memcached, IP-address * last-hit counters will be shared across wikis. * * @param $action \string Action to enforce; 'edit' if unspecified * @return \bool True if a rate limiter was tripped */ function pingLimiter( $action='edit' ) { # Call the 'PingLimiter' hook $result = false; if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) { return $result; } global $wgRateLimits; if( !isset( $wgRateLimits[$action] ) ) { return false; } # Some groups shouldn't trigger the ping limiter, ever if( !$this->isPingLimitable() ) return false; global $wgMemc, $wgRateLimitLog; wfProfileIn( __METHOD__ ); $limits = $wgRateLimits[$action]; $keys = array(); $id = $this->getId(); $ip = wfGetIP(); $userLimit = false; if( isset( $limits['anon'] ) && $id == 0 ) { $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon']; } if( isset( $limits['user'] ) && $id != 0 ) { $userLimit = $limits['user']; } if( $this->isNewbie() ) { if( isset( $limits['newbie'] ) && $id != 0 ) { $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie']; } if( isset( $limits['ip'] ) ) { $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip']; } $matches = array(); if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) { $subnet = $matches[1]; $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet']; } } // Check for group-specific permissions // If more than one group applies, use the group with the highest limit foreach ( $this->getGroups() as $group ) { if ( isset( $limits[$group] ) ) { if ( $userLimit === false || $limits[$group] > $userLimit ) { $userLimit = $limits[$group]; } } } // Set the user limit key if ( $userLimit !== false ) { wfDebug( __METHOD__.": effective user limit: $userLimit\n" ); $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit; } $triggered = false; foreach( $keys as $key => $limit ) { list( $max, $period ) = $limit; $summary = "(limit $max in {$period}s)"; $count = $wgMemc->get( $key ); if( $count ) { if( $count > $max ) { wfDebug( __METHOD__.": tripped! $key at $count $summary\n" ); if( $wgRateLimitLog ) { @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog ); } $triggered = true; } else { wfDebug( __METHOD__.": ok. $key at $count $summary\n" ); } } else { wfDebug( __METHOD__.": adding record for $key $summary\n" ); $wgMemc->add( $key, 1, intval( $period ) ); } $wgMemc->incr( $key ); } wfProfileOut( __METHOD__ ); return $triggered; } /** * Check if user is blocked * * @param $bFromSlave \bool Whether to check the slave database instead of the master * @return \bool True if blocked, false otherwise */ function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site wfDebug( "User::isBlocked: enter\n" ); $this->getBlockedStatus( $bFromSlave ); return $this->mBlockedby !== 0; } /** * Check if user is blocked from editing a particular article * * @param $title \string Title to check * @param $bFromSlave \bool Whether to check the slave database instead of the master * @return \bool True if blocked, false otherwise */ function isBlockedFrom( $title, $bFromSlave = false ) { global $wgBlockAllowsUTEdit; wfProfileIn( __METHOD__ ); wfDebug( __METHOD__.": enter\n" ); wfDebug( __METHOD__.": asking isBlocked()\n" ); $blocked = $this->isBlocked( $bFromSlave ); $allowUsertalk = ($wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false); # If a user's name is suppressed, they cannot make edits anywhere if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() && $title->getNamespace() == NS_USER_TALK ) { $blocked = false; wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" ); } wfProfileOut( __METHOD__ ); return $blocked; } /** * If user is blocked, return the name of the user who placed the block * @return \string name of blocker */ function blockedBy() { $this->getBlockedStatus(); return $this->mBlockedby; } /** * If user is blocked, return the specified reason for the block * @return \string Blocking reason */ function blockedFor() { $this->getBlockedStatus(); return $this->mBlockreason; } /** * If user is blocked, return the ID for the block * @return \int Block ID */ function getBlockId() { $this->getBlockedStatus(); return ($this->mBlock ? $this->mBlock->mId : false); } /** * Check if user is blocked on all wikis. * Do not use for actual edit permission checks! * This is intented for quick UI checks. * * @param $ip \type{\string} IP address, uses current client if none given * @return \type{\bool} True if blocked, false otherwise */ function isBlockedGlobally( $ip = '' ) { if( $this->mBlockedGlobally !== null ) { return $this->mBlockedGlobally; } // User is already an IP? if( IP::isIPAddress( $this->getName() ) ) { $ip = $this->getName(); } else if( !$ip ) { $ip = wfGetIP(); } $blocked = false; wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) ); $this->mBlockedGlobally = (bool)$blocked; return $this->mBlockedGlobally; } /** * Check if user account is locked * * @return \type{\bool} True if locked, false otherwise */ function isLocked() { if( $this->mLocked !== null ) { return $this->mLocked; } global $wgAuth; $authUser = $wgAuth->getUserInstance( $this ); $this->mLocked = (bool)$authUser->isLocked(); return $this->mLocked; } /** * Check if user account is hidden * * @return \type{\bool} True if hidden, false otherwise */ function isHidden() { if( $this->mHideName !== null ) { return $this->mHideName; } $this->getBlockedStatus(); if( !$this->mHideName ) { global $wgAuth; $authUser = $wgAuth->getUserInstance( $this ); $this->mHideName = (bool)$authUser->isHidden(); } return $this->mHideName; } /** * Get the user's ID. * @return \int The user's ID; 0 if the user is anonymous or nonexistent */ function getId() { if( $this->mId === null and $this->mName !== null and User::isIP( $this->mName ) ) { // Special case, we know the user is anonymous return 0; } elseif( $this->mId === null ) { // Don't load if this was initialized from an ID $this->load(); } return $this->mId; } /** * Set the user and reload all fields according to a given ID * @param $v \int User ID to reload */ function setId( $v ) { $this->mId = $v; $this->clearInstanceCache( 'id' ); } /** * Get the user name, or the IP of an anonymous user * @return \string User's name or IP address */ function getName() { if ( !$this->mDataLoaded && $this->mFrom == 'name' ) { # Special case optimisation return $this->mName; } else { $this->load(); if ( $this->mName === false ) { # Clean up IPs $this->mName = IP::sanitizeIP( wfGetIP() ); } return $this->mName; } } /** * Set the user name. * * This does not reload fields from the database according to the given * name. Rather, it is used to create a temporary "nonexistent user" for * later addition to the database. It can also be used to set the IP * address for an anonymous user to something other than the current * remote IP. * * @note User::newFromName() has rougly the same function, when the named user * does not exist. * @param $str \string New user name to set */ function setName( $str ) { $this->load(); $this->mName = $str; } /** * Get the user's name escaped by underscores. * @return \string Username escaped by underscores. */ function getTitleKey() { return str_replace( ' ', '_', $this->getName() ); } /** * Check if the user has new messages. * @return \bool True if the user has new messages */ function getNewtalk() { $this->load(); # Load the newtalk status if it is unloaded (mNewtalk=-1) if( $this->mNewtalk === -1 ) { $this->mNewtalk = false; # reset talk page status # Check memcached separately for anons, who have no # entire User object stored in there. if( !$this->mId ) { global $wgMemc; $key = wfMemcKey( 'newtalk', 'ip', $this->getName() ); $newtalk = $wgMemc->get( $key ); if( strval( $newtalk ) !== '' ) { $this->mNewtalk = (bool)$newtalk; } else { // Since we are caching this, make sure it is up to date by getting it // from the master $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true ); $wgMemc->set( $key, (int)$this->mNewtalk, 1800 ); } } else { $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId ); } } return (bool)$this->mNewtalk; } /** * Return the talk page(s) this user has new messages on. * @return \type{\arrayof{\string}} Array of page URLs */ function getNewMessageLinks() { $talks = array(); if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks))) return $talks; if (!$this->getNewtalk()) return array(); $up = $this->getUserPage(); $utp = $up->getTalkPage(); return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL())); } /** * Internal uncached check for new messages * * @see getNewtalk() * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise * @param $fromMaster \bool true to fetch from the master, false for a slave * @return \bool True if the user has new messages * @private */ function checkNewtalk( $field, $id, $fromMaster = false ) { if ( $fromMaster ) { $db = wfGetDB( DB_MASTER ); } else { $db = wfGetDB( DB_SLAVE ); } $ok = $db->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__ ); return $ok !== false; } /** * Add or update the new messages flag * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise * @return \bool True if successful, false otherwise * @private */ function updateNewtalk( $field, $id ) { $dbw = wfGetDB( DB_MASTER ); $dbw->insert( 'user_newtalk', array( $field => $id ), __METHOD__, 'IGNORE' ); if ( $dbw->affectedRows() ) { wfDebug( __METHOD__.": set on ($field, $id)\n" ); return true; } else { wfDebug( __METHOD__." already set ($field, $id)\n" ); return false; } } /** * Clear the new messages flag for the given user * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise * @return \bool True if successful, false otherwise * @private */ function deleteNewtalk( $field, $id ) { $dbw = wfGetDB( DB_MASTER ); $dbw->delete( 'user_newtalk', array( $field => $id ), __METHOD__ ); if ( $dbw->affectedRows() ) { wfDebug( __METHOD__.": killed on ($field, $id)\n" ); return true; } else { wfDebug( __METHOD__.": already gone ($field, $id)\n" ); return false; } } /** * Update the 'You have new messages!' status. * @param $val \bool Whether the user has new messages */ function setNewtalk( $val ) { if( wfReadOnly() ) { return; } $this->load(); $this->mNewtalk = $val; if( $this->isAnon() ) { $field = 'user_ip'; $id = $this->getName(); } else { $field = 'user_id'; $id = $this->getId(); } global $wgMemc; if( $val ) { $changed = $this->updateNewtalk( $field, $id ); } else { $changed = $this->deleteNewtalk( $field, $id ); } if( $this->isAnon() ) { // Anons have a separate memcached space, since // user records aren't kept for them. $key = wfMemcKey( 'newtalk', 'ip', $id ); $wgMemc->set( $key, $val ? 1 : 0, 1800 ); } if ( $changed ) { $this->invalidateCache(); } } /** * Generate a current or new-future timestamp to be stored in the * user_touched field when we update things. * @return \string Timestamp in TS_MW format */ private static function newTouchedTimestamp() { global $wgClockSkewFudge; return wfTimestamp( TS_MW, time() + $wgClockSkewFudge ); } /** * Clear user data from memcached. * Use after applying fun updates to the database; caller's * responsibility to update user_touched if appropriate. * * Called implicitly from invalidateCache() and saveSettings(). */ private function clearSharedCache() { $this->load(); if( $this->mId ) { global $wgMemc; $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) ); } } /** * Immediately touch the user data cache for this account. * Updates user_touched field, and removes account data from memcached * for reload on the next hit. */ function invalidateCache() { $this->load(); if( $this->mId ) { $this->mTouched = self::newTouchedTimestamp(); $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'user', array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ), array( 'user_id' => $this->mId ), __METHOD__ ); $this->clearSharedCache(); } } /** * Validate the cache for this account. * @param $timestamp \string A timestamp in TS_MW format */ function validateCache( $timestamp ) { $this->load(); return ($timestamp >= $this->mTouched); } /** * Get the user touched timestamp */ function getTouched() { $this->load(); return $this->mTouched; } /** * Set the password and reset the random token. * Calls through to authentication plugin if necessary; * will have no effect if the auth plugin refuses to * pass the change through or if the legal password * checks fail. * * As a special case, setting the password to null * wipes it, so the account cannot be logged in until * a new password is set, for instance via e-mail. * * @param $str \string New password to set * @throws PasswordError on failure */ function setPassword( $str ) { global $wgAuth; if( $str !== null ) { if( !$wgAuth->allowPasswordChange() ) { throw new PasswordError( wfMsg( 'password-change-forbidden' ) ); } if( !$this->isValidPassword( $str ) ) { global $wgMinimalPasswordLength; throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ), $wgMinimalPasswordLength ) ); } } if( !$wgAuth->setPassword( $this, $str ) ) { throw new PasswordError( wfMsg( 'externaldberror' ) ); } $this->setInternalPassword( $str ); return true; } /** * Set the password and reset the random token unconditionally. * * @param $str \string New password to set */ function setInternalPassword( $str ) { $this->load(); $this->setToken(); if( $str === null ) { // Save an invalid hash... $this->mPassword = ''; } else { $this->mPassword = self::crypt( $str ); } $this->mNewpassword = ''; $this->mNewpassTime = null; } /** * Get the user's current token. * @return \string Token */ function getToken() { $this->load(); return $this->mToken; } /** * Set the random token (used for persistent authentication) * Called from loadDefaults() among other places. * * @param $token \string If specified, set the token to this value * @private */ function setToken( $token = false ) { global $wgSecretKey, $wgProxyKey; $this->load(); if ( !$token ) { if ( $wgSecretKey ) { $key = $wgSecretKey; } elseif ( $wgProxyKey ) { $key = $wgProxyKey; } else { $key = microtime(); } $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId ); } else { $this->mToken = $token; } } /** * Set the cookie password * * @param $str \string New cookie password * @private */ function setCookiePassword( $str ) { $this->load(); $this->mCookiePassword = md5( $str ); } /** * Set the password for a password reminder or new account email * * @param $str \string New password to set * @param $throttle \bool If true, reset the throttle timestamp to the present */ function setNewpassword( $str, $throttle = true ) { $this->load(); $this->mNewpassword = self::crypt( $str ); if ( $throttle ) { $this->mNewpassTime = wfTimestampNow(); } } /** * Has password reminder email been sent within the last * $wgPasswordReminderResendTime hours? * @return \bool True or false */ function isPasswordReminderThrottled() { global $wgPasswordReminderResendTime; $this->load(); if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) { return false; } $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600; return time() < $expiry; } /** * Get the user's e-mail address * @return \string User's email address */ function getEmail() { $this->load(); wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) ); return $this->mEmail; } /** * Get the timestamp of the user's e-mail authentication * @return \string TS_MW timestamp */ function getEmailAuthenticationTimestamp() { $this->load(); wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) ); return $this->mEmailAuthenticated; } /** * Set the user's e-mail address * @param $str \string New e-mail address */ function setEmail( $str ) { $this->load(); $this->mEmail = $str; wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) ); } /** * Get the user's real name * @return \string User's real name */ function getRealName() { $this->load(); return $this->mRealName; } /** * Set the user's real name * @param $str \string New real name */ function setRealName( $str ) { $this->load(); $this->mRealName = $str; } /** * Get the user's current setting for a given option. * * @param $oname \string The option to check * @param $defaultOverride \string A default value returned if the option does not exist * @return \string User's current value for the option * @see getBoolOption() * @see getIntOption() */ function getOption( $oname, $defaultOverride = '' ) { $this->load(); if ( is_null( $this->mOptions ) ) { if($defaultOverride != '') { return $defaultOverride; } $this->mOptions = User::getDefaultOptions(); } if ( array_key_exists( $oname, $this->mOptions ) ) { return trim( $this->mOptions[$oname] ); } else { return $defaultOverride; } } /** * Get the user's current setting for a given option, as a boolean value. * * @param $oname \string The option to check * @return \bool User's current value for the option * @see getOption() */ function getBoolOption( $oname ) { return (bool)$this->getOption( $oname ); } /** * Get the user's current setting for a given option, as a boolean value. * * @param $oname \string The option to check * @param $defaultOverride \int A default value returned if the option does not exist * @return \int User's current value for the option * @see getOption() */ function getIntOption( $oname, $defaultOverride=0 ) { $val = $this->getOption( $oname ); if( $val == '' ) { $val = $defaultOverride; } return intval( $val ); } /** * Set the given option for a user. * * @param $oname \string The option to set * @param $val \mixed New value to set */ function setOption( $oname, $val ) { $this->load(); if ( is_null( $this->mOptions ) ) { $this->mOptions = User::getDefaultOptions(); } if ( $oname == 'skin' ) { # Clear cached skin, so the new one displays immediately in Special:Preferences unset( $this->mSkin ); } // Filter out any newlines that may have passed through input validation. // Newlines are used to separate items in the options blob. if( $val ) { $val = str_replace( "\r\n", "\n", $val ); $val = str_replace( "\r", "\n", $val ); $val = str_replace( "\n", " ", $val ); } // Explicitly NULL values should refer to defaults global $wgDefaultUserOptions; if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) { $val = $wgDefaultUserOptions[$oname]; } $this->mOptions[$oname] = $val; } /** * Reset all options to the site defaults */ function restoreOptions() { $this->mOptions = User::getDefaultOptions(); } /** * Get the user's preferred date format. * @return \string User's preferred date format */ function getDatePreference() { // Important migration for old data rows if ( is_null( $this->mDatePreference ) ) { global $wgLang; $value = $this->getOption( 'date' ); $map = $wgLang->getDatePreferenceMigrationMap(); if ( isset( $map[$value] ) ) { $value = $map[$value]; } $this->mDatePreference = $value; } return $this->mDatePreference; } /** * Get the permissions this user has. * @return \type{\arrayof{\string}} Array of permission names */ function getRights() { if ( is_null( $this->mRights ) ) { $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() ); wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) ); // Force reindexation of rights when a hook has unset one of them $this->mRights = array_values( $this->mRights ); } return $this->mRights; } /** * Get the list of explicit group memberships this user has. * The implicit * and user groups are not included. * @return \type{\arrayof{\string}} Array of internal group names */ function getGroups() { $this->load(); return $this->mGroups; } /** * Get the list of implicit group memberships this user has. * This includes all explicit groups, plus 'user' if logged in, * '*' for all accounts and autopromoted groups * @param $recache \bool Whether to avoid the cache * @return \type{\arrayof{\string}} Array of internal group names */ function getEffectiveGroups( $recache = false ) { if ( $recache || is_null( $this->mEffectiveGroups ) ) { $this->mEffectiveGroups = $this->getGroups(); $this->mEffectiveGroups[] = '*'; if( $this->getId() ) { $this->mEffectiveGroups[] = 'user'; $this->mEffectiveGroups = array_unique( array_merge( $this->mEffectiveGroups, Autopromote::getAutopromoteGroups( $this ) ) ); # Hook for additional groups wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) ); } } return $this->mEffectiveGroups; } /** * Get the user's edit count. * @return \int User'e edit count */ function getEditCount() { if ($this->getId()) { if ( !isset( $this->mEditCount ) ) { /* Populate the count, if it has not been populated yet */ $this->mEditCount = User::edits($this->mId); } return $this->mEditCount; } else { /* nil */ return null; } } /** * Add the user to the given group. * This takes immediate effect. * @param $group \string Name of the group to add */ function addGroup( $group ) { $dbw = wfGetDB( DB_MASTER ); if( $this->getId() ) { $dbw->insert( 'user_groups', array( 'ug_user' => $this->getID(), 'ug_group' => $group, ), 'User::addGroup', array( 'IGNORE' ) ); } $this->loadGroups(); $this->mGroups[] = $group; $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) ); $this->invalidateCache(); } /** * Remove the user from the given group. * This takes immediate effect. * @param $group \string Name of the group to remove */ function removeGroup( $group ) { $this->load(); $dbw = wfGetDB( DB_MASTER ); $dbw->delete( 'user_groups', array( 'ug_user' => $this->getID(), 'ug_group' => $group, ), 'User::removeGroup' ); $this->loadGroups(); $this->mGroups = array_diff( $this->mGroups, array( $group ) ); $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) ); $this->invalidateCache(); } /** * Get whether the user is logged in * @return \bool True or false */ function isLoggedIn() { return $this->getID() != 0; } /** * Get whether the user is anonymous * @return \bool True or false */ function isAnon() { return !$this->isLoggedIn(); } /** * Get whether the user is a bot * @return \bool True or false * @deprecated */ function isBot() { wfDeprecated( __METHOD__ ); return $this->isAllowed( 'bot' ); } /** * Check if user is allowed to access a feature / make an action * @param $action \string action to be checked * @return \bool True if action is allowed, else false */ function isAllowed( $action = '' ) { if ( $action === '' ) return true; // In the spirit of DWIM # Patrolling may not be enabled if( $action === 'patrol' || $action === 'autopatrol' ) { global $wgUseRCPatrol, $wgUseNPPatrol; if( !$wgUseRCPatrol && !$wgUseNPPatrol ) return false; } # Use strict parameter to avoid matching numeric 0 accidentally inserted # by misconfiguration: 0 == 'foo' return in_array( $action, $this->getRights(), true ); } /** * Check whether to enable recent changes patrol features for this user * @return \bool True or false */ public function useRCPatrol() { global $wgUseRCPatrol; return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) ); } /** * Check whether to enable new pages patrol features for this user * @return \bool True or false */ public function useNPPatrol() { global $wgUseRCPatrol, $wgUseNPPatrol; return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) ); } /** * Get the current skin, loading it if required * @return \type{Skin} Current skin * @todo FIXME : need to check the old failback system [AV] */ function &getSkin() { global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin; if ( ! isset( $this->mSkin ) ) { wfProfileIn( __METHOD__ ); if( $wgAllowUserSkin ) { # get the user skin $userSkin = $this->getOption( 'skin' ); $userSkin = $wgRequest->getVal('useskin', $userSkin); } else { # if we're not allowing users to override, then use the default $userSkin = $wgDefaultSkin; } $this->mSkin =& Skin::newFromKey( $userSkin ); wfProfileOut( __METHOD__ ); } return $this->mSkin; } /** * Check the watched status of an article. * @param $title \type{Title} Title of the article to look at * @return \bool True if article is watched */ function isWatched( $title ) { $wl = WatchedItem::fromUserTitle( $this, $title ); return $wl->isWatched(); } /** * Watch an article. * @param $title \type{Title} Title of the article to look at */ function addWatch( $title ) { $wl = WatchedItem::fromUserTitle( $this, $title ); $wl->addWatch(); $this->invalidateCache(); } /** * Stop watching an article. * @param $title \type{Title} Title of the article to look at */ function removeWatch( $title ) { $wl = WatchedItem::fromUserTitle( $this, $title ); $wl->removeWatch(); $this->invalidateCache(); } /** * Clear the user's notification timestamp for the given title. * If e-notif e-mails are on, they will receive notification mails on * the next change of the page if it's watched etc. * @param $title \type{Title} Title of the article to look at */ function clearNotification( &$title ) { global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker; # Do nothing if the database is locked to writes if( wfReadOnly() ) { return; } if ($title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) { if (!wfRunHooks('UserClearNewTalkNotification', array(&$this))) return; $this->setNewtalk( false ); } if( !$wgUseEnotif && !$wgShowUpdatedMarker ) { return; } if( $this->isAnon() ) { // Nothing else to do... return; } // Only update the timestamp if the page is being watched. // The query to find out if it is watched is cached both in memcached and per-invocation, // and when it does have to be executed, it can be on a slave // If this is the user's newtalk page, we always update the timestamp if ($title->getNamespace() == NS_USER_TALK && $title->getText() == $wgUser->getName()) { $watched = true; } elseif ( $this->getId() == $wgUser->getId() ) { $watched = $title->userIsWatching(); } else { $watched = true; } // If the page is watched by the user (or may be watched), update the timestamp on any // any matching rows if ( $watched ) { $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'watchlist', array( /* SET */ 'wl_notificationtimestamp' => NULL ), array( /* WHERE */ 'wl_title' => $title->getDBkey(), 'wl_namespace' => $title->getNamespace(), 'wl_user' => $this->getID() ), __METHOD__ ); } } /** * Resets all of the given user's page-change notification timestamps. * If e-notif e-mails are on, they will receive notification mails on * the next change of any watched page. * * @param $currentUser \int User ID */ function clearAllNotifications( $currentUser ) { global $wgUseEnotif, $wgShowUpdatedMarker; if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) { $this->setNewtalk( false ); return; } if( $currentUser != 0 ) { $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'watchlist', array( /* SET */ 'wl_notificationtimestamp' => NULL ), array( /* WHERE */ 'wl_user' => $currentUser ), __METHOD__ ); # We also need to clear here the "you have new message" notification for the own user_talk page # This is cleared one page view later in Article::viewUpdates(); } } /** * Encode this user's options as a string * @return \string Encoded options * @private */ function encodeOptions() { $this->load(); if ( is_null( $this->mOptions ) ) { $this->mOptions = User::getDefaultOptions(); } $a = array(); foreach ( $this->mOptions as $oname => $oval ) { array_push( $a, $oname.'='.$oval ); } $s = implode( "\n", $a ); return $s; } /** * Set this user's options from an encoded string * @param $str \string Encoded options to import * @private */ function decodeOptions( $str ) { $this->mOptions = array(); $a = explode( "\n", $str ); foreach ( $a as $s ) { $m = array(); if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) { $this->mOptions[$m[1]] = $m[2]; } } } /** * Set a cookie on the user's client. Wrapper for * WebResponse::setCookie * @param $name \string Name of the cookie to set * @param $value \string Value to set * @param $exp \int Expiration time, as a UNIX time value; * if 0 or not specified, use the default $wgCookieExpiration */ protected function setCookie( $name, $value, $exp=0 ) { global $wgRequest; $wgRequest->response()->setcookie( $name, $value, $exp ); } /** * Clear a cookie on the user's client * @param $name \string Name of the cookie to clear */ protected function clearCookie( $name ) { $this->setCookie( $name, '', time() - 86400 ); } /** * Set the default cookies for this session on the user's client. */ function setCookies() { $this->load(); if ( 0 == $this->mId ) return; $session = array( 'wsUserID' => $this->mId, 'wsToken' => $this->mToken, 'wsUserName' => $this->getName() ); $cookies = array( 'UserID' => $this->mId, 'UserName' => $this->getName(), ); if ( 1 == $this->getOption( 'rememberpassword' ) ) { $cookies['Token'] = $this->mToken; } else { $cookies['Token'] = false; } wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) ); #check for null, since the hook could cause a null value if ( !is_null( $session ) && isset( $_SESSION ) ){ $_SESSION = $session + $_SESSION; } foreach ( $cookies as $name => $value ) { if ( $value === false ) { $this->clearCookie( $name ); } else { $this->setCookie( $name, $value ); } } } /** * Log this user out. */ function logout() { global $wgUser; if( wfRunHooks( 'UserLogout', array(&$this) ) ) { $this->doLogout(); } } /** * Clear the user's cookies and session, and reset the instance cache. * @private * @see logout() */ function doLogout() { $this->clearInstanceCache( 'defaults' ); $_SESSION['wsUserID'] = 0; $this->clearCookie( 'UserID' ); $this->clearCookie( 'Token' ); # Remember when user logged out, to prevent seeing cached pages $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 ); } /** * Save this user's settings into the database. * @todo Only rarely do all these fields need to be set! */ function saveSettings() { $this->load(); if ( wfReadOnly() ) { return; } if ( 0 == $this->mId ) { return; } $this->mTouched = self::newTouchedTimestamp(); $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'user', array( /* SET */ 'user_name' => $this->mName, 'user_password' => $this->mPassword, 'user_newpassword' => $this->mNewpassword, 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ), 'user_real_name' => $this->mRealName, 'user_email' => $this->mEmail, 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ), 'user_options' => $this->encodeOptions(), 'user_touched' => $dbw->timestamp($this->mTouched), 'user_token' => $this->mToken, 'user_email_token' => $this->mEmailToken, 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ), ), array( /* WHERE */ 'user_id' => $this->mId ), __METHOD__ ); wfRunHooks( 'UserSaveSettings', array( $this ) ); $this->clearSharedCache(); $this->getUserPage()->invalidateCache(); } /** * If only this user's username is known, and it exists, return the user ID. */ function idForName() { $s = trim( $this->getName() ); if ( $s === '' ) return 0; $dbr = wfGetDB( DB_SLAVE ); $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ ); if ( $id === false ) { $id = 0; } return $id; } /** * Add a user to the database, return the user object * * @param $name \string Username to add * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database: * - password The user's password. Password logins will be disabled if this is omitted. * - newpassword A temporary password mailed to the user * - email The user's email address * - email_authenticated The email authentication timestamp * - real_name The user's real name * - options An associative array of non-default options * - token Random authentication token. Do not set. * - registration Registration timestamp. Do not set. * * @return \type{User} A new User object, or null if the username already exists */ static function createNew( $name, $params = array() ) { $user = new User; $user->load(); if ( isset( $params['options'] ) ) { $user->mOptions = $params['options'] + $user->mOptions; unset( $params['options'] ); } $dbw = wfGetDB( DB_MASTER ); $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' ); $fields = array( 'user_id' => $seqVal, 'user_name' => $name, 'user_password' => $user->mPassword, 'user_newpassword' => $user->mNewpassword, 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ), 'user_email' => $user->mEmail, 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ), 'user_real_name' => $user->mRealName, 'user_options' => $user->encodeOptions(), 'user_token' => $user->mToken, 'user_registration' => $dbw->timestamp( $user->mRegistration ), 'user_editcount' => 0, ); foreach ( $params as $name => $value ) { $fields["user_$name"] = $value; } $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) ); if ( $dbw->affectedRows() ) { $newUser = User::newFromId( $dbw->insertId() ); } else { $newUser = null; } return $newUser; } /** * Add this existing user object to the database */ function addToDatabase() { $this->load(); $dbw = wfGetDB( DB_MASTER ); $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' ); $dbw->insert( 'user', array( 'user_id' => $seqVal, 'user_name' => $this->mName, 'user_password' => $this->mPassword, 'user_newpassword' => $this->mNewpassword, 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ), 'user_email' => $this->mEmail, 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ), 'user_real_name' => $this->mRealName, 'user_options' => $this->encodeOptions(), 'user_token' => $this->mToken, 'user_registration' => $dbw->timestamp( $this->mRegistration ), 'user_editcount' => 0, ), __METHOD__ ); $this->mId = $dbw->insertId(); // Clear instance cache other than user table data, which is already accurate $this->clearInstanceCache(); } /** * If this (non-anonymous) user is blocked, block any IP address * they've successfully logged in from. */ function spreadBlock() { wfDebug( __METHOD__."()\n" ); $this->load(); if ( $this->mId == 0 ) { return; } $userblock = Block::newFromDB( '', $this->mId ); if ( !$userblock ) { return; } $userblock->doAutoblock( wfGetIp() ); } /** * Generate a string which will be different for any combination of * user options which would produce different parser output. * This will be used as part of the hash key for the parser cache, * so users will the same options can share the same cached data * safely. * * Extensions which require it should install 'PageRenderingHash' hook, * which will give them a chance to modify this key based on their own * settings. * * @return \string Page rendering hash */ function getPageRenderingHash() { global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang; if( $this->mHash ){ return $this->mHash; } // stubthreshold is only included below for completeness, // it will always be 0 when this function is called by parsercache. $confstr = $this->getOption( 'math' ); $confstr .= '!' . $this->getOption( 'stubthreshold' ); if ( $wgUseDynamicDates ) { $confstr .= '!' . $this->getDatePreference(); } $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : ''); $confstr .= '!' . $wgLang->getCode(); $confstr .= '!' . $this->getOption( 'thumbsize' ); // add in language specific options, if any $extra = $wgContLang->getExtraHashOptions(); $confstr .= $extra; $confstr .= $wgRenderHashAppend; // Give a chance for extensions to modify the hash, if they have // extra options or other effects on the parser cache. wfRunHooks( 'PageRenderingHash', array( &$confstr ) ); // Make it a valid memcached key fragment $confstr = str_replace( ' ', '_', $confstr ); $this->mHash = $confstr; return $confstr; } /** * Get whether the user is explicitly blocked from account creation. * @return \bool True if blocked */ function isBlockedFromCreateAccount() { $this->getBlockedStatus(); return $this->mBlock && $this->mBlock->mCreateAccount; } /** * Get whether the user is blocked from using Special:Emailuser. * @return \bool True if blocked */ function isBlockedFromEmailuser() { $this->getBlockedStatus(); return $this->mBlock && $this->mBlock->mBlockEmail; } /** * Get whether the user is allowed to create an account. * @return \bool True if allowed */ function isAllowedToCreateAccount() { return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount(); } /** * @deprecated */ function setLoaded( $loaded ) { wfDeprecated( __METHOD__ ); } /** * Get this user's personal page title. * * @return \type{Title} User's personal page title */ function getUserPage() { return Title::makeTitle( NS_USER, $this->getName() ); } /** * Get this user's talk page title. * * @return \type{Title} User's talk page title */ function getTalkPage() { $title = $this->getUserPage(); return $title->getTalkPage(); } /** * Get the maximum valid user ID. * @return \int User ID * @static */ function getMaxID() { static $res; // cache if ( isset( $res ) ) return $res; else { $dbr = wfGetDB( DB_SLAVE ); return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' ); } } /** * Determine whether the user is a newbie. Newbies are either * anonymous IPs, or the most recently created accounts. * @return \bool True if the user is a newbie */ function isNewbie() { return !$this->isAllowed( 'autoconfirmed' ); } /** * Is the user active? We check to see if they've made at least * X number of edits in the last Y days. * * @return \bool True if the user is active, false if not. */ public function isActiveEditor() { global $wgActiveUserEditCount, $wgActiveUserDays; $dbr = wfGetDB( DB_SLAVE ); // Stolen without shame from RC $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 ); $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 ); $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) ); $res = $dbr->select( 'revision', '1', array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"), __METHOD__, array('LIMIT' => $wgActiveUserEditCount ) ); $count = $dbr->numRows($res); $dbr->freeResult($res); return $count == $wgActiveUserEditCount; } /** * Check to see if the given clear-text password is one of the accepted passwords * @param $password \string user password. * @return \bool True if the given password is correct, otherwise False. */ function checkPassword( $password ) { global $wgAuth; $this->load(); // Even though we stop people from creating passwords that // are shorter than this, doesn't mean people wont be able // to. Certain authentication plugins do NOT want to save // domain passwords in a mysql database, so we should // check this (incase $wgAuth->strict() is false). if( !$this->isValidPassword( $password ) ) { return false; } if( $wgAuth->authenticate( $this->getName(), $password ) ) { return true; } elseif( $wgAuth->strict() ) { /* Auth plugin doesn't allow local authentication */ return false; } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) { /* Auth plugin doesn't allow local authentication for this user name */ return false; } if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) { return true; } elseif ( function_exists( 'iconv' ) ) { # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted # Check for this with iconv $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ); if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) { return true; } } return false; } /** * Check if the given clear-text password matches the temporary password * sent by e-mail for password reset operations. * @return \bool True if matches, false otherwise */ function checkTemporaryPassword( $plaintext ) { global $wgNewPasswordExpiry; if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) { $this->load(); $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry; return ( time() < $expiry ); } else { return false; } } /** * Initialize (if necessary) and return a session token value * which can be used in edit forms to show that the user's * login credentials aren't being hijacked with a foreign form * submission. * * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing * @return \string The new edit token */ function editToken( $salt = '' ) { if ( $this->isAnon() ) { return EDIT_TOKEN_SUFFIX; } else { if( !isset( $_SESSION['wsEditToken'] ) ) { $token = self::generateToken(); $_SESSION['wsEditToken'] = $token; } else { $token = $_SESSION['wsEditToken']; } if( is_array( $salt ) ) { $salt = implode( '|', $salt ); } return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX; } } /** * Generate a looking random token for various uses. * * @param $salt \string Optional salt value * @return \string The new random token */ public static function generateToken( $salt = '' ) { $token = dechex( mt_rand() ) . dechex( mt_rand() ); return md5( $token . $salt ); } /** * Check given value against the token value stored in the session. * A match should confirm that the form was submitted from the * user's own login session, not a form submission from a third-party * site. * * @param $val \string Input value to compare * @param $salt \string Optional function-specific data for hashing * @return \bool Whether the token matches */ function matchEditToken( $val, $salt = '' ) { $sessionToken = $this->editToken( $salt ); if ( $val != $sessionToken ) { wfDebug( "User::matchEditToken: broken session data\n" ); } return $val == $sessionToken; } /** * Check given value against the token value stored in the session, * ignoring the suffix. * * @param $val \string Input value to compare * @param $salt \string Optional function-specific data for hashing * @return \bool Whether the token matches */ function matchEditTokenNoSuffix( $val, $salt = '' ) { $sessionToken = $this->editToken( $salt ); return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 ); } /** * Generate a new e-mail confirmation token and send a confirmation/invalidation * mail to the user's given address. * * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure. */ function sendConfirmationMail() { global $wgLang; $expiration = null; // gets passed-by-ref and defined in next line. $token = $this->confirmationToken( $expiration ); $url = $this->confirmationTokenUrl( $token ); $invalidateURL = $this->invalidationTokenUrl( $token ); $this->saveSettings(); return $this->sendMail( wfMsg( 'confirmemail_subject' ), wfMsg( 'confirmemail_body', wfGetIP(), $this->getName(), $url, $wgLang->timeanddate( $expiration, false ), $invalidateURL ) ); } /** * Send an e-mail to this user's account. Does not check for * confirmed status or validity. * * @param $subject \string Message subject * @param $body \string Message body * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used * @param $replyto \string Reply-To address * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure */ function sendMail( $subject, $body, $from = null, $replyto = null ) { if( is_null( $from ) ) { global $wgPasswordSender; $from = $wgPasswordSender; } $to = new MailAddress( $this ); $sender = new MailAddress( $from ); return UserMailer::send( $to, $sender, $subject, $body, $replyto ); } /** * Generate, store, and return a new e-mail confirmation code. * A hash (unsalted, since it's used as a key) is stored. * * @note Call saveSettings() after calling this function to commit * this change to the database. * * @param[out] &$expiration \mixed Accepts the expiration time * @return \string New token * @private */ function confirmationToken( &$expiration ) { $now = time(); $expires = $now + 7 * 24 * 60 * 60; $expiration = wfTimestamp( TS_MW, $expires ); $token = self::generateToken( $this->mId . $this->mEmail . $expires ); $hash = md5( $token ); $this->load(); $this->mEmailToken = $hash; $this->mEmailTokenExpires = $expiration; return $token; } /** * Return a URL the user can use to confirm their email address. * @param $token \string Accepts the email confirmation token * @return \string New token URL * @private */ function confirmationTokenUrl( $token ) { return $this->getTokenUrl( 'ConfirmEmail', $token ); } /** * Return a URL the user can use to invalidate their email address. * @param $token \string Accepts the email confirmation token * @return \string New token URL * @private */ function invalidationTokenUrl( $token ) { return $this->getTokenUrl( 'Invalidateemail', $token ); } /** * Internal function to format the e-mail validation/invalidation URLs. * This uses $wgArticlePath directly as a quickie hack to use the * hardcoded English names of the Special: pages, for ASCII safety. * * @note Since these URLs get dropped directly into emails, using the * short English names avoids insanely long URL-encoded links, which * also sometimes can get corrupted in some browsers/mailers * (bug 6957 with Gmail and Internet Explorer). * * @param $page \string Special page * @param $token \string Token * @return \string Formatted URL */ protected function getTokenUrl( $page, $token ) { global $wgArticlePath; return wfExpandUrl( str_replace( '$1', "Special:$page/$token", $wgArticlePath ) ); } /** * Mark the e-mail address confirmed. * * @note Call saveSettings() after calling this function to commit the change. */ function confirmEmail() { $this->setEmailAuthenticationTimestamp( wfTimestampNow() ); return true; } /** * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail * address if it was already confirmed. * * @note Call saveSettings() after calling this function to commit the change. */ function invalidateEmail() { $this->load(); $this->mEmailToken = null; $this->mEmailTokenExpires = null; $this->setEmailAuthenticationTimestamp( null ); return true; } /** * Set the e-mail authentication timestamp. * @param $timestamp \string TS_MW timestamp */ function setEmailAuthenticationTimestamp( $timestamp ) { $this->load(); $this->mEmailAuthenticated = $timestamp; wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) ); } /** * Is this user allowed to send e-mails within limits of current * site configuration? * @return \bool True if allowed */ function canSendEmail() { global $wgEnableEmail, $wgEnableUserEmail; if( !$wgEnableEmail || !$wgEnableUserEmail ) { return false; } $canSend = $this->isEmailConfirmed(); wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) ); return $canSend; } /** * Is this user allowed to receive e-mails within limits of current * site configuration? * @return \bool True if allowed */ function canReceiveEmail() { return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' ); } /** * Is this user's e-mail address valid-looking and confirmed within * limits of the current site configuration? * * @note If $wgEmailAuthentication is on, this may require the user to have * confirmed their address by returning a code or using a password * sent to the address from the wiki. * * @return \bool True if confirmed */ function isEmailConfirmed() { global $wgEmailAuthentication; $this->load(); $confirmed = true; if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) { if( $this->isAnon() ) return false; if( !self::isValidEmailAddr( $this->mEmail ) ) return false; if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) return false; return true; } else { return $confirmed; } } /** * Check whether there is an outstanding request for e-mail confirmation. * @return \bool True if pending */ function isEmailConfirmationPending() { global $wgEmailAuthentication; return $wgEmailAuthentication && !$this->isEmailConfirmed() && $this->mEmailToken && $this->mEmailTokenExpires > wfTimestamp(); } /** * Get the timestamp of account creation. * * @return \types{\string,\bool} string Timestamp of account creation, or false for * non-existent/anonymous user accounts. */ public function getRegistration() { return $this->getId() > 0 ? $this->mRegistration : false; } /** * Get the timestamp of the first edit * * @return \types{\string,\bool} string Timestamp of first edit, or false for * non-existent/anonymous user accounts. */ public function getFirstEditTimestamp() { if( $this->getId() == 0 ) return false; // anons $dbr = wfGetDB( DB_SLAVE ); $time = $dbr->selectField( 'revision', 'rev_timestamp', array( 'rev_user' => $this->getId() ), __METHOD__, array( 'ORDER BY' => 'rev_timestamp ASC' ) ); if( !$time ) return false; // no edits return wfTimestamp( TS_MW, $time ); } /** * Get the permissions associated with a given list of groups * * @param $groups \type{\arrayof{\string}} List of internal group names * @return \type{\arrayof{\string}} List of permission key names for given groups combined */ static function getGroupPermissions( $groups ) { global $wgGroupPermissions; $rights = array(); foreach( $groups as $group ) { if( isset( $wgGroupPermissions[$group] ) ) { $rights = array_merge( $rights, // array_filter removes empty items array_keys( array_filter( $wgGroupPermissions[$group] ) ) ); } } return array_unique($rights); } /** * Get all the groups who have a given permission * * @param $role \string Role to check * @return \type{\arrayof{\string}} List of internal group names with the given permission */ static function getGroupsWithPermission( $role ) { global $wgGroupPermissions; $allowedGroups = array(); foreach ( $wgGroupPermissions as $group => $rights ) { if ( isset( $rights[$role] ) && $rights[$role] ) { $allowedGroups[] = $group; } } return $allowedGroups; } /** * Get the localized descriptive name for a group, if it exists * * @param $group \string Internal group name * @return \string Localized descriptive group name */ static function getGroupName( $group ) { global $wgMessageCache; $wgMessageCache->loadAllMessages(); $key = "group-$group"; $name = wfMsg( $key ); return $name == '' || wfEmptyMsg( $key, $name ) ? $group : $name; } /** * Get the localized descriptive name for a member of a group, if it exists * * @param $group \string Internal group name * @return \string Localized name for group member */ static function getGroupMember( $group ) { global $wgMessageCache; $wgMessageCache->loadAllMessages(); $key = "group-$group-member"; $name = wfMsg( $key ); return $name == '' || wfEmptyMsg( $key, $name ) ? $group : $name; } /** * Return the set of defined explicit groups. * The implicit groups (by default *, 'user' and 'autoconfirmed') * are not included, as they are defined automatically, not in the database. * @return \type{\arrayof{\string}} Array of internal group names */ static function getAllGroups() { global $wgGroupPermissions; return array_diff( array_keys( $wgGroupPermissions ), self::getImplicitGroups() ); } /** * Get a list of all available permissions. * @return \type{\arrayof{\string}} Array of permission names */ static function getAllRights() { if ( self::$mAllRights === false ) { global $wgAvailableRights; if ( count( $wgAvailableRights ) ) { self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) ); } else { self::$mAllRights = self::$mCoreRights; } wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) ); } return self::$mAllRights; } /** * Get a list of implicit groups * @return \type{\arrayof{\string}} Array of internal group names */ public static function getImplicitGroups() { global $wgImplicitGroups; $groups = $wgImplicitGroups; wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead return $groups; } /** * Get the title of a page describing a particular group * * @param $group \string Internal group name * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise */ static function getGroupPage( $group ) { global $wgMessageCache; $wgMessageCache->loadAllMessages(); $page = wfMsgForContent( 'grouppage-' . $group ); if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) { $title = Title::newFromText( $page ); if( is_object( $title ) ) return $title; } return false; } /** * Create a link to the group in HTML, if available; * else return the group name. * * @param $group \string Internal name of the group * @param $text \string The text of the link * @return \string HTML link to the group */ static function makeGroupLinkHTML( $group, $text = '' ) { if( $text == '' ) { $text = self::getGroupName( $group ); } $title = self::getGroupPage( $group ); if( $title ) { global $wgUser; $sk = $wgUser->getSkin(); return $sk->makeLinkObj( $title, htmlspecialchars( $text ) ); } else { return $text; } } /** * Create a link to the group in Wikitext, if available; * else return the group name. * * @param $group \string Internal name of the group * @param $text \string The text of the link * @return \string Wikilink to the group */ static function makeGroupLinkWiki( $group, $text = '' ) { if( $text == '' ) { $text = self::getGroupName( $group ); } $title = self::getGroupPage( $group ); if( $title ) { $page = $title->getPrefixedText(); return "[[$page|$text]]"; } else { return $text; } } /** * Increment the user's edit-count field. * Will have no effect for anonymous users. */ function incEditCount() { if( !$this->isAnon() ) { $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'user', array( 'user_editcount=user_editcount+1' ), array( 'user_id' => $this->getId() ), __METHOD__ ); // Lazy initialization check... if( $dbw->affectedRows() == 0 ) { // Pull from a slave to be less cruel to servers // Accuracy isn't the point anyway here $dbr = wfGetDB( DB_SLAVE ); $count = $dbr->selectField( 'revision', 'COUNT(rev_user)', array( 'rev_user' => $this->getId() ), __METHOD__ ); // Now here's a goddamn hack... if( $dbr !== $dbw ) { // If we actually have a slave server, the count is // at least one behind because the current transaction // has not been committed and replicated. $count++; } else { // But if DB_SLAVE is selecting the master, then the // count we just read includes the revision that was // just added in the working transaction. } $dbw->update( 'user', array( 'user_editcount' => $count ), array( 'user_id' => $this->getId() ), __METHOD__ ); } } // edit count in user cache too $this->invalidateCache(); } /** * Get the description of a given right * * @param $right \string Right to query * @return \string Localized description of the right */ static function getRightDescription( $right ) { global $wgMessageCache; $wgMessageCache->loadAllMessages(); $key = "right-$right"; $name = wfMsg( $key ); return $name == '' || wfEmptyMsg( $key, $name ) ? $right : $name; } /** * Make an old-style password hash * * @param $password \string Plain-text password * @param $userId \string User ID * @return \string Password hash */ static function oldCrypt( $password, $userId ) { global $wgPasswordSalt; if ( $wgPasswordSalt ) { return md5( $userId . '-' . md5( $password ) ); } else { return md5( $password ); } } /** * Make a new-style password hash * * @param $password \string Plain-text password * @param $salt \string Optional salt, may be random or the user ID. * If unspecified or false, will generate one automatically * @return \string Password hash */ static function crypt( $password, $salt = false ) { global $wgPasswordSalt; $hash = ''; if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) { return $hash; } if( $wgPasswordSalt ) { if ( $salt === false ) { $salt = substr( wfGenerateToken(), 0, 8 ); } return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) ); } else { return ':A:' . md5( $password ); } } /** * Compare a password hash with a plain-text password. Requires the user * ID if there's a chance that the hash is an old-style hash. * * @param $hash \string Password hash * @param $password \string Plain-text password to compare * @param $userId \string User ID for old-style password salt * @return \bool */ static function comparePasswords( $hash, $password, $userId = false ) { $m = false; $type = substr( $hash, 0, 3 ); $result = false; if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) { return $result; } if ( $type == ':A:' ) { # Unsalted return md5( $password ) === substr( $hash, 3 ); } elseif ( $type == ':B:' ) { # Salted list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 ); return md5( $salt.'-'.md5( $password ) ) == $realHash; } else { # Old-style return self::oldCrypt( $password, $userId ) === $hash; } } /** * Add a newuser log entry for this user * @param $byEmail Boolean: account made by email? */ public function addNewUserLogEntry( $byEmail = false ) { global $wgUser, $wgContLang, $wgNewUserLog; if( empty($wgNewUserLog) ) { return true; // disabled } $talk = $wgContLang->getFormattedNsText( NS_TALK ); if( $this->getName() == $wgUser->getName() ) { $action = 'create'; $message = ''; } else { $action = 'create2'; $message = $byEmail ? wfMsgForContent( 'newuserlog-byemail' ) : ''; } $log = new LogPage( 'newusers' ); $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) ); return true; } /** * Add an autocreate newuser log entry for this user * Used by things like CentralAuth and perhaps other authplugins. */ public function addNewUserLogEntryAutoCreate() { global $wgNewUserLog; if( empty($wgNewUserLog) ) { return true; // disabled } $log = new LogPage( 'newusers', false ); $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) ); return true; } function setHeaders() { global $wgOut, $wgTitle; $wgOut->setRobotPolicy( 'noindex,nofollow' ); if ( $this->formtype == 'preview' ) { $wgOut->setPageTitleActionText( wfMsg( 'preview' ) ); } if ( $this->isConflict ) { $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) ); } elseif ( $this->section != '' ) { $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection'; $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) ); } else { # Use the title defined by DISPLAYTITLE magic word when present if ( isset($this->mParserOutput) && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) { $title = $dt; } else { $title = $wgTitle->getPrefixedText(); } $wgOut->setPageTitle( wfMsg( 'editing', $title ) ); } } /** * Send the edit form and related headers to $wgOut * @param $formCallback Optional callable that takes an OutputPage * parameter; will be called during form output * near the top, for captchas and the like. */ function showEditForm( $formCallback=null ) { global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest; # If $wgTitle is null, that means we're in API mode. # Some hook probably called this function without checking # for is_null($wgTitle) first. Bail out right here so we don't # do lots of work just to discard it right after. if (is_null($wgTitle)) return; $fname = 'EditPage::showEditForm'; wfProfileIn( $fname ); $sk = $wgUser->getSkin(); wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ; #need to parse the preview early so that we know which templates are used, #otherwise users with "show preview after edit box" will get a blank list #we parse this near the beginning so that setHeaders can do the title #setting work instead of leaving it in getPreviewText $previewOutput = ''; if ( $this->formtype == 'preview' ) { $previewOutput = $this->getPreviewText(); } $this->setHeaders(); # Enabled article-related sidebar, toplinks, etc. $wgOut->setArticleRelated( true ); if ( $this->isConflict ) { $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' ); $this->textbox2 = $this->textbox1; $this->textbox1 = $this->getContent(); $this->edittime = $this->mArticle->getTimestamp(); } else { if ( $this->section != '' && $this->section != 'new' ) { $matches = array(); if ( !$this->summary && !$this->preview && !$this->diff ) { preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches ); if ( !empty( $matches[2] ) ) { global $wgParser; $this->summary = "/* " . $wgParser->stripSectionName(trim($matches[2])) . " */ "; } } } if ( $this->missingComment ) { $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' ); } if ( $this->missingSummary && $this->section != 'new' ) { $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' ); } if ( $this->missingSummary && $this->section == 'new' ) { $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' ); } if ( $this->hookError !== '' ) { $wgOut->addWikiText( $this->hookError ); } if ( !$this->checkUnicodeCompliantBrowser() ) { $wgOut->addWikiMsg( 'nonunicodebrowser' ); } if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) { // Let sysop know that this will make private content public if saved if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) { $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' ); } else if ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) { $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' ); } if ( !$this->mArticle->mRevision->isCurrent() ) { $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() ); $wgOut->addWikiMsg( 'editingold' ); } } } if ( wfReadOnly() ) { $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) ); } elseif ( $wgUser->isAnon() && $this->formtype != 'preview' ) { $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' ); } else { if ( $this->isCssJsSubpage ) { # Check the skin exists if ( $this->isValidCssJsSubpage ) { if ( $this->formtype !== 'preview' ) { $wgOut->addWikiMsg( 'usercssjsyoucanpreview' ); } } else { $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() ); } } } $classes = array(); // Textarea CSS if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) { } elseif ( $this->mTitle->isProtected( 'edit' ) ) { # Is the title semi-protected? if ( $this->mTitle->isSemiProtected() ) { $noticeMsg = 'semiprotectedpagewarning'; $classes[] = 'mw-textarea-sprotected'; } else { # Then it must be protected based on static groups (regular) $noticeMsg = 'protectedpagewarning'; $classes[] = 'mw-textarea-protected'; } $wgOut->addHTML( "<div class='mw-warning-with-logexcerpt'>\n" ); $wgOut->addWikiMsg( $noticeMsg ); LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '', 1 ); $wgOut->addHTML( "</div>\n" ); } if ( $this->mTitle->isCascadeProtected() ) { # Is this page under cascading protection from some source pages? list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources(); $notice = "<div class='mw-cascadeprotectedwarning'>$1\n"; $cascadeSourcesCount = count( $cascadeSources ); if ( $cascadeSourcesCount > 0 ) { # Explain, and list the titles responsible foreach( $cascadeSources as $page ) { $notice .= '* [[:' . $page->getPrefixedText() . "]]\n"; } } $notice .= '</div>'; $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) ); } if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) { $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' ); } if ( $this->kblength === false ) { $this->kblength = (int)(strlen( $this->textbox1 ) / 1024); } if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) { $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" ); $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ); $wgOut->addHTML( "</div>\n" ); } elseif ( $this->kblength > 29 ) { $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" ); $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ); $wgOut->addHTML( "</div>\n" ); } $q = 'action='.$this->action; #if ( "no" == $redirect ) { $q .= "&redirect=no"; } $action = $wgTitle->escapeLocalURL( $q ); $summary = wfMsg( 'summary' ); $subject = wfMsg( 'subject' ); $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(), wfMsgExt('cancel', array('parseinline')) ); $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' ); $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' )); $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'. htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '. htmlspecialchars( wfMsg( 'newwindow' ) ); global $wgRightsText; if ( $wgRightsText ) { $copywarnMsg = array( 'copyrightwarning', '[[' . wfMsgForContent( 'copyrightpage' ) . ']]', $wgRightsText ); } else { $copywarnMsg = array( 'copyrightwarning2', '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' ); } if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) { # prepare toolbar for edit buttons $toolbar = EditPage::getEditToolbar(); } else { $toolbar = ''; } // activate checkboxes if user wants them to be always active if ( !$this->preview && !$this->diff ) { # Sort out the "watch" checkbox if ( $wgUser->getOption( 'watchdefault' ) ) { # Watch all edits $this->watchthis = true; } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) { # Watch creations $this->watchthis = true; } elseif ( $this->mTitle->userIsWatching() ) { # Already watched $this->watchthis = true; } # May be overriden by request parameters if( $wgRequest->getBool( 'watchthis' ) ) { $this->watchthis = true; } if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true; } $wgOut->addHTML( $this->editFormPageTop ); if ( $wgUser->getOption( 'previewontop' ) ) { $this->displayPreviewArea( $previewOutput, true ); } $wgOut->addHTML( $this->editFormTextTop ); # if this is a comment, show a subject line at the top, which is also the edit summary. # Otherwise, show a summary field at the bottom $summarytext = $wgContLang->recodeForEdit( $this->summary ); # If a blank edit summary was previously provided, and the appropriate # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the # user being bounced back more than once in the event that a summary # is not required. ##### # For a bit more sophisticated detection of blank summaries, hash the # automatic one and pass that in the hidden field wpAutoSummary. $summaryhiddens = ''; if ( $this->missingSummary ) $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true ); $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary ); $summaryhiddens .= Xml::hidden( 'wpAutoSummary', $autosumm ); if ( $this->section == 'new' ) { $commentsubject = ''; if ( !$wgRequest->getBool( 'nosummary' ) ) { # Add a class if 'missingsummary' is triggered to allow styling of the summary line $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary'; $commentsubject = Xml::tags( 'label', array( 'for' => 'wpSummary' ), $subject ); $commentsubject = Xml::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ), $commentsubject ); $commentsubject .= ' '; $commentsubject .= Xml::input( 'wpSummary', 60, $summarytext, array( 'id' => 'wpSummary', 'maxlength' => '200', 'tabindex' => '1' ) ); } $editsummary = "<div class='editOptions'>\n"; global $wgParser; $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary ) ); $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">". wfMsg('subject-preview') . $sk->commentBlock( $formattedSummary, $this->mTitle, true )."</div>\n" : ''; $summarypreview = ''; } else { $commentsubject = ''; # Add a class if 'missingsummary' is triggered to allow styling of the summary line $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary'; $editsummary = Xml::tags( 'label', array( 'for' => 'wpSummary' ), $summary ); $editsummary = Xml::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ), $editsummary ) . ' '; $editsummary .= Xml::input( 'wpSummary', 60, $summarytext, array( 'id' => 'wpSummary', 'maxlength' => '200', 'tabindex' => '1' ) ); // No idea where this is closed. $editsummary = Xml::openElement( 'div', array( 'class' => 'editOptions' ) ) . $editsummary . '<br/>'; $summarypreview = ''; if ( $summarytext && $this->preview ) { $summarypreview = Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), wfMsg( 'summary-preview' ) . $sk->commentBlock( $this->summary, $this->mTitle ) ); } $subjectpreview = ''; } $commentsubject .= $summaryhiddens; # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display if ( !$this->preview && !$this->diff ) { $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' ); } $templates = $this->getTemplates(); $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != ''); $hiddencats = $this->mArticle->getHiddenCategories(); $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats ); global $wgUseMetadataEdit ; if ( $wgUseMetadataEdit ) { $metadata = $this->mMetaData ; $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ; $top = wfMsgWikiHtml( 'metadata_help' ); /* ToDo: Replace with clean code */ $ew = $wgUser->getOption( 'editwidth' ); if ( $ew ) $ew = " style=\"width:100%\""; else $ew = ''; $cols = $wgUser->getIntOption( 'cols' ); /* /ToDo */ $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ; } else $metadata = "" ; $recreate = ''; if ( $this->wasDeletedSinceLastEdit() ) { if ( 'save' != $this->formtype ) { $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1</div>", 'deletedwhileediting' ); } else { // Hide the toolbar and edit area, user can click preview to get it back // Add an confirmation checkbox and explanation. $toolbar = ''; $recreate = '<div class="mw-confirm-recreate">' . $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ) ) . Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false, array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ) ) . '</div>'; } } $tabindex = 2; $checkboxes = $this->getCheckboxes( $tabindex, $sk, array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) ); $checkboxhtml = implode( $checkboxes, "\n" ); $buttons = $this->getEditButtons( $tabindex ); $buttonshtml = implode( $buttons, "\n" ); $safemodehtml = $this->checkUnicodeCompliantBrowser() ? '' : Xml::hidden( 'safemode', '1' ); $wgOut->addHTML( <<<END {$toolbar} <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data"> END ); if ( is_callable( $formCallback ) ) { call_user_func_array( $formCallback, array( &$wgOut ) ); } wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) ); // Put these up at the top to ensure they aren't lost on early form submission $this->showFormBeforeText(); $wgOut->addHTML( <<<END {$recreate} {$commentsubject} {$subjectpreview} {$this->editFormTextBeforeContent} END ); $this->showTextbox1( $classes ); $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg ); $wgOut->addHTML( <<<END {$this->editFormTextAfterWarn} {$metadata} {$editsummary} {$summarypreview} {$checkboxhtml} {$safemodehtml} END ); $wgOut->addHTML( "<div class='editButtons'> {$buttonshtml} <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span> </div><!-- editButtons --> </div><!-- editOptions -->"); /** * To make it harder for someone to slip a user a page * which submits an edit form to the wiki without their * knowledge, a random token is associated with the login * session. If it's not passed back with the submission, * we won't save the page, or render user JavaScript and * CSS previews. * * For anon editors, who may not have a session, we just * include the constant suffix to prevent editing from * broken text-mangling proxies. */ $token = htmlspecialchars( $wgUser->editToken() ); $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" ); $this->showEditTools(); $wgOut->addHTML( <<<END {$this->editFormTextAfterTools} <div class='templatesUsed'> {$formattedtemplates} </div> <div class='hiddencats'> {$formattedhiddencats} </div> END ); if ( $this->isConflict && wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) { $wgOut->wrapWikiMsg( '==$1==', "yourdiff" ); $de = new DifferenceEngine( $this->mTitle ); $de->setText( $this->textbox2, $this->textbox1 ); $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) ); $wgOut->wrapWikiMsg( '==$1==', "yourtext" ); $this->showTextbox2(); } $wgOut->addHTML( $this->editFormTextBottom ); $wgOut->addHTML( "</form>\n" ); if ( !$wgUser->getOption( 'previewontop' ) ) { $this->displayPreviewArea( $previewOutput, false ); } wfProfileOut( $fname ); } protected function showFormBeforeText() { global $wgOut; $wgOut->addHTML( " <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" /> <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" ); } protected function showTextbox1( $classes ) { $attribs = array( 'tabindex' => 1 ); if ( $this->wasDeletedSinceLastEdit() ) $attribs['type'] = 'hidden'; if ( !empty($classes) ) $attribs['class'] = implode(' ',$classes); $this->showTextbox( $this->textbox1, 'wpTextbox1', $attribs ); } protected function showTextbox2() { $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6 ) ); } protected function showTextbox( $content, $name, $attribs = array() ) { global $wgOut, $wgUser; $wikitext = $this->safeUnicodeOutput( $content ); if ( $wikitext !== '' ) { // Ensure there's a newline at the end, otherwise adding lines // is awkward. // But don't add a newline if the ext is empty, or Firefox in XHTML // mode will show an extra newline. A bit annoying. $wikitext .= "\n"; } $attribs['accesskey'] = ','; $attribs['id'] = $name; if ( $wgUser->getOption( 'editwidth' ) ) $attribs['style'] = 'width: 100%'; $wgOut->addHTML( Xml::textarea( $name, $wikitext, $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ), $attribs ) ); } protected function displayPreviewArea( $previewOutput, $isOnTop = false ) { global $wgOut; $classes = array(); if ( $isOnTop ) $classes[] = 'ontop'; $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ); if ( $this->formtype != 'preview' ) $attribs['style'] = 'display: none;'; $wgOut->addHTML( Xml::openElement( 'div', $attribs ) ); if ( $this->formtype == 'preview' ) { $this->showPreview( $previewOutput ); } $wgOut->addHTML( '</div>' ); if ( $this->formtype == 'diff') { $this->showDiff(); } } /** * Append preview output to $wgOut. * Includes category rendering if this is a category page. * * @param string $text The HTML to be output for the preview. */ protected function showPreview( $text ) { global $wgOut; if ( $this->mTitle->getNamespace() == NS_CATEGORY) { $this->mArticle->openShowCategory(); } # This hook seems slightly odd here, but makes things more # consistent for extensions. wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) ); $wgOut->addHTML( $text ); if ( $this->mTitle->getNamespace() == NS_CATEGORY ) { $this->mArticle->closeShowCategory(); } } /** * Live Preview lets us fetch rendered preview page content and * add it to the page without refreshing the whole page. * If not supported by the browser it will fall through to the normal form * submission method. * * This function outputs a script tag to support live preview, and * returns an onclick handler which should be added to the attributes * of the preview button */ function doLivePreviewScript() { global $wgOut, $wgTitle; $wgOut->addScriptFile( 'preview.js' ); $liveAction = $wgTitle->getLocalUrl( "action={$this->action}&wpPreview=true&live=true" ); return "return !lpDoPreview(" . "editform.wpTextbox1.value," . '"' . $liveAction . '"' . ")"; } protected function showEditTools() { global $wgOut; $wgOut->addHTML( '<div class="mw-editTools">' ); $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) ); $wgOut->addHTML( '</div>' ); } protected function getLastDelete() { $dbr = wfGetDB( DB_SLAVE ); $data = $dbr->selectRow( array( 'logging', 'user' ), array( 'log_type', 'log_action', 'log_timestamp', 'log_user', 'log_namespace', 'log_title', 'log_comment', 'log_params', 'log_deleted', 'user_name' ), array( 'log_namespace' => $this->mTitle->getNamespace(), 'log_title' => $this->mTitle->getDBkey(), 'log_type' => 'delete', 'log_action' => 'delete', 'user_id=log_user' ), __METHOD__, array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) ); // Quick paranoid permission checks... if( is_object($data) ) { if( $data->log_deleted & LogPage::DELETED_USER ) $data->user_name = wfMsgHtml('rev-deleted-user'); if( $data->log_deleted & LogPage::DELETED_COMMENT ) $data->log_comment = wfMsgHtml('rev-deleted-comment'); } return $data; } /** * Get the rendered text for previewing. * @return string */ function getPreviewText() { global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache; wfProfileIn( __METHOD__ ); if ( $this->mTriedSave && !$this->mTokenOk ) { if ( $this->mTokenOkExceptSuffix ) { $note = wfMsg( 'token_suffix_mismatch' ); } else { $note = wfMsg( 'session_fail_preview' ); } } else { $note = wfMsg( 'previewnote' ); } $parserOptions = ParserOptions::newFromUser( $wgUser ); $parserOptions->setEditSection( false ); $parserOptions->setIsPreview( true ); $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' ); global $wgRawHtml; if ( $wgRawHtml && !$this->mTokenOk ) { // Could be an offsite preview attempt. This is very unsafe if // HTML is enabled, as it could be an attack. return $wgOut->parse( "<div class='previewnote'>" . wfMsg( 'session_fail_preview_html' ) . "</div>" ); } # don't parse user css/js, show message about preview # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here if ( $this->isCssJsSubpage ) { if (preg_match("/\\.css$/", $this->mTitle->getText() ) ) { $previewtext = wfMsg('usercsspreview'); } else if (preg_match("/\\.js$/", $this->mTitle->getText() ) ) { $previewtext = wfMsg('userjspreview'); } $parserOptions->setTidy(true); $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions ); $previewHTML = $parserOutput->mText; } elseif ( $rt = Title::newFromRedirectArray( $this->textbox1 ) ) { $previewHTML = $this->mArticle->viewRedirect( $rt, false ); } else { $toparse = $this->textbox1; # If we're adding a comment, we need to show the # summary as the headline if ( $this->section=="new" && $this->summary!="" ) { $toparse="== {$this->summary} ==\n\n".$toparse; } if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData; // Parse mediawiki messages with correct target language if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) { list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle->getText() ); $obj = wfGetLangObj( $lang ); $parserOptions->setTargetLanguage( $obj ); } $parserOptions->setTidy(true); $parserOptions->enableLimitReport(); $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ), $this->mTitle, $parserOptions ); $previewHTML = $parserOutput->getText(); $this->mParserOutput = $parserOutput; $wgOut->addParserOutputNoText( $parserOutput ); if ( count( $parserOutput->getWarnings() ) ) { $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() ); } } $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" . "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n"; if ( $this->isConflict ) { $previewhead .='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n"; } wfProfileOut( __METHOD__ ); return $previewhead . $previewHTML; } function getTemplates() { if ( $this->preview || $this->section != '' ) { $templates = array(); if ( !isset($this->mParserOutput) ) return $templates; foreach( $this->mParserOutput->getTemplates() as $ns => $template) { foreach( array_keys( $template ) as $dbk ) { $templates[] = Title::makeTitle($ns, $dbk); } } return $templates; } else { return $this->mArticle->getUsedTemplates(); } } /** * Call the stock "user is blocked" page */ function blockedPage() { global $wgOut, $wgUser; $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return' # If the user made changes, preserve them when showing the markup # (This happens when a user is blocked during edit, for instance) $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' ); if ( $first ) { $source = $this->mTitle->exists() ? $this->getContent() : false; } else { $source = $this->textbox1; } # Spit out the source or the user's modified version if ( $source !== false ) { $rows = $wgUser->getIntOption( 'rows' ); $cols = $wgUser->getIntOption( 'cols' ); $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' ); $wgOut->addHTML( '<hr />' ); $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ); # Why we don't use Xml::element here? # Is it because if $source is '', it returns <textarea />? $wgOut->addHTML( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) ); } } /** * Produce the stock "please login to edit pages" page */ function userNotLoggedInPage() { global $wgUser, $wgOut, $wgTitle; $skin = $wgUser->getSkin(); $loginTitle = SpecialPage::getTitleFor( 'Userlogin' ); $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() ); $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $wgOut->setArticleRelated( false ); $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) ); $wgOut->returnToMain( false, $wgTitle ); } /** * Creates a basic error page which informs the user that * they have attempted to edit a nonexistent section. */ function noSuchSectionPage() { global $wgOut, $wgTitle; $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $wgOut->setArticleRelated( false ); $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section ); $wgOut->returnToMain( false, $wgTitle ); } /** * Produce the stock "your edit contains spam" page * * @param $match Text which triggered one or more filters */ function spamPage( $match = false ) { global $wgOut, $wgTitle; $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) ); $wgOut->setRobotPolicy( 'noindex,nofollow' ); $wgOut->setArticleRelated( false ); $wgOut->addHTML( '<div id="spamprotected">' ); $wgOut->addWikiMsg( 'spamprotectiontext' ); if ( $match ) $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) ); $wgOut->addHTML( '</div>' ); $wgOut->returnToMain( false, $wgTitle ); } /** * @private * @todo document */ function mergeChangesInto( &$editText ){ $fname = 'EditPage::mergeChangesInto'; wfProfileIn( $fname ); $db = wfGetDB( DB_MASTER ); // This is the revision the editor started from $baseRevision = $this->getBaseRevision(); if ( is_null( $baseRevision ) ) { wfProfileOut( $fname ); return false; } $baseText = $baseRevision->getText(); // The current state, we want to merge updates into it $currentRevision = Revision::loadFromTitle( $db, $this->mTitle ); if ( is_null( $currentRevision ) ) { wfProfileOut( $fname ); return false; } $currentText = $currentRevision->getText(); $result = ''; if ( wfMerge( $baseText, $editText, $currentText, $result ) ) { $editText = $result; wfProfileOut( $fname ); return true; } else { wfProfileOut( $fname ); return false; } } /** * Check if the browser is on a blacklist of user-agents known to * mangle UTF-8 data on form submission. Returns true if Unicode * should make it through, false if it's known to be a problem. * @return bool * @private */ function checkUnicodeCompliantBrowser() { global $wgBrowserBlackList; if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) { // No User-Agent header sent? Trust it by default... return true; } $currentbrowser = $_SERVER["HTTP_USER_AGENT"]; foreach ( $wgBrowserBlackList as $browser ) { if ( preg_match($browser, $currentbrowser) ) { return false; } } return true; } /** * @deprecated use $wgParser->stripSectionName() */ function pseudoParseSectionAnchor( $text ) { global $wgParser; return $wgParser->stripSectionName( $text ); } /** * Format an anchor fragment as it would appear for a given section name * @param string $text * @return string * @private */ function sectionAnchor( $text ) { global $wgParser; return $wgParser->guessSectionNameFromWikiText( $text ); } /** * Shows a bulletin board style toolbar for common editing functions. * It can be disabled in the user preferences. * The necessary JavaScript code can be found in skins/common/edit.js. * * @return string */ static function getEditToolbar() { global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType; /** * toolarray an array of arrays which each include the filename of * the button image (without path), the opening tag, the closing tag, * and optionally a sample text that is inserted between the two when no * selection is highlighted. * The tip text is shown when the user moves the mouse over the button. * * Already here are accesskeys (key), which are not used yet until someone * can figure out a way to make them work in IE. However, we should make * sure these keys are not defined on the edit page. */ $toolarray = array( array( 'image' => $wgLang->getImageFile('button-bold'), 'id' => 'mw-editbutton-bold', 'open' => '\'\'\'', 'close' => '\'\'\'', 'sample' => wfMsg('bold_sample'), 'tip' => wfMsg('bold_tip'), 'key' => 'B' ), array( 'image' => $wgLang->getImageFile('button-italic'), 'id' => 'mw-editbutton-italic', 'open' => '\'\'', 'close' => '\'\'', 'sample' => wfMsg('italic_sample'), 'tip' => wfMsg('italic_tip'), 'key' => 'I' ), array( 'image' => $wgLang->getImageFile('button-link'), 'id' => 'mw-editbutton-link', 'open' => '[[', 'close' => ']]', 'sample' => wfMsg('link_sample'), 'tip' => wfMsg('link_tip'), 'key' => 'L' ), array( 'image' => $wgLang->getImageFile('button-extlink'), 'id' => 'mw-editbutton-extlink', 'open' => '[', 'close' => ']', 'sample' => wfMsg('extlink_sample'), 'tip' => wfMsg('extlink_tip'), 'key' => 'X' ), array( 'image' => $wgLang->getImageFile('button-headline'), 'id' => 'mw-editbutton-headline', 'open' => "\n== ", 'close' => " ==\n", 'sample' => wfMsg('headline_sample'), 'tip' => wfMsg('headline_tip'), 'key' => 'H' ), array( 'image' => $wgLang->getImageFile('button-image'), 'id' => 'mw-editbutton-image', 'open' => '[['.$wgContLang->getNsText(NS_FILE).':', 'close' => ']]', 'sample' => wfMsg('image_sample'), 'tip' => wfMsg('image_tip'), 'key' => 'D' ), array( 'image' => $wgLang->getImageFile('button-media'), 'id' => 'mw-editbutton-media', 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':', 'close' => ']]', 'sample' => wfMsg('media_sample'), 'tip' => wfMsg('media_tip'), 'key' => 'M' ), array( 'image' => $wgLang->getImageFile('button-math'), 'id' => 'mw-editbutton-math', 'open' => "<math>", 'close' => "</math>", 'sample' => wfMsg('math_sample'), 'tip' => wfMsg('math_tip'), 'key' => 'C' ), array( 'image' => $wgLang->getImageFile('button-nowiki'), 'id' => 'mw-editbutton-nowiki', 'open' => "<nowiki>", 'close' => "</nowiki>", 'sample' => wfMsg('nowiki_sample'), 'tip' => wfMsg('nowiki_tip'), 'key' => 'N' ), array( 'image' => $wgLang->getImageFile('button-sig'), 'id' => 'mw-editbutton-signature', 'open' => '--~~~~', 'close' => '', 'sample' => '', 'tip' => wfMsg('sig_tip'), 'key' => 'Y' ), array( 'image' => $wgLang->getImageFile('button-hr'), 'id' => 'mw-editbutton-hr', 'open' => "\n----\n", 'close' => '', 'sample' => '', 'tip' => wfMsg('hr_tip'), 'key' => 'R' ) ); $toolbar = "<div id='toolbar'>\n"; $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n"; foreach($toolarray as $tool) { $params = array( $image = $wgStylePath.'/common/images/'.$tool['image'], // Note that we use the tip both for the ALT tag and the TITLE tag of the image. // Older browsers show a "speedtip" type message only for ALT. // Ideally these should be different, realistically they // probably don't need to be. $tip = $tool['tip'], $open = $tool['open'], $close = $tool['close'], $sample = $tool['sample'], $cssId = $tool['id'], ); $paramList = implode( ',', array_map( array( 'Xml', 'encodeJsVar' ), $params ) ); $toolbar.="addButton($paramList);\n"; } $toolbar.="/*]]>*/\n</script>"; $toolbar.="\n</div>"; return $toolbar; } /** * Returns an array of html code of the following checkboxes: * minor and watch * * @param $tabindex Current tabindex * @param $skin Skin object * @param $checked Array of checkbox => bool, where bool indicates the checked * status of the checkbox * * @return array */ public function getCheckboxes( &$tabindex, $skin, $checked ) { global $wgUser; $checkboxes = array(); $checkboxes['minor'] = ''; $minorLabel = wfMsgExt('minoredit', array('parseinline')); if ( $wgUser->isAllowed('minoredit') ) { $attribs = array( 'tabindex' => ++$tabindex, 'accesskey' => wfMsg( 'accesskey-minoredit' ), 'id' => 'wpMinoredit', ); $checkboxes['minor'] = Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) . " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>"; } $watchLabel = wfMsgExt('watchthis', array('parseinline')); $checkboxes['watch'] = ''; if ( $wgUser->isLoggedIn() ) { $attribs = array( 'tabindex' => ++$tabindex, 'accesskey' => wfMsg( 'accesskey-watch' ), 'id' => 'wpWatchthis', ); $checkboxes['watch'] = Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) . " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>"; } wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) ); return $checkboxes; } /** * Returns an array of html code of the following buttons: * save, diff, preview and live * * @param $tabindex Current tabindex * * @return array */ public function getEditButtons(&$tabindex) { global $wgLivePreview, $wgUser; $buttons = array(); $temp = array( 'id' => 'wpSave', 'name' => 'wpSave', 'type' => 'submit', 'tabindex' => ++$tabindex, 'value' => wfMsg('savearticle'), 'accesskey' => wfMsg('accesskey-save'), 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']', ); $buttons['save'] = Xml::element('input', $temp, ''); ++$tabindex; // use the same for preview and live preview if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) { $temp = array( 'id' => 'wpPreview', 'name' => 'wpPreview', 'type' => 'submit', 'tabindex' => $tabindex, 'value' => wfMsg('showpreview'), 'accesskey' => '', 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']', 'style' => 'display: none;', ); $buttons['preview'] = Xml::element('input', $temp, ''); $temp = array( 'id' => 'wpLivePreview', 'name' => 'wpLivePreview', 'type' => 'submit', 'tabindex' => $tabindex, 'value' => wfMsg('showlivepreview'), 'accesskey' => wfMsg('accesskey-preview'), 'title' => '', 'onclick' => $this->doLivePreviewScript(), ); $buttons['live'] = Xml::element('input', $temp, ''); } else { $temp = array( 'id' => 'wpPreview', 'name' => 'wpPreview', 'type' => 'submit', 'tabindex' => $tabindex, 'value' => wfMsg('showpreview'), 'accesskey' => wfMsg('accesskey-preview'), 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']', ); $buttons['preview'] = Xml::element('input', $temp, ''); $buttons['live'] = ''; } $temp = array( 'id' => 'wpDiff', 'name' => 'wpDiff', 'type' => 'submit', 'tabindex' => ++$tabindex, 'value' => wfMsg('showdiff'), 'accesskey' => wfMsg('accesskey-diff'), 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']', ); $buttons['diff'] = Xml::element('input', $temp, ''); wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) ); return $buttons; } /** * Output preview text only. This can be sucked into the edit page * via JavaScript, and saves the server time rendering the skin as * well as theoretically being more robust on the client (doesn't * disturb the edit box's undo history, won't eat your text on * failure, etc). * * @todo This doesn't include category or interlanguage links. * Would need to enhance it a bit, <s>maybe wrap them in XML * or something...</s> that might also require more skin * initialization, so check whether that's a problem. */ function livePreview() { global $wgOut; $wgOut->disable(); header( 'Content-type: text/xml; charset=utf-8' ); header( 'Cache-control: no-cache' ); $previewText = $this->getPreviewText(); #$categories = $skin->getCategoryLinks(); $s = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" . Xml::tags( 'livepreview', null, Xml::element( 'preview', null, $previewText ) #. Xml::element( 'category', null, $categories ) ); echo $s; } /** * Get a diff between the current contents of the edit box and the * version of the page we're editing from. * * If this is a section edit, we'll replace the section as for final * save and then make a comparison. */ function showDiff() { $oldtext = $this->mArticle->fetchContent(); $newtext = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime ); $newtext = $this->mArticle->preSaveTransform( $newtext ); $oldtitle = wfMsgExt( 'currentrev', array('parseinline') ); $newtitle = wfMsgExt( 'yourtext', array('parseinline') ); if ( $oldtext !== false || $newtext != '' ) { $de = new DifferenceEngine( $this->mTitle ); $de->setText( $oldtext, $newtext ); $difftext = $de->getDiff( $oldtitle, $newtitle ); $de->showDiffStyle(); } else { $difftext = ''; } global $wgOut; $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' ); } /** * Filter an input field through a Unicode de-armoring process if it * came from an old browser with known broken Unicode editing issues. * * @param WebRequest $request * @param string $field * @return string * @private */ function safeUnicodeInput( $request, $field ) { $text = rtrim( $request->getText( $field ) ); return $request->getBool( 'safemode' ) ? $this->unmakesafe( $text ) : $text; } /** * Filter an output field through a Unicode armoring process if it is * going to an old browser with known broken Unicode editing issues. * * @param string $text * @return string * @private */ function safeUnicodeOutput( $text ) { global $wgContLang; $codedText = $wgContLang->recodeForEdit( $text ); return $this->checkUnicodeCompliantBrowser() ? $codedText : $this->makesafe( $codedText ); } /** * A number of web browsers are known to corrupt non-ASCII characters * in a UTF-8 text editing environment. To protect against this, * detected browsers will be served an armored version of the text, * with non-ASCII chars converted to numeric HTML character references. * * Preexisting such character references will have a 0 added to them * to ensure that round-trips do not alter the original data. * * @param string $invalue * @return string * @private */ function makesafe( $invalue ) { // Armor existing references for reversability. $invalue = strtr( $invalue, array( "&#x" => "�" ) ); $bytesleft = 0; $result = ""; $working = 0; for( $i = 0; $i < strlen( $invalue ); $i++ ) { $bytevalue = ord( $invalue{$i} ); if ( $bytevalue <= 0x7F ) { //0xxx xxxx $result .= chr( $bytevalue ); $bytesleft = 0; } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx $working = $working << 6; $working += ($bytevalue & 0x3F); $bytesleft--; if ( $bytesleft <= 0 ) { $result .= "&#x" . strtoupper( dechex( $working ) ) . ";"; } } elseif ( $bytevalue <= 0xDF ) { //110x xxxx $working = $bytevalue & 0x1F; $bytesleft = 1; } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx $working = $bytevalue & 0x0F; $bytesleft = 2; } else { //1111 0xxx $working = $bytevalue & 0x07; $bytesleft = 3; } } return $result; } /** * Reverse the previously applied transliteration of non-ASCII characters * back to UTF-8. Used to protect data from corruption by broken web browsers * as listed in $wgBrowserBlackList. * * @param string $invalue * @return string * @private */ function unmakesafe( $invalue ) { $result = ""; for( $i = 0; $i < strlen( $invalue ); $i++ ) { if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) { $i += 3; $hexstring = ""; do { $hexstring .= $invalue{$i}; $i++; } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) ); // Do some sanity checks. These aren't needed for reversability, // but should help keep the breakage down if the editor // breaks one of the entities whilst editing. if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) { $codepoint = hexdec($hexstring); $result .= codepointToUtf8( $codepoint ); } else { $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 ); } } else { $result .= substr( $invalue, $i, 1 ); } } // reverse the transform that we made for reversability reasons. return strtr( $result, array( "�" => "&#x" ) ); } function noCreatePermission() { global $wgOut; $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) ); $wgOut->addWikiMsg( 'nocreatetext' ); } /** * If there are rows in the deletion log for this page, show them, * along with a nice little note for the user * * @param OutputPage $out */ protected function showDeletionLog( $out ) { global $wgUser; $loglist = new LogEventsList( $wgUser->getSkin(), $out ); $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() ); $count = $pager->getNumRows(); if ( $count > 0 ) { $pager->mLimit = 10; $out->addHTML( '<div class="mw-warning-with-logexcerpt">' ); $out->addWikiMsg( 'recreate-deleted-warn' ); $out->addHTML( $loglist->beginLogEventsList() . $pager->getBody() . $loglist->endLogEventsList() ); if($count > 10){ $out->addHTML( $wgUser->getSkin()->link( SpecialPage::getTitleFor( 'Log' ), wfMsgHtml( 'deletelog-fulllog' ), array(), array( 'type' => 'delete', 'page' => $this->mTitle->getPrefixedText() ) ) ); } $out->addHTML( '</div>' ); return true; } return false; } /** * Attempt submission * @return bool false if output is done, true if the rest of the form should be displayed */ function attemptSave() { global $wgUser, $wgOut, $wgTitle, $wgRequest; $resultDetails = false; # Allow bots to exempt some edits from bot flagging $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true); $value = $this->internalAttemptSave( $resultDetails, $bot ); if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) { $this->didSave = true; } switch ($value) { case self::AS_HOOK_ERROR_EXPECTED: case self::AS_CONTENT_TOO_BIG: case self::AS_ARTICLE_WAS_DELETED: case self::AS_CONFLICT_DETECTED: case self::AS_SUMMARY_NEEDED: case self::AS_TEXTBOX_EMPTY: case self::AS_MAX_ARTICLE_SIZE_EXCEEDED: case self::AS_END: return true; case self::AS_HOOK_ERROR: case self::AS_FILTERING: case self::AS_SUCCESS_NEW_ARTICLE: case self::AS_SUCCESS_UPDATE: return false; case self::AS_SPAM_ERROR: $this->spamPage ( $resultDetails['spam'] ); return false; case self::AS_BLOCKED_PAGE_FOR_USER: $this->blockedPage(); return false; case self::AS_IMAGE_REDIRECT_ANON: $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' ); return false; case self::AS_READ_ONLY_PAGE_ANON: $this->userNotLoggedInPage(); return false; case self::AS_READ_ONLY_PAGE_LOGGED: case self::AS_READ_ONLY_PAGE: $wgOut->readOnlyPage(); return false; case self::AS_RATE_LIMITED: $wgOut->rateLimited(); return false; case self::AS_NO_CREATE_PERMISSION; $this->noCreatePermission(); return; case self::AS_BLANK_ARTICLE: $wgOut->redirect( $wgTitle->getFullURL() ); return false; case self::AS_IMAGE_REDIRECT_LOGGED: $wgOut->permissionRequired( 'upload' ); return false; } } function getBaseRevision() { if ( $this->mBaseRevision == false ) { $db = wfGetDB( DB_MASTER ); $baseRevision = Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime ); return $this->mBaseRevision = $baseRevision; } else { return $this->mBaseRevision; } $this->getAutosummary($baseRevision, $db, $this->DeleteReason); //it was slow! } }