示例#1
0
 /**
  * @return bool|int|null
  */
 protected function saveContent()
 {
     global $wgLogRestrictions;
     $dbw = wfGetDB(DB_MASTER);
     $log_id = $dbw->nextSequenceValue('logging_log_id_seq');
     $this->timestamp = $now = wfTimestampNow();
     $data = array('log_id' => $log_id, 'log_type' => $this->type, 'log_action' => $this->action, 'log_timestamp' => $dbw->timestamp($now), 'log_user' => $this->doer->getId(), 'log_user_text' => $this->doer->getName(), 'log_namespace' => $this->target->getNamespace(), 'log_title' => $this->target->getDBkey(), 'log_page' => $this->target->getArticleId(), 'log_comment' => $this->comment, 'log_params' => $this->params);
     $dbw->insert('logging', $data, __METHOD__);
     $newId = !is_null($log_id) ? $log_id : $dbw->insertId();
     # And update recentchanges
     if ($this->updateRecentChanges) {
         $titleObj = SpecialPage::getTitleFor('Log', $this->type);
         RecentChange::notifyLog($now, $titleObj, $this->doer, $this->getRcComment(), '', $this->type, $this->action, $this->target, $this->comment, $this->params, $newId);
     } elseif ($this->sendToUDP) {
         # Don't send private logs to UDP
         if (isset($wgLogRestrictions[$this->type]) && $wgLogRestrictions[$this->type] != '*') {
             return true;
         }
         # Notify external application via UDP.
         # We send this to IRC but do not want to add it the RC table.
         $titleObj = SpecialPage::getTitleFor('Log', $this->type);
         $rc = RecentChange::newLogEntry($now, $titleObj, $this->doer, $this->getRcComment(), '', $this->type, $this->action, $this->target, $this->comment, $this->params, $newId);
         $rc->notifyRC2UDP();
     }
     return $newId;
 }
 public function getContext(Title $title, $skinName)
 {
     $wrapper = new GlobalStateWrapper(['wgTitle' => $title]);
     $wg = F::app()->wg;
     return $wrapper->wrap(function () use($title, $wg, $skinName) {
         $wikiFactoryHub = WikiFactoryHub::getInstance();
         $hubService = new HubService();
         $adPageTypeService = new AdEngine2PageTypeService();
         $wikiaPageType = new WikiaPageType();
         $sevenOneMediaCombinedUrl = null;
         if (!empty($wg->AdDriverUseSevenOneMedia)) {
             // TODO: implicitly gets the skin from the context!
             $sevenOneMediaCombinedUrl = ResourceLoader::makeCustomURL($wg->Out, ['wikia.ext.adengine.sevenonemedia'], 'scripts');
         }
         $monetizationServiceAds = null;
         if (!empty($wg->AdDriverUseMonetizationService) && !empty($wg->EnableMonetizationModuleExt)) {
             $monetizationServiceAds = F::app()->sendRequest('MonetizationModule', 'index')->getData()['data'];
         }
         $langCode = $title->getPageLanguage()->getCode();
         return ['opts' => $this->filterOutEmptyItems(['adsInContent' => $wg->EnableAdsInContent, 'delayBtf' => $wg->AdDriverDelayBelowTheFold, 'enableAdsInMaps' => $wg->AdDriverEnableAdsInMaps, 'pageType' => $adPageTypeService->getPageType(), 'paidAssetDropConfig' => $wg->PaidAssetDropConfig, 'showAds' => $adPageTypeService->areAdsShowableOnPage(), 'trackSlotState' => $wg->AdDriverTrackState, 'usePostScribe' => $wg->Request->getBool('usepostscribe', false)]), 'targeting' => $this->filterOutEmptyItems(['enablePageCategories' => array_search($langCode, $wg->AdPageLevelCategoryLangs) !== false, 'pageArticleId' => $title->getArticleId(), 'pageIsArticle' => !!$title->getArticleId(), 'pageIsHub' => $wikiaPageType->isWikiaHub(), 'pageName' => $title->getPrefixedDBKey(), 'pageType' => $wikiaPageType->getPageType(), 'sevenOneMediaSub2Site' => $wg->AdDriverSevenOneMediaOverrideSub2Site, 'skin' => $skinName, 'wikiCategory' => $wikiFactoryHub->getCategoryShort($wg->CityId), 'wikiCustomKeyValues' => $wg->DartCustomKeyValues, 'wikiDbName' => $wg->DBname, 'wikiDirectedAtChildren' => $wg->WikiDirectedAtChildrenByFounder || $wg->WikiDirectedAtChildrenByStaff, 'wikiIsCorporate' => $wikiaPageType->isCorporatePage(), 'wikiIsTop1000' => $wg->AdDriverWikiIsTop1000, 'wikiLanguage' => $langCode, 'wikiVertical' => $hubService->getCategoryInfoForCity($wg->CityId)->cat_name]), 'providers' => $this->filterOutEmptyItems(['monetizationService' => $wg->AdDriverUseMonetizationService, 'monetizationServiceAds' => $monetizationServiceAds, 'sevenOneMedia' => $wg->AdDriverUseSevenOneMedia, 'sevenOneMediaCombinedUrl' => $sevenOneMediaCombinedUrl, 'taboola' => $wg->AdDriverUseTaboola]), 'slots' => $this->filterOutEmptyItems(['exitstitial' => $wg->EnableOutboundScreenExt, 'exitstitialRedirectDelay' => $wg->OutboundScreenRedirectDelay, 'invisibleHighImpact' => $wg->AdDriverEnableInvisibleHighImpactSlot]), 'forcedProvider' => $wg->AdDriverForcedProvider];
     });
 }
 public function userCanVote()
 {
     $pageId = $this->mTitle->getArticleId();
     $oFauxRequest = new FauxRequest(['action' => 'query', 'list' => 'wkvoteart', 'wkpage' => $pageId, 'wkuservote' => 1]);
     $oApi = new ApiMain($oFauxRequest);
     $oApi->execute();
     $aResult = $oApi->GetResultData();
     if (isset($aResult['query']['wkvoteart'][$pageId]['uservote'])) {
         $result = false;
     } else {
         $result = true;
     }
     return $result;
 }
	/**
	 * check if $page belongs to $category
	 * @param $page Title current page
	 * @param $category String category to check (not a title object!)
	 * @param $parser Parser
	 * @return boolean If $page is a member of $category
	 */
	private static function inCat( Title $page, $category, Parser $parser ) {
		if ( $category === '' ) return false;
		$catTitle = Title::makeTitleSafe(
			NS_CATEGORY,
			$category
		);
		if ( !$catTitle ) return false;
		$catDBkey = $catTitle->getDBkey();

		if ( !isset( $parser->pageInCat_cache ) ) {
			$parser->pageInCat_cache = array();
		} else {
			if ( isset( $parser->pageInCat_cache[$catDBkey] ) ) {
				# been there done that, return cached value
				return $parser->pageInCat_cache[$catDBkey];
			} elseif( isset( $parser->pageInCat_onlyCache ) && $parser->pageInCat_onlyCache ) {
				# All categories have been preloaded into cache, so
				# we must have hit a cat not in page.
				# Mark it so can be checked for correctness later.
				$parser->PageInCat_cache[$catDBkey] = false;
				return false;
			}
		}

		$pageId = $page->getArticleId();
		if ( !$pageId ) {
			// page hasn't yet been saved (preview)
			// add to the cache list so the other hook
			// will warn about incorrect value.
			// Important to do this after checking cache
			// in case categories were pre-loaded during preview.
			$parser->pageInCat_cache[$catDBkey] = false;
			return false;
		}

		if ( !$parser->incrementExpensiveFunctionCount() ) {
			# expensive function limit reached.
			return false;
		}

		if ( self::inCatCheckDb( $pageId, $catDBkey ) ) {
			$parser->pageInCat_cache[$catDBkey] = true;
			return true;
		} /* else if false */

		$parser->pageInCat_cache[$catDBkey] = false;
		return false;
	}
示例#5
0
 static function storeBackLinkText($skin, Title $target, array $options, &$text, array &$attribs, &$ret)
 {
     wfProfileIn(__METHOD__);
     global $wgArticle;
     $targetArticleId = $target->getArticleId();
     if (!is_int($targetArticleId) || $wgArticle === null || $targetArticleId === 0) {
         wfProfileOut(__METHOD__);
         return true;
     }
     $sourceArticleId = $wgArticle->getId();
     self::$sourceArticleIds = array_unique(self::$sourceArticleIds + array($sourceArticleId));
     $backlinkRowSignature = sprintf("(%s,%s,'%s',", $sourceArticleId, $targetArticleId, mysql_real_escape_string(substr($text, 0, 255)));
     self::$backlinkRows[$backlinkRowSignature] = isset(self::$backlinkRows[$backlinkRowSignature]) ? self::$backlinkRows[$backlinkRowSignature] + 1 : 1;
     wfProfileOut(__METHOD__);
     return true;
 }
 /**
  * Gets the HTML fragment for a watched page.
  *
  * @param Title $title The title of the watched page
  * @param int $ts When the page was last touched
  * @param string $thumb An HTML fragment for the page's thumbnaiL
  * @return string
  */
 public static function getLineHtml(Title $title, $ts, $thumb)
 {
     $titleText = $title->getPrefixedText();
     if ($ts) {
         $ts = new MWTimestamp($ts);
         $lastModified = wfMessage('mobile-frontend-watchlist-modified', $ts->getHumanTimestamp())->text();
         $className = 'title';
     } else {
         $className = 'title new';
         $lastModified = '';
     }
     $html = Html::openElement('li', array('class' => 'page-summary', 'title' => $titleText, 'data-id' => $title->getArticleId())) . Html::openElement('a', array('href' => $title->getLocalUrl(), 'class' => $className));
     $html .= $thumb;
     $html .= Html::element('h3', array(), $titleText) . Html::element('div', array('class' => 'info'), $lastModified) . Html::closeElement('a') . Html::closeElement('li');
     return $html;
 }
 /**
  * @param Title $title
  * @param WikiPage $article
  * @return bool
  */
 public function onArticleFromTitle(Title &$title, &$article)
 {
     if ($title->exists() && $title->getNamespace() != NS_FILE && $title->getNamespace() != NS_CATEGORY) {
         $key = $this->generateCacheKey($title->getArticleId());
         $this->switches = $this->app->wg->memc->get($key);
         if (empty($this->switches)) {
             $article = F::build('Article', array($title));
             $this->switches = array();
             foreach ($this->magicWords as $wordID) {
                 $magicWord = MagicWord::get($wordID);
                 $this->switches[$wordID] = 0 < $magicWord->match($article->getRawText());
             }
             $this->app->wg->memc->set($key, $this->switches, self::CACHE_DURATION);
         }
         $this->process();
     }
     return true;
 }
 /**
  * @param Title $title
  * @param WikiPage $article
  * @return bool
  */
 public static function onArticleFromTitle(Title &$title, &$article)
 {
     global $wgLandingPagesAsContentMagicWords;
     $app = F::app();
     if ($title->exists() && $title->getNamespace() != NS_FILE && $title->getNamespace() != NS_CATEGORY) {
         $key = self::generateCacheKey($title->getArticleId());
         self::$switches = $app->wg->memc->get($key);
         if (empty(self::$switches)) {
             $article = new Article($title);
             self::$switches = array();
             $magicWords = array_keys($wgLandingPagesAsContentMagicWords);
             foreach ($magicWords as $wordID) {
                 $magicWord = MagicWord::get($wordID);
                 self::$switches[$wordID] = 0 < $magicWord->match($article->getRawText());
             }
             $app->wg->memc->set($key, self::$switches, self::CACHE_DURATION);
         }
         self::process();
     }
     return true;
 }
示例#9
0
 /**
  * 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
  * @return array
  * @private
  */
 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);
 }
 /**
  * Merge page histories
  *
  * @param integer $id The page_id
  * @param Title $newTitle The new title
  */
 private function mergePage($id, Title $newTitle)
 {
     $destId = $newTitle->getArticleId();
     $this->db->begin(__METHOD__);
     $this->db->update('revision', array('rev_page' => $destId), array('rev_page' => $id), __METHOD__);
     $this->db->delete('page', array('page_id' => $id), __METHOD__);
     // @fixme Need WikiPage::doDeleteUpdates() or similar to avoid orphan
     // rows in the links tables.
     $this->db->commit(__METHOD__);
     return true;
 }
 /**
  * Inserts a trace of the user action into the database
  * @global string $wgDBtype
  * @param Title $oTitle
  * @param User $oUser
  * @param Request $oRequest
  * @return boolean
  */
 public function insertTrace($oTitle, $oUser, $oRequest)
 {
     if (wfReadOnly()) {
         return true;
     }
     if ($oUser->getId() == 0) {
         return true;
     }
     // Anonymous user
     $sPageTitle = $oTitle->getText();
     if ($sPageTitle == '-') {
         return true;
     }
     // otherwise strange '-' with page_id 0 are logged
     $iPageId = $oTitle->getArticleId();
     $iPageNamespaceId = $oTitle->getNamespace();
     $iCurrentTimestamp = time();
     $vLastLoggedPageHash = $oRequest->getSessionData($this->mExtensionKey . '::lastLoggedPageHash');
     $vLastLoggedTime = $oRequest->getSessionData($this->mExtensionKey . '::lastLoggedTime');
     $sCurrentPageHash = md5($iPageId . $iPageNamespaceId . $sPageTitle);
     //this combination should be pretty unique, even with specialpages.
     $iMaxIdleTime = BsConfig::get('MW::WhoIsOnline::MaxIdleTime');
     $iInterval = BsConfig::get('MW::WhoIsOnline::Interval');
     if ($vLastLoggedPageHash == $sCurrentPageHash && $vLastLoggedTime + $iMaxIdleTime + $iInterval + $iMaxIdleTime * 0.1 > $iCurrentTimestamp) {
         return true;
     }
     //log action
     wfProfileIn('BS::' . __METHOD__);
     $oRequest->setSessionData($this->mExtensionKey . '::lastLoggedPageHash', $sCurrentPageHash);
     $oRequest->setSessionData($this->mExtensionKey . '::lastLoggedTime', $iCurrentTimestamp);
     $iRemoveEntriesAfter = 2592000;
     $dbw = wfGetDB(DB_MASTER);
     $dbw->delete('bs_whoisonline', array('wo_timestamp < ' . ($iCurrentTimestamp - $iRemoveEntriesAfter)));
     $aNewRow = array();
     $aNewRow['wo_page_id'] = $oTitle->getArticleId();
     $aNewRow['wo_page_namespace'] = $oTitle->getNamespace();
     $aNewRow['wo_page_title'] = $sPageTitle;
     $aNewRow['wo_user_id'] = $oUser->getId();
     $aNewRow['wo_user_name'] = $oUser->getName();
     $aNewRow['wo_user_real_name'] = $oUser->getRealName();
     $aNewRow['wo_timestamp'] = $iCurrentTimestamp;
     $aNewRow['wo_action'] = $oRequest->getVal('action', 'view');
     global $wgDBtype;
     if ($wgDBtype == 'oracle') {
         $aNewRow['wo_id'] = 0;
     }
     $dbw->insert('bs_whoisonline', $aNewRow);
     wfProfileOut('BS::' . __METHOD__);
     return true;
 }
 /**
  * Return instance of this class for given title from RelatedVideos namespace
  */
 public static function newFromTitle(Title $title)
 {
     $id = $title->getArticleId();
     return new self($id, $title);
 }
 /**
  * Hook
  *
  * @param Title $oTitle -- instance of Title class
  * @param User    $User    -- current user
  * @param string  $reason  -- undeleting reason
  *
  * @static
  * @access public
  *
  * @return true -- because it's hook
  */
 public static function undeleteComplete($oTitle, $oUser, $reason)
 {
     wfProfileIn(__METHOD__);
     if ($oTitle instanceof Title) {
         if (in_array($oTitle->getNamespace(), array(NS_BLOG_ARTICLE, NS_BLOG_ARTICLE_TALK))) {
             $aProps = $oTitle->aProps;
             $pageId = $oTitle->getArticleId();
             if (!empty($aProps)) {
                 BlogArticle::setProps($pageId, $aProps);
             }
         }
     }
     wfProfileOut(__METHOD__);
     return true;
 }
	/**
	 * Gets the summary data for all ratings on the specified page.
	 * 
	 * @since 0.1
	 * 
	 * @param Title $page
	 * 
	 * @return array
	 */
	protected static function getAndCalcPageRatings( Title $page ) {
		$tags = array();
		
		foreach ( self::getTagNames() as $tagName => $tagId ) {
			$tags[$tagId] = array( 'count' => 0, 'total' => 0, 'name' => $tagName );
		}		
		
		$dbr = wfGetDb( DB_SLAVE );
		
		$votes = $dbr->select(
			'votes',
			array(
				'vote_prop_id',
				'vote_value'
			),
			array(
				'vote_page_id' => $page->getArticleId()
			)
		);	
		
		foreach( $votes as $vote ) {
			$tags[$vote->vote_prop_id]['count']++;
			$tags[$vote->vote_prop_id]['total'] += $vote->vote_value;
		}
		
		foreach ( $tags as &$tag ) {
			$tag['avarage'] = $tag['count'] > 0 ? $tag['total'] / $tag['count'] : 0;
		}
		
		return $tags;
	}
示例#15
0
 private function formatRevisionRow($row, $earliestLiveTime, $remaining)
 {
     $rev = Revision::newFromArchiveRow($row, array('page' => $this->mTargetObj->getArticleId()));
     $stxt = '';
     $ts = wfTimestamp(TS_MW, $row->ar_timestamp);
     // Build checkboxen...
     if ($this->mAllowed) {
         if ($this->mInvert) {
             if (in_array($ts, $this->mTargetTimestamp)) {
                 $checkBox = Xml::check("ts{$ts}");
             } else {
                 $checkBox = Xml::check("ts{$ts}", true);
             }
         } else {
             $checkBox = Xml::check("ts{$ts}");
         }
     } else {
         $checkBox = '';
     }
     $user = $this->getUser();
     // Build page & diff links...
     if ($this->mCanView) {
         $titleObj = $this->getTitle();
         # Last link
         if (!$rev->userCan(Revision::DELETED_TEXT, $this->getUser())) {
             $pageLink = htmlspecialchars($this->getLanguage()->userTimeAndDate($ts, $user));
             $last = $this->msg('diff')->escaped();
         } elseif ($remaining > 0 || $earliestLiveTime && $ts > $earliestLiveTime) {
             $pageLink = $this->getPageLink($rev, $titleObj, $ts);
             $last = Linker::linkKnown($titleObj, $this->msg('diff')->escaped(), array(), array('target' => $this->mTargetObj->getPrefixedText(), 'timestamp' => $ts, 'diff' => 'prev'));
         } else {
             $pageLink = $this->getPageLink($rev, $titleObj, $ts);
             $last = $this->msg('diff')->escaped();
         }
     } else {
         $pageLink = htmlspecialchars($this->getLanguage()->userTimeAndDate($ts, $user));
         $last = $this->msg('diff')->escaped();
     }
     // User links
     $userLink = Linker::revUserTools($rev);
     // Revision text size
     $size = $row->ar_len;
     if (!is_null($size)) {
         $stxt = Linker::formatRevisionSize($size);
     }
     // Edit summary
     $comment = Linker::revComment($rev);
     // Revision delete links
     $revdlink = Linker::getRevDeleteLink($user, $rev, $this->mTargetObj);
     return "<li>{$checkBox} {$revdlink} ({$last}) {$pageLink} . . {$userLink} {$stxt} {$comment}</li>";
 }
示例#16
0
 /**
  * Merge page histories
  *
  * @param integer $id The page_id
  * @param Title $newTitle The new title
  * @return bool
  */
 private function mergePage($row, Title $newTitle)
 {
     $id = $row->page_id;
     // Construct the WikiPage object we will need later, while the
     // page_id still exists. Note that this cannot use makeTitleSafe(),
     // we are deliberately constructing an invalid title.
     $sourceTitle = Title::makeTitle($row->page_namespace, $row->page_title);
     $sourceTitle->resetArticleID($id);
     $wikiPage = new WikiPage($sourceTitle);
     $wikiPage->loadPageData('fromdbmaster');
     $destId = $newTitle->getArticleId();
     $this->beginTransaction($this->db, __METHOD__);
     $this->db->update('revision', array('rev_page' => $destId), array('rev_page' => $id), __METHOD__);
     $this->db->delete('page', array('page_id' => $id), __METHOD__);
     /* Call LinksDeletionUpdate to delete outgoing links from the old title,
      * and update category counts.
      *
      * Calling external code with a fake broken Title is a fairly dubious
      * idea. It's necessary because it's quite a lot of code to duplicate,
      * but that also makes it fragile since it would be easy for someone to
      * accidentally introduce an assumption of title validity to the code we
      * are calling.
      */
     $update = new LinksDeletionUpdate($wikiPage);
     $update->doUpdate();
     $this->commitTransaction($this->db, __METHOD__);
     return true;
 }
示例#17
0
 /**
  * Check if no edits were made by other users since
  * the time a user started editing the page. Limit to
  * 50 revisions for the sake of performance.
  *
  * @param $id int
  * @param $edittime string
  *
  * @return bool
  */
 protected function userWasLastToEdit($id, $edittime)
 {
     if (!$id) {
         return false;
     }
     $dbw = wfGetDB(DB_MASTER);
     $res = $dbw->select('revision', 'rev_user', array('rev_page' => $this->mTitle->getArticleId(), 'rev_timestamp > ' . $dbw->addQuotes($dbw->timestamp($edittime))), __METHOD__, array('ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50));
     foreach ($res as $row) {
         if ($row->rev_user != $id) {
             return false;
         }
     }
     return true;
 }
示例#18
0
 protected static function addSectionTag(Title $title, $revision, $pageRevision)
 {
     if ($pageRevision === null) {
         throw new MWException('Page revision is null');
     }
     $dbw = wfGetDB(DB_MASTER);
     $conds = array('rt_page' => $title->getArticleId(), 'rt_type' => RevTag::getType('tp:transver'), 'rt_revision' => $revision);
     $dbw->delete('revtag', $conds, __METHOD__);
     $conds['rt_value'] = $pageRevision;
     $dbw->insert('revtag', $conds, __METHOD__);
 }
示例#19
0
 /**
  * Get count of revisions per page...not very efficient
  * @param Database $db
  * @param Title $title
  */
 static function countByTitle($db, $title)
 {
     $id = $title->getArticleId();
     if ($id) {
         return Revision::countByPageId($db, $id);
     }
     return 0;
 }
   	/**
	* Get a table of the vote totals for a page
	* @param Title $page
	* @param int $period, number of days back
	* @param array $add, optional vote to add on (used to visually avoid lag)
	* @param string $cache, optional param to not use cache
	* @return string HTML table
	*/	
	public static function getVoteAggregates(
		$page, $period, $add = array(), $cache = 'useCache'
	) {
		global $wgLang, $wgMemc;
		$votes = null;
		$now = time();
		$key = wfMemcKey( 'feedback', 'ratingtally', $page->getArticleId(), $period );
		// Check cache
		if( $cache == 'useCache' ) {
			$set = $wgMemc->get($key);
			// Cutoff is at the 24 hour mark due to the way the aggregate 
			// schema groups ratings by date for graphs.
			$cache_cutoff = $now - ($now % 86400);
			if( is_array($set) && count($set) == 2 ) {
				list($val,$time) = $set;
				$touched = wfTimestamp( TS_UNIX, RatingHistory::getTouched($page) );
				if( $time > $cache_cutoff && $time > $touched ) {
					$votes = $val;
				}
			}
		}
		// Do query, cache miss
		if( !isset($votes) ) {
			// Set cutoff time for period
			$dbr = wfGetDB( DB_SLAVE );
			$cutoff_unixtime = $now - ($period * 24 * 3600);
			// Use integral number of days to be consistent with graphs
			$cutoff_unixtime = $cutoff_unixtime - ($cutoff_unixtime % 86400);
			$cutoff = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
			// Get the first revision possibly voted on in the range
			$firstRevTS = $dbr->selectField( 'revision',
				'rev_timestamp',
				array( 'rev_page' => $page->getArticleId(), "rev_timestamp <= $cutoff" ),
				__METHOD__,
				array( 'ORDER BY' => 'rev_timestamp DESC' )
			);
			// Find average, median...
			$res = $dbr->select( array( 'revision', 'reader_feedback' ),
				array( 'rfb_ratings' ),
				array( 'rev_page' => $page->getArticleId(),
					"rev_id = rfb_rev_id",
					"rfb_timestamp >= $cutoff",
					// Trigger INDEX usage
					"rev_timestamp >= ".$dbr->addQuotes($firstRevTS) ),
				__METHOD__,
				array( 'USE INDEX' => array('revision' => 'page_timestamp') )
			);
			$votes = array();
			foreach( ReaderFeedback::getFeedbackTags() as $tag => $w ) {
				$votes[$tag] = array( 0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0 );
			}
			// Read votes and tally the numbers
			foreach ( $res as $row ) {
				$dims = ReaderFeedback::expandRatings( $row->rfb_ratings );
				foreach( $dims as $tag => $val ) {
					if( isset($votes[$tag]) && isset($votes[$tag][$val]) ) {
						$votes[$tag][$val]++;
					}
				}
			}
			// Tack on $add for display (used to avoid cache/lag)
			foreach( $add as $tag => $val ) {
				if( isset($votes[$tag]) && isset($votes[$tag][$val]) ) {
					$votes[$tag][$val]++;
				}
			}
			$wgMemc->set( $key, array( $votes, $now ), 24*3600 );
		}
		// Output multi-column list
		$html = "<table class='rfb-reader_feedback_table' cellspacing='0'><tr>";
		foreach( ReaderFeedback::getFeedbackTags() as $tag => $w ) {
			// Get tag average...
			$dist = isset($votes[$tag]) ? $votes[$tag] : array();
			$count = array_sum($dist);
			if( $count ) {
				$ave = ($dist[0] + 2*$dist[1] + 3*$dist[2] + 4*$dist[3] + 5*$dist[4])/$count;
				$ave = round($ave,1);
			} else {
				$ave = '-'; // DIV by zero
			}
			$html .= '<td align="center"><b>'.wfMsgHtml("readerfeedback-$tag").'</b>&#160;&#160;'.
				'<sup>('.wfMsgHtml('ratinghistory-ave',$wgLang->formatNum($ave)).')</sup></td>';
		}
		$html .= '</tr><tr>';
		foreach( $votes as $dist ) {
			$html .= '<td><table>';
			$html .= '<tr><th align="left">'.wfMsgHtml('ratinghistory-table-rating').'</th>';
			for( $i = 1; $i <= 5; $i++ ) {
				$html .= "<td align='center' class='rfb-rating-option-".($i-1)."'>$i</td>";
			}
			$html .= '</tr><tr>';
			$html .= '<th align="left">'.wfMsgHtml("ratinghistory-table-votes").'</th>';
			$html .= '<td align="center">'.$dist[0].'</td>';
			$html .= '<td align="center">'.$dist[1].'</td>';
			$html .= '<td align="center">'.$dist[2].'</td>';
			$html .= '<td align="center">'.$dist[3].'</td>';
			$html .= '<td align="center">'.$dist[4].'</td>';
			$html .= "</tr></table></td>\n";
		}
		$html .= '</tr></table>';
		return $html;
	}
 /**
  * Encapsulated permission check.
  * @param User $oCurrentUser The requested MediaWiki User.
  * @param Title $oCurrentTitle The MediaWiki Title to check against.
  * @return boolean Wether the user is allowed to change responsibility or not.
  */
 public function userIsAllowedToChangeResponsibility($oCurrentUser, $oCurrentTitle)
 {
     //Check users permissions and/or if he is assigned as a responsible editor
     $bUserIsAllowedToChangeResponsiblity = false;
     $aResponsibleEditorIds = $this->getResponsibleEditorIdsByArticleId($oCurrentTitle->getArticleId());
     if ($oCurrentTitle->userCan('responsibleeditors-changeresponsibility') === true) {
         $bUserIsAllowedToChangeResponsiblity = true;
     } else {
         if (BsConfig::get('MW::ResponsibleEditors::ResponsibleEditorMayChangeAssignment') && in_array($oCurrentUser->getId(), $aResponsibleEditorIds)) {
             $bUserIsAllowedToChangeResponsiblity = true;
         }
     }
     return $bUserIsAllowedToChangeResponsiblity;
 }
示例#22
0
 /**
  * This is the function that gets called for "action=edit". It
  * sets up various member variables, then passes execution to
  * another function, usually showEditForm()
  *
  * The edit form is self-submitting, so that when things like
  * preview and edit conflicts occur, we get the same form back
  * with the extra stuff added.  Only when the final submission
  * is made and all is well do we actually save and redirect to
  * the newly-edited page.
  */
 function edit()
 {
     global $wgOut, $wgRequest, $wgUser;
     // Allow extensions to modify/prevent this form or submission
     if (!wfRunHooks('AlternateEdit', array($this))) {
         return;
     }
     wfProfileIn(__METHOD__);
     wfDebug(__METHOD__ . ": enter\n");
     // This is not an article
     $wgOut->setArticleFlag(false);
     $this->importFormData($wgRequest);
     $this->firsttime = false;
     if ($this->live) {
         $this->livePreview();
         wfProfileOut(__METHOD__);
         return;
     }
     if (wfReadOnly() && $this->save) {
         // Force preview
         $this->save = false;
         $this->preview = true;
     }
     $wgOut->addModules(array('mediawiki.action.edit'));
     if ($wgUser->getOption('uselivepreview', false)) {
         $wgOut->addModules('mediawiki.legacy.preview');
     }
     // Bug #19334: textarea jumps when editing articles in IE8
     $wgOut->addStyle('common/IE80Fixes.css', 'screen', 'IE 8');
     $permErrors = $this->getEditPermissionErrors();
     if ($permErrors) {
         // Auto-block user's IP if the account was "hard" blocked
         $wgUser->spreadAnyEditBlock();
         wfDebug(__METHOD__ . ": User can't edit\n");
         $content = $this->getContent(null);
         $content = $content === '' ? null : $content;
         $this->readOnlyPage($content, true, $permErrors, 'edit');
         wfProfileOut(__METHOD__);
         return;
     } else {
         if ($this->save) {
             $this->formtype = 'save';
         } elseif ($this->preview) {
             $this->formtype = 'preview';
         } elseif ($this->diff) {
             $this->formtype = 'diff';
         } else {
             # First time through
             $this->firsttime = true;
             if ($this->previewOnOpen()) {
                 $this->formtype = 'preview';
             } else {
                 $this->formtype = 'initial';
             }
         }
     }
     // If they used redlink=1 and the page exists, redirect to the main article
     if ($wgRequest->getBool('redlink') && $this->mTitle->exists()) {
         $wgOut->redirect($this->mTitle->getFullURL());
     }
     wfProfileIn(__METHOD__ . "-business-end");
     $this->isConflict = false;
     // css / js subpages of user pages get a special treatment
     $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
     $this->isCssSubpage = $this->mTitle->isCssSubpage();
     $this->isJsSubpage = $this->mTitle->isJsSubpage();
     $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
     $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
     # Show applicable editing introductions
     if ($this->formtype == 'initial' || $this->firsttime) {
         $this->showIntro();
     }
     if ($this->mTitle->isTalkPage()) {
         $wgOut->addWikiMsg('talkpagetext');
     }
     # Optional notices on a per-namespace and per-page basis
     $editnotice_ns = 'editnotice-' . $this->mTitle->getNamespace();
     $editnotice_ns_message = wfMessage($editnotice_ns)->inContentLanguage();
     if ($editnotice_ns_message->exists()) {
         $wgOut->addWikiText($editnotice_ns_message->plain());
     }
     if (MWNamespace::hasSubpages($this->mTitle->getNamespace())) {
         $parts = explode('/', $this->mTitle->getDBkey());
         $editnotice_base = $editnotice_ns;
         while (count($parts) > 0) {
             $editnotice_base .= '-' . array_shift($parts);
             $editnotice_base_msg = wfMessage($editnotice_base)->inContentLanguage();
             if ($editnotice_base_msg->exists()) {
                 $wgOut->addWikiText($editnotice_base_msg->plain());
             }
         }
     }
     # Attempt submission here.  This will check for edit conflicts,
     # and redundantly check for locked database, blocked IPs, etc.
     # that edit() already checked just in case someone tries to sneak
     # in the back door with a hand-edited submission URL.
     if ('save' == $this->formtype) {
         if (!$this->attemptSave()) {
             wfProfileOut(__METHOD__ . "-business-end");
             wfProfileOut(__METHOD__);
             return;
         }
     }
     # First time through: get contents, set time for conflict
     # checking, etc.
     if ('initial' == $this->formtype || $this->firsttime) {
         if ($this->initialiseForm() === false) {
             $this->noSuchSectionPage();
             wfProfileOut(__METHOD__ . "-business-end");
             wfProfileOut(__METHOD__);
             return;
         }
         if (!$this->mTitle->getArticleId()) {
             wfRunHooks('EditFormPreloadText', array(&$this->textbox1, &$this->mTitle));
         } else {
             wfRunHooks('EditFormInitialText', array($this));
         }
     }
     $this->showEditForm();
     wfProfileOut(__METHOD__ . "-business-end");
     wfProfileOut(__METHOD__);
 }
 protected function hasCxTag(Title $title, $row)
 {
     $dbr = wfGetDB(DB_SLAVE);
     $conds = array();
     # Apparently translation_start_timestamp has been incorrecly updated on changes in the past
     #$conds[] = 'rev_timestamp > ' . $dbr->addQuotes( $row->translation_start_timestamp );
     $conds['rev_page'] = $title->getArticleId();
     $conds[] = 'rev_id = ct_rev_id';
     $conds['ct_tag'] = 'contenttranslation';
     $field = $dbr->selectField(array('revision', 'change_tag'), 'ct_tag', $conds, __METHOD__);
     return $field === 'contenttranslation';
 }
示例#24
0
 /**
  * @param $title Title
  * @return bool
  */
 public static function isSourcePage(Title $title)
 {
     static $cache = null;
     $cacheObj = wfGetCache(CACHE_ANYTHING);
     $cacheKey = wfMemcKey('pagetranslation', 'sourcepages');
     if ($cache === null) {
         $cache = $cacheObj->get($cacheKey);
     }
     if (!is_array($cache)) {
         $cache = self::getTranslatablePages();
         $cacheObj->set($cacheKey, $cache, 60 * 5);
     }
     return in_array($title->getArticleId(), $cache);
 }
示例#25
0
 /**
  * Uses MediaWiki LinkEnd hook to store outbound links
  * @param unknown_type $skin
  * @param Title $target
  * @param array $options
  * @param unknown_type $text
  * @param array $attribs
  * @param unknown_type $ret
  * @return boolean
  */
 public static function onLinkEnd($skin, \Title $target, array $options, &$text, array &$attribs, &$ret)
 {
     $service = self::$service ?: new MediaWikiService();
     self::$service = $service;
     $targetId = $service->getCanonicalPageIdFromPageId($target->getArticleId());
     if ($targetId !== 0) {
         $targetDocId = $service->getWikiId() . '_' . $targetId;
         self::$outboundLinks[] = sprintf("%s | %s", $targetDocId, strip_tags($text));
     }
     return true;
 }
 /**
  * @static
  * @param Title $title
  * @return PageStatsService
  */
 public static function newFromTitle($title)
 {
     $service = new self($title->getArticleId());
     $service->mTitle = $title;
     return $service;
 }
 protected function findRevisionToTag(Title $title, $name, $timestamp)
 {
     $dbr = wfGetDB(DB_SLAVE);
     // Allow one minute slack
     $ts = wfTimestamp(TS_UNIX, $timestamp) + 60;
     $tables = array('revision', 'change_tag');
     $conds = array();
     $conds[] = 'rev_timestamp < ' . $dbr->addQuotes($dbr->timestamp($ts));
     $conds['rev_page'] = $title->getArticleId();
     $conds['rev_user_text'] = $name;
     // Take the oldest timestamp by the author
     $options = array('ORDER BY' => 'rev_timestamp ASC');
     $revId = $dbr->selectField($tables, 'rev_id', $conds, __METHOD__, $options);
     return $revId;
 }
 /**
  * Returns the main classification type of the template.
  * @return string
  */
 public function getType()
 {
     return Wikia::getProps($this->title->getArticleId(), self::TEMPLATE_CLASSIFICATION_MAIN_PROP);
 }
示例#29
0
 /**
  * Return instance of WikiaPoll for given title from Poll namespace
  */
 public static function newFromTitle(Title $title)
 {
     $id = $title->getArticleId();
     return self::newFromId($id);
 }
	/**
	 * @param $title Title
	 * @param $revision int
	 * @param $fuzzy bool
	 */
	protected static function updateFuzzyTag( Title $title, $revision, $fuzzy ) {
		$dbw = wfGetDB( DB_MASTER );

		$conds = array(
			'rt_page' => $title->getArticleId(),
			'rt_type' => RevTag::getType( 'fuzzy' ),
			'rt_revision' => $revision
		);

		// Replace the existing fuzzy tag, if any
		if ( $fuzzy !== false ) {
			$index = array_keys( $conds );
			$dbw->replace( 'revtag', array( $index ), $conds, __METHOD__ );
		} else {
			$dbw->delete( 'revtag', $conds, __METHOD__ );
		}
	}