public function testHidingRevisions()
 {
     $user = self::$users['sysop']->getUser();
     $revid = array_shift($this->revs);
     $out = $this->doApiRequest(array('action' => 'revisiondelete', 'type' => 'revision', 'target' => self::$page, 'ids' => $revid, 'hide' => 'content|user|comment', 'token' => $user->getEditToken()));
     // Check the output
     $out = $out[0]['revisiondelete'];
     $this->assertEquals($out['status'], 'Success');
     $this->assertArrayHasKey('items', $out);
     $item = $out['items'][0];
     $this->assertArrayHasKey('userhidden', $item);
     $this->assertArrayHasKey('commenthidden', $item);
     $this->assertArrayHasKey('texthidden', $item);
     $this->assertEquals($item['id'], $revid);
     // Now check that that revision was actually hidden
     $rev = Revision::newFromId($revid);
     $this->assertEquals($rev->getContent(Revision::FOR_PUBLIC), null);
     $this->assertEquals($rev->getComment(Revision::FOR_PUBLIC), '');
     $this->assertEquals($rev->getUser(Revision::FOR_PUBLIC), 0);
     // Now test unhiding!
     $out2 = $this->doApiRequest(array('action' => 'revisiondelete', 'type' => 'revision', 'target' => self::$page, 'ids' => $revid, 'show' => 'content|user|comment', 'token' => $user->getEditToken()));
     // Check the output
     $out2 = $out2[0]['revisiondelete'];
     $this->assertEquals($out2['status'], 'Success');
     $this->assertArrayHasKey('items', $out2);
     $item = $out2['items'][0];
     $this->assertArrayNotHasKey('userhidden', $item);
     $this->assertArrayNotHasKey('commenthidden', $item);
     $this->assertArrayNotHasKey('texthidden', $item);
     $this->assertEquals($item['id'], $revid);
     $rev = Revision::newFromId($revid);
     $this->assertNotEquals($rev->getContent(Revision::FOR_PUBLIC), null);
     $this->assertNotEquals($rev->getComment(Revision::FOR_PUBLIC), '');
     $this->assertNotEquals($rev->getUser(Revision::FOR_PUBLIC), 0);
 }
 public function execute()
 {
     $params = $this->extractRequestParams();
     $rev1 = $this->revisionOrTitleOrId($params['fromrev'], $params['fromtitle'], $params['fromid']);
     $rev2 = $this->revisionOrTitleOrId($params['torev'], $params['totitle'], $params['toid']);
     $revision = Revision::newFromId($rev1);
     if (!$revision) {
         $this->dieUsage('The diff cannot be retrieved, ' . 'one revision does not exist or you do not have permission to view it.', 'baddiff');
     }
     $contentHandler = $revision->getContentHandler();
     $de = $contentHandler->createDifferenceEngine($this->getContext(), $rev1, $rev2, null, true, false);
     $vals = array();
     if (isset($params['fromtitle'])) {
         $vals['fromtitle'] = $params['fromtitle'];
     }
     if (isset($params['fromid'])) {
         $vals['fromid'] = $params['fromid'];
     }
     $vals['fromrevid'] = $rev1;
     if (isset($params['totitle'])) {
         $vals['totitle'] = $params['totitle'];
     }
     if (isset($params['toid'])) {
         $vals['toid'] = $params['toid'];
     }
     $vals['torevid'] = $rev2;
     $difftext = $de->getDiffBody();
     if ($difftext === false) {
         $this->dieUsage('The diff cannot be retrieved. Maybe one or both revisions do ' . 'not exist or you do not have permission to view them.', 'baddiff');
     }
     ApiResult::setContentValue($vals, 'body', $difftext);
     $this->getResult()->addValue(null, $this->getModuleName(), $vals);
 }
Esempio n. 3
0
 public static function articleCountWordDiff(&$article, &$user, $newText, $summary, $flag, $fake1, $fake2, &$flags, $revision, &$status, $baseRevId)
 {
     global $wgContentNamespaces, $wgSitename;
     wfProfileIn(__METHOD__);
     if (is_null($revision)) {
         // nothing's changed, quit early
         wfProfileOut(__METHOD__);
         return true;
     }
     if (!in_array($article->getTitle()->getNamespace(), $wgContentNamespaces)) {
         wfProfileOut(__METHOD__);
         return true;
     }
     // do not push reverts
     $baseRevision = Revision::newFromId($baseRevId);
     if ($baseRevision && $revision->getTextId() == $baseRevision->getTextId()) {
         wfProfileOut(__METHOD__);
         return true;
     }
     $diff = 0;
     $wNewCount = strlen($newText);
     $wOldCount = strlen($article->getRawText());
     $countDiff = $wNewCount - $wOldCount;
     if ($countDiff > self::$MIN_CHARS_TO_PUSH) {
         $params = array('$ARTICLENAME' => $article->getTitle()->getText(), '$WIKINAME' => $wgSitename, '$ARTICLE_URL' => $article->getTitle()->getFullURL("ref=fbfeed&fbtype=largeedit"), '$EVENTIMG' => self::$eventImage, '$SUMMART' => $summary, '$TEXT' => self::shortenText(self::parseArticle($article, $newText)));
         self::pushEvent(self::$messageName, $params, __CLASS__);
     }
     wfProfileOut(__METHOD__);
     return true;
 }
 protected function parseWikitext($title, $newRevId)
 {
     $apiParams = array('action' => 'parse', 'page' => $title->getPrefixedDBkey(), 'oldid' => $newRevId, 'prop' => 'text|revid|categorieshtml|displaytitle|modules|jsconfigvars');
     $api = new ApiMain(new DerivativeRequest($this->getRequest(), $apiParams, false), true);
     $api->execute();
     if (defined('ApiResult::META_CONTENT')) {
         $result = $api->getResult()->getResultData(null, array('BC' => array(), 'Types' => array(), 'Strip' => 'all'));
     } else {
         $result = $api->getResultData();
     }
     $content = isset($result['parse']['text']['*']) ? $result['parse']['text']['*'] : false;
     $categorieshtml = isset($result['parse']['categorieshtml']['*']) ? $result['parse']['categorieshtml']['*'] : false;
     $links = isset($result['parse']['links']) ? $result['parse']['links'] : array();
     $revision = Revision::newFromId($result['parse']['revid']);
     $timestamp = $revision ? $revision->getTimestamp() : wfTimestampNow();
     $displaytitle = isset($result['parse']['displaytitle']) ? $result['parse']['displaytitle'] : false;
     $modules = isset($result['parse']['modules']) ? $result['parse']['modules'] : array();
     $jsconfigvars = isset($result['parse']['jsconfigvars']) ? $result['parse']['jsconfigvars'] : array();
     if ($content === false || strlen($content) && $revision === null) {
         return false;
     }
     if ($displaytitle !== false) {
         // Escape entities as in OutputPage::setPageTitle()
         $displaytitle = Sanitizer::normalizeCharReferences(Sanitizer::removeHTMLtags($displaytitle));
     }
     return array('content' => $content, 'categorieshtml' => $categorieshtml, 'basetimestamp' => $timestamp, 'starttimestamp' => wfTimestampNow(), 'displayTitleHtml' => $displaytitle, 'modules' => $modules, 'jsconfigvars' => $jsconfigvars);
 }
Esempio n. 5
0
 /**
  * Patrols the article or provides the reason the patrol failed.
  */
 public function execute()
 {
     $params = $this->extractRequestParams();
     $this->requireOnlyOneParameter($params, 'rcid', 'revid');
     if (isset($params['rcid'])) {
         $rc = RecentChange::newFromID($params['rcid']);
         if (!$rc) {
             $this->dieUsageMsg(array('nosuchrcid', $params['rcid']));
         }
     } else {
         $rev = Revision::newFromId($params['revid']);
         if (!$rev) {
             $this->dieUsageMsg(array('nosuchrevid', $params['revid']));
         }
         $rc = $rev->getRecentChange();
         if (!$rc) {
             $this->dieUsage('The revision ' . $params['revid'] . " can't be patrolled as it's too old", 'notpatrollable');
         }
     }
     $retval = $rc->doMarkPatrolled($this->getUser());
     if ($retval) {
         $this->dieUsageMsg(reset($retval));
     }
     $result = array('rcid' => intval($rc->getAttribute('rc_id')));
     ApiQueryBase::addTitleInfo($result, $rc->getTitle());
     $this->getResult()->addValue(null, $this->getModuleName(), $result);
 }
 protected function logTagAdded($tags, $revId, $user, $reason)
 {
     // log it
     $logEntry = new ManualLogEntry('tag', 'update');
     $logEntry->setPerformer($user);
     $logEntry->setComment($reason);
     // find the appropriate target page
     if ($revId) {
         $rev = Revision::newFromId($revId);
         if ($rev) {
             $logEntry->setTarget($rev->getTitle());
         }
     }
     if (!$logEntry->getTarget()) {
         // target is required, so we have to set something
         $logEntry->setTarget(SpecialPage::getTitleFor('Tags'));
     }
     $logParams = array('4::revid' => $revId, '6:list:tagsAdded' => $tags, '7:number:tagsAddedCount' => count($tags));
     $logEntry->setParameters($logParams);
     $logEntry->setRelations(array('Tag' => $tags));
     $dbw = wfGetDB(DB_MASTER);
     $logId = $logEntry->insert($dbw);
     // Only send this to UDP, not RC, similar to patrol events
     $logEntry->publish($logId, 'udp');
     //$logEntry->publish( $logId );
 }
Esempio n. 7
0
 /**
  * get board info: the number of threads, the number of posts, the username and timestamp of the last post
  * @return array $info
  */
 public function getBoardInfo($db = DB_SLAVE)
 {
     wfProfileIn(__METHOD__);
     $memKey = wfMemcKey('forum_board_info', $this->getId());
     if ($db == DB_SLAVE) {
         $info = $this->wg->Memc->get($memKey);
     }
     if (empty($info)) {
         $db = wfGetDB($db);
         $row = $db->selectRow(array('comments_index'), array('count(if(parent_comment_id=0,1,null)) threads, count(*) posts, max(first_rev_id) rev_id'), array('parent_page_id' => $this->getId(), 'archived' => 0, 'deleted' => 0, 'removed' => 0), __METHOD__);
         $info = array('postCount' => 0, 'threadCount' => 0);
         if ($row) {
             $info = array('postCount' => $row->posts, 'threadCount' => $row->threads);
             // get last post info
             $revision = Revision::newFromId($row->rev_id);
             if ($revision instanceof Revision) {
                 if ($revision->getRawUser() == 0) {
                     $username = wfMsg('oasis-anon-user');
                 } else {
                     $username = $revision->getRawUserText();
                 }
                 $userprofile = Title::makeTitle($this->wg->EnableWallExt ? NS_USER_WALL : NS_USER_TALK, $username)->getFullURL();
                 $info['lastPost'] = array('username' => $username, 'userprofile' => $userprofile, 'timestamp' => $revision->getTimestamp());
             }
         }
         $this->wg->Memc->set($memKey, $info, 60 * 60 * 12);
     }
     wfProfileOut(__METHOD__);
     return $info;
 }
Esempio n. 8
0
 /**
  * @param Parser $parser
  * @return string
  */
 public static function moddate($parser)
 {
     $title = $parser->getTitle();
     if (!$title || !$title->exists()) {
         return '';
     }
     $lastRev = Revision::newFromId($title->getLatestRevID());
     return date("j M Y", wfTimestamp(TS_UNIX, $lastRev->getTimestamp()));
 }
 function feedItemDesc($row)
 {
     if (isset($row->rev_id)) {
         $revision = Revision::newFromId($row->rev_id);
         if ($revision) {
             return '<p>' . htmlspecialchars(wfMsg('summary')) . ': ' . $text . "</p>\n<hr />\n<div>" . nl2br(htmlspecialchars($revision->getText())) . "</div>";
         }
     }
     return parent::feedItemDesc($row);
 }
Esempio n. 10
0
 public function getResultParams()
 {
     $testInfo = $this->getTestInfo();
     $r = Revision::newFromId($testInfo['rq_rev_new']);
     if (!$r) {
         throw new Exception("Unable to create revision from testInfo['rq_rev_new'] = {$testInfo['rq_rev_new']}");
     }
     $params['title'] = $r->getTitle();
     $params['old'] = $testInfo['rq_rev_old'];
     $params['new'] = $testInfo['rq_rev_new'];
     return $params;
 }
	public function execute() {
		global $wgUser;
		if ( !$wgUser->isallowed( self::$right ) ) {
			$this->dieUsage( 'Permission denied', 'permissiondenied' );
		}

		$params = $this->extractRequestParams();

		$revision = Revision::newFromId( $params['revision'] );
		if ( !$revision ) {
			$this->dieUsage( 'Invalid revision', 'invalidrevision' );
		}

		$title = $revision->getTitle();
		$handle = new MessageHandle( $title );
		if ( !$handle->isValid() ) {
			$this->dieUsage( 'Unknown message', 'unknownmessage' );
		}

		if ( $handle->isFuzzy() ) {
			$this->dieUsage( 'Cannot review fuzzy translations', 'fuzzymessage' );
		}

		if ( $revision->getUser() == $wgUser->getId() ) {
			$this->dieUsage( 'Cannot review own translations', 'owntranslation' );
		}

		$dbw = wfGetDB( DB_MASTER );
		$table = 'translate_reviews';
		$row = array(
			'trr_user' => $wgUser->getId(),
			'trr_page' => $revision->getPage(),
			'trr_revision' => $revision->getId(),
		);
		$options = array( 'IGNORE' );
		$res = $dbw->insert( $table, $row, __METHOD__, $options );
		if ( !$dbw->affectedRows() ) {
			$this->setWarning( 'Already marked as reviewed by you' );
		} else {
			$logger = new LogPage( 'translationreview' );
			$params = array( $revision->getId() );
			$logger->addEntry( 'message', $title, null, $params, $wgUser );
		}

		$output = array( 'review' => array(
			'title' => $title->getPrefixedText(),
			'pageid' => $revision->getPage(),
			'revision' => $revision->getId()
		) );

		$this->getResult()->addValue( null, $this->getModuleName(), $output );
	}
Esempio n. 12
0
 public static function revertTips($user, $cutoff, $cutoff2, $unpatrol_limit)
 {
     global $wgLang, $wgOut;
     //max number of possible unpatrols
     $limit = array();
     if (!empty($unpatrol_limit)) {
         $limit = array('LIMIT' => $unpatrol_limit);
     }
     $dbw = wfGetDB(DB_MASTER);
     $options = array('tw_user' => $user->getID(), "tw_timestamp > '{$cutoff}'");
     if ($cutoff2) {
         $options[] = "tw_timestamp < '{$cutoff2}'";
     }
     $res = $dbw->select('tipsandwarnings_log', array('tw_id', 'tw_rev_this'), $options, __METHOD__, $limit);
     $tipIds = array();
     while ($row = $dbw->fetchObject($res)) {
         $tipIds[$row->tw_id] = $row->tw_rev_this;
     }
     wfRunHooks('UnpatrolTips', array(&$tipIds));
     $count = sizeof($tipIds);
     foreach ($tipIds as $tipId => $revId) {
         // undo the tip
         $success = TipsPatrol::undoTip($tipId);
         if ($revId) {
             $revision = Revision::newFromId($revId);
             $title = $revision->getTitle();
             if (!$success) {
                 $wgOut->addHTML("failed to undo tip: {$tipId} with revId: {$revId} with Title: {$title}<br>");
                 continue;
             }
             $wgOut->addHTML("undid approved tip: {$tipId} with revId: {$revId} with Title: {$title}<br>");
         } else {
             $wgOut->addHTML("undid rejected tip: {$tipId} <br>");
         }
     }
     //log the change
     $logTitle = Title::newFromText('Special:UnpatrolTips');
     $logPage = new LogPage('undotips', false);
     $logData = array();
     $logMessage = "[[User:"******"]]: {$count} tip patrols undone";
     $logPage->addEntry('unpatrol', $logTitle, $logMessage, $logData);
     // set the original logs to be deleted
     unset($options);
     $options = array('log_user' => $user->getID(), 'log_type' => 'newtips', "log_timestamp > '{$cutoff}'", 'log_deleted' => 0);
     if ($cutoff2) {
         $options[] = "tw_timestamp < '{$cutoff2}'";
     }
     $res = $dbw->update('logging', array('log_deleted' => 1), $options, __METHOD__, $limit);
     return $count;
 }
 public function execute()
 {
     if (!$this->getUser()->isAllowed(self::$right)) {
         $this->dieUsage('Permission denied', 'permissiondenied');
     }
     $params = $this->extractRequestParams();
     $revision = Revision::newFromId($params['revision']);
     if (!$revision) {
         $this->dieUsage('Invalid revision', 'invalidrevision');
     }
     $error = self::getReviewBlockers($this->getUser(), $revision);
     switch ($error) {
         case '':
             // Everything is okay
             break;
         case 'permissiondenied':
             $this->dieUsage('Permission denied', $error);
             break;
             // Unreachable, but throws off code analyzer.
         // Unreachable, but throws off code analyzer.
         case 'blocked':
             $this->dieUsage('You have been blocked', $error);
             break;
             // Unreachable, but throws off code analyzer.
         // Unreachable, but throws off code analyzer.
         case 'unknownmessage':
             $this->dieUsage('Unknown message', $error);
             break;
             // Unreachable, but throws off code analyzer.
         // Unreachable, but throws off code analyzer.
         case 'owntranslation':
             $this->dieUsage('Cannot review own translations', $error);
             break;
             // Unreachable, but throws off code analyzer.
         // Unreachable, but throws off code analyzer.
         case 'fuzzymessage':
             $this->dieUsage('Cannot review fuzzy translations', $error);
             break;
             // Unreachable, but throws off code analyzer.
         // Unreachable, but throws off code analyzer.
         default:
             $this->dieUsage('Unknown error', $error);
     }
     $ok = self::doReview($this->getUser(), $revision);
     if (!$ok) {
         $this->setWarning('Already marked as reviewed by you');
     }
     $output = array('review' => array('title' => $revision->getTitle()->getPrefixedText(), 'pageid' => $revision->getPage(), 'revision' => $revision->getId()));
     $this->getResult()->addValue(null, $this->getModuleName(), $output);
 }
 /**
  * This function does essentially the same as RevisionReview::AjaxReview,
  * except that it generates the template and image parameters itself.
  */
 public function execute()
 {
     global $wgUser;
     $params = $this->extractRequestParams();
     // Check basic permissions
     if (!$wgUser->isAllowed('review')) {
         $this->dieUsage("You don't have the right to review revisions.", 'permissiondenied');
     } elseif ($wgUser->isBlocked(false)) {
         $this->dieUsageMsg(array('blockedtext'));
     }
     $newRev = Revision::newFromId($params['oldid']);
     if (!$newRev || !$newRev->getTitle()) {
         $this->dieUsage("Cannot find a revision with the specified ID.", 'notarget');
     }
     $title = $newRev->getTitle();
     $fa = FlaggableWikiPage::getTitleInstance($title);
     if (!$fa->isReviewable()) {
         $this->dieUsage("Provided page is not reviewable.", 'notreviewable');
     }
     $status = false;
     if ($params['previd']) {
         // changes
         $oldRev = Revision::newFromId($params['previd']);
         if (!$oldRev || $oldRev->getPage() != $newRev->getPage()) {
             $this->dieUsage("Revisions do not belong to the same page.", 'notarget');
         }
         // Mark as reviewing...
         if ($params['reviewing']) {
             $status = FRUserActivity::setUserReviewingDiff($wgUser, $params['previd'], $params['oldid']);
             // Unmark as reviewing...
         } else {
             $status = FRUserActivity::clearUserReviewingDiff($wgUser, $params['previd'], $params['oldid']);
         }
     } else {
         // Mark as reviewing...
         if ($params['reviewing']) {
             $status = FRUserActivity::setUserReviewingPage($wgUser, $newRev->getPage());
             // Unmark as reviewing...
         } else {
             $status = FRUserActivity::clearUserReviewingPage($wgUser, $newRev->getPage());
         }
     }
     # Success in setting flag...
     if ($status === true) {
         $this->getResult()->addValue(null, $this->getModuleName(), array('result' => 'Success'));
         # Failure...
     } else {
         $this->getResult()->addValue(null, $this->getModuleName(), array('result' => 'Failure'));
     }
 }
 /**
  * Returns the last edit of the user
  *
  * @return Revision|false
  */
 public function getLastEdit()
 {
     $conds = array('rev_user' => $this->user->getId());
     $options = array('LIMIT' => 1, 'ORDER BY' => 'rev_timestamp DESC');
     $dbr = wfGetDB(DB_SLAVE, 'revision');
     $res = $dbr->select('revision', 'rev_id', $conds, __METHOD__, $options);
     $row = $res->fetchObject();
     if ($row) {
         $rev = Revision::newFromId($row->rev_id);
     } else {
         $rev = false;
     }
     return $rev;
 }
Esempio n. 16
0
 public static function formatDiffRow($title, $oldid, $newid, $timestamp, $comment, $actiontext = '')
 {
     global $wgFeedDiffCutoff, $wgContLang, $wgUser;
     wfProfileIn(__FUNCTION__);
     $skin = $wgUser->getSkin();
     # log enties
     $completeText = '<p>' . implode(' ', array_filter(array($actiontext, $skin->formatComment($comment)))) . "</p>\n";
     //NOTE: Check permissions for anonymous users, not current user.
     //      No "privileged" version should end up in the cache.
     //      Most feed readers will not log in anway.
     $anon = new User();
     $accErrors = $title->getUserPermissionsErrors('read', $anon, true);
     if ($title->getNamespace() >= 0 && !$accErrors) {
         if ($oldid) {
             wfProfileIn(__FUNCTION__ . "-dodiff");
             #$diffText = $de->getDiff( wfMsg( 'revisionasof',
             #	$wgContLang->timeanddate( $timestamp ) ),
             #	wfMsg( 'currentrev' ) );
             // Don't bother generating the diff if we won't be able to show it
             if ($wgFeedDiffCutoff > 0) {
                 $de = new DifferenceEngine($title, $oldid, $newid);
                 $diffText = $de->getDiff(wfMsg('previousrevision'), wfMsg('revisionasof', $wgContLang->timeanddate($timestamp)));
             }
             if (strlen($diffText) > $wgFeedDiffCutoff || $wgFeedDiffCutoff <= 0) {
                 // Omit large diffs
                 $diffLink = $title->escapeFullUrl('diff=' . $newid . '&oldid=' . $oldid);
                 $diffText = '<a href="' . $diffLink . '">' . htmlspecialchars(wfMsgForContent('showdiff')) . '</a>';
             } elseif ($diffText === false) {
                 // Error in diff engine, probably a missing revision
                 $diffText = "<p>Can't load revision {$newid}</p>";
             } else {
                 // Diff output fine, clean up any illegal UTF-8
                 $diffText = UtfNormal::cleanUp($diffText);
                 $diffText = self::applyDiffStyle($diffText);
             }
             wfProfileOut(__FUNCTION__ . "-dodiff");
         } else {
             $rev = Revision::newFromId($newid);
             if (is_null($rev)) {
                 $newtext = '';
             } else {
                 $newtext = $rev->getText();
             }
             $diffText = '<p><b>' . wfMsg('newpage') . '</b></p>' . '<div>' . nl2br(htmlspecialchars($newtext)) . '</div>';
         }
         $completeText .= $diffText;
     }
     wfProfileOut(__FUNCTION__);
     return $completeText;
 }
 public function initEmail()
 {
     // This title is for the article being commented upon
     $titleText = $this->request->getVal('pageTitle');
     $titleNamespace = $this->request->getVal('namespace');
     $this->pageTitle = \Title::newFromText($titleText, $titleNamespace);
     // This revision ID is for the comment that was left
     $commentRevID = $this->getVal('currentRevId', false);
     if ($commentRevID) {
         $rev = \Revision::newFromId($commentRevID, \Revision::USE_MASTER_DB);
         if ($rev) {
             $this->commentTitle = $rev->getTitle(\Revision::USE_MASTER_DB);
         }
     }
     $this->assertValidParams();
 }
 /**
  * Retrieve the last edit to this page.
  * @return array defining edit with keys name, timestamp and gender
  */
 public function getLatestEdit()
 {
     $rev = Revision::newFromId($this->getTitle()->getLatestRevID());
     $unixTimestamp = wfTimestamp(TS_UNIX, $this->getLatestTimestamp());
     $edit = array('timestamp' => $unixTimestamp, 'name' => '', 'gender' => '');
     if ($rev) {
         $userId = $rev->getUser();
         if ($userId) {
             $revUser = User::newFromId($userId);
             $revUser->load(User::READ_NORMAL);
             $edit['name'] = $revUser->getName();
             $edit['gender'] = $revUser->getOption('gender');
         }
     }
     return $edit;
 }
Esempio n. 19
0
 function execute()
 {
     if ($this->hasOption('tpl-time')) {
         $this->templateTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('tpl-time')));
         Hooks::register('BeforeParserFetchTemplateAndtitle', [$this, 'onFetchTemplate']);
     }
     $this->clearLinkCache = $this->hasOption('reset-linkcache');
     // Set as a member variable to avoid function calls when we're timing the parse
     $this->linkCache = MediaWikiServices::getInstance()->getLinkCache();
     $title = Title::newFromText($this->getArg());
     if (!$title) {
         $this->error("Invalid title");
         exit(1);
     }
     if ($this->hasOption('page-time')) {
         $pageTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('page-time')));
         $id = $this->getRevIdForTime($title, $pageTimestamp);
         if (!$id) {
             $this->error("The page did not exist at that time");
             exit(1);
         }
         $revision = Revision::newFromId($id);
     } else {
         $revision = Revision::newFromTitle($title);
     }
     if (!$revision) {
         $this->error("Unable to load revision, incorrect title?");
         exit(1);
     }
     $warmup = $this->getOption('warmup', 1);
     for ($i = 0; $i < $warmup; $i++) {
         $this->runParser($revision);
     }
     $loops = $this->getOption('loops', 1);
     if ($loops < 1) {
         $this->error('Invalid number of loops specified', true);
     }
     $startUsage = getrusage();
     $startTime = microtime(true);
     for ($i = 0; $i < $loops; $i++) {
         $this->runParser($revision);
     }
     $endUsage = getrusage();
     $endTime = microtime(true);
     printf("CPU time = %.3f s, wall clock time = %.3f s\n", ($endUsage['ru_utime.tv_sec'] + $endUsage['ru_utime.tv_usec'] * 1.0E-6 - $startUsage['ru_utime.tv_sec'] - $startUsage['ru_utime.tv_usec'] * 1.0E-6) / $loops, ($endTime - $startTime) / $loops);
 }
 public function processEntites($userId, $entityKey)
 {
     wfProfileIn(__METHOD__);
     if (!$this->getEntityProcessed($userId, $entityKey)) {
         $entityKeyArray = explode('_', $entityKey);
         $rev = Revision::newFromId($entityKeyArray[0]);
         if (!empty($rev)) {
             $notif = F::build('WallNotificationEntity', array($rev, $this->app->wg->CityId), 'createFromRev');
             if (!empty($notif)) {
                 $wn = F::build('WallNotifications', array());
                 $wn->addNotificationLinks(array($userId), $notif);
             }
         }
         $this->setEntityProcessed($userId, $entityKey);
         $this->clearQueue();
     }
     wfProfileOut(__METHOD__);
 }
Esempio n. 21
0
 public function execute()
 {
     $this->output("Fetching redirects...\n");
     $dbr = $this->getDB(DB_SLAVE);
     $result = $dbr->select(array('page'), array('page_namespace', 'page_title', 'page_latest'), array('page_is_redirect' => 1));
     $count = $result->numRows();
     $this->output("Found {$count} redirects.\n" . "Checking for bad redirects:\n\n");
     foreach ($result as $row) {
         $title = Title::makeTitle($row->page_namespace, $row->page_title);
         $rev = Revision::newFromId($row->page_latest);
         if ($rev) {
             $target = $rev->getContent()->getRedirectTarget();
             if (!$target) {
                 $this->output($title->getPrefixedText() . "\n");
             }
         }
     }
     $this->output("\nDone.\n");
 }
Esempio n. 22
0
 protected function processIndividual($type, $params, $id)
 {
     $idResult = array($type => $id);
     // validate the ID
     $valid = false;
     switch ($type) {
         case 'rcid':
             $valid = RecentChange::newFromId($id);
             break;
         case 'revid':
             $valid = Revision::newFromId($id);
             break;
         case 'logid':
             $valid = self::validateLogId($id);
             break;
     }
     if (!$valid) {
         $idResult['status'] = 'error';
         $idResult += $this->parseMsg(array("nosuch{$type}", $id));
         return $idResult;
     }
     $status = ChangeTags::updateTagsWithChecks($params['add'], $params['remove'], $type === 'rcid' ? $id : null, $type === 'revid' ? $id : null, $type === 'logid' ? $id : null, null, $params['reason'], $this->getUser());
     if (!$status->isOK()) {
         if ($status->hasMessage('actionthrottledtext')) {
             $idResult['status'] = 'skipped';
         } else {
             $idResult['status'] = 'failure';
             $idResult['errors'] = $this->getErrorFormatter()->arrayFromStatus($status, 'error');
         }
     } else {
         $idResult['status'] = 'success';
         if (is_null($status->value->logId)) {
             $idResult['noop'] = '';
         } else {
             $idResult['actionlogid'] = $status->value->logId;
             $idResult['added'] = $status->value->addedTags;
             ApiResult::setIndexedTagName($idResult['added'], 't');
             $idResult['removed'] = $status->value->removedTags;
             ApiResult::setIndexedTagName($idResult['removed'], 't');
         }
     }
     return $idResult;
 }
Esempio n. 23
0
 function uncategorizeRequest($article, $user, $reason)
 {
     global $wgContLang, $wgOut;
     // is the article brandnew
     $t = $article->getTitle();
     if ($t->getNamespace() == NS_MAIN) {
         $dbr = wfGetDB(DB_SLAVE);
         $r = Title::makeTitle(NS_ARTICLE_REQUEST, $t->getText());
         if ($r->getArticleID() < 0) {
             $r = Title::makeTitle(NS_ARTICLE_REQUEST, EditPageWrapper::formatTitle($t->getText()));
         }
         if ($r->getArticleID() > 0) {
             $res = $dbr->select('revision', array('rev_id'), array('rev_page=' . $r->getArticleId()), "wfUncategorizeRequest", array('ORDER BY' => 'rev_id DESC'));
             $answered .= "[[" . $wgContLang->getNSText(NS_CATEGORY) . ":" . wfMsg('answered-requests') . "]]";
             $origcat = '';
             while ($row = $dbr->fetchObject($res)) {
                 $rev = Revision::newFromId($row->rev_id);
                 $text = $rev->getText();
                 // does it match answered?
                 if (strpos($text, $answered) === false) {
                     preg_match('/\\[\\[' . $wgContLang->getNSText(NS_CATEGORY) . '[^\\]]*\\]\\]/', $text, $matches);
                     if (sizeof($matches[0]) > 0) {
                         $origcat = $matches[0];
                     }
                     break;
                 }
             }
             if ($origcat != null) {
                 $revision = Revision::newFromTitle($r);
                 $text = $revision->getText();
                 if (strpos($text, wfMsg('answered-requests')) !== false) {
                     $ra = new Article($r);
                     $text = ereg_replace("[\\[]+" . $wgContLang->getNSText(NS_CATEGORY) . "\\:([- ]*[.]?[a-zA-Z0-9_/-?&%])*[]]+", "", $text);
                     $text .= "\n{$origcat}";
                     $ra->updateArticle($text, wfMsg('request-no-longer-answered'), true, false);
                     $wgOut->redirect('');
                 }
             }
             $dbr->freeResult($res);
         }
     }
     return true;
 }
Esempio n. 24
0
/**
 * Hook function called before content is saved.  At this point we can extract information about the article
 * and store it on the session to be used later.
 */
function alfArticleSave(&$article, &$user, &$text, &$summary, $minor, $watch, $sectionanchor, &$flags)
{
    // Execute a query to get the previous versions URL, we can use this later when we save the content
    // and want to update the version history.
    $url = null;
    $fieldName = "old_text";
    $revision = Revision::newFromId($article->mLatest);
    if (isset($revision) == true) {
        $dbw =& $article->getDB();
        $row = $dbw->selectRow('text', array('old_text', 'old_flags'), array('old_id' => $revision->getTextId()), "ExternalStoreAlfresco::alfArticleSave");
        $url = $row->{$fieldName};
    }
    // Store the details of the article in the session
    $_SESSION["title"] = ExternalStoreAlfresco::getTitle($article->getTitle());
    $_SESSION["description"] = $summary;
    $_SESSION["lastVersionUrl"] = $url;
    // Returning true ensures that the document is saved
    return true;
}
Esempio n. 25
0
function wfSpecialRevisionReel($par)
{
    global $wgOut, $wgParser, $wgRequest, $wgLang, $wgUser;
    $fname = "wfRevisionReel";
    if ($wgUser->getId() == 0) {
        $wgOut->showErrorPage('revisionreel', 'revisionreel_loggedin');
        return;
    }
    if ($wgRequest->getVal('rev', null)) {
        $wgOut->setArticleBodyOnly(true);
        $r = Revision::newFromId($wgRequest->getVal('rev'));
        $title = Title::newFromDBKey($wgRequest->getVal('target'));
        $output = $wgParser->parse($r->getText(), $title, new ParserOptions());
        $wgOut->addHTML($output->getText());
        return;
    }
    // landing page
    if ($wgRequest->getVal('target', null)) {
        $title = Title::newFromDBKey($wgRequest->getVal('target'));
        if ($title->getText() == wfMsg('mainpage')) {
            $wgOut->setPageTitle('Now Playing: ' . wfMsg('mainpage'));
        } else {
            $wgOut->setPageTitle('Now Playing: ' . wfMsg('howto', $title->getText()));
        }
        $dbr =& wfGetDB(DB_SLAVE);
        $res = $dbr->select('revision', array('rev_id', 'rev_timestamp'), array('rev_page=' . $title->getArticleID()), array('ORDER BY' => 'rev_id'));
        $revs = array();
        $rev_timestamps = array();
        while ($row = $dbr->fetchObject($res)) {
            $revs[] = $row->rev_id;
            $rev_timestamps[] = "'" . $wgLang->timeanddate(wfTimestamp(TS_MW, $row->rev_timestamp), true) . "'";
            //$rev_timestamps[] = "'" .  wfTimestamp( TS_MW, $row->rev_timestamp ) . "'";
        }
        $dbr->freeResult($res);
        $revisions = implode(',', $revs);
        $timestamps = implode(',', $rev_timestamps);
        $size = sizeof($revs);
        $wgOut->addHTML("\n\t\n<script type='text/javascript'>\n\n\t\tvar index = 0;\n\t\tvar stop = 0;\n\t\tvar size = {$size};\n\t\tvar revisions = new Array({$revisions});\n\t\tvar timestamps = new Array({$timestamps});\n\t\tvar requester = null;\n\t\tfunction showRevision() {\n\t\t\tvar box = document.getElementById('output_html');\n\t\t\tif ( requester.readyState == 4) {\n        \t\tif ( requester.status == 200) {\n\t\t\t\t\tbox.innerHTML = requester.responseText;\n\t\t\t\t\trevision_date = document.getElementById('revision_date');\n\t\t\t\t\trevision_date.innerHTML = timestamps[index] + ' Revision #' + (index + 1) + ' of ' + size;\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (index != size)\n\t\t\t\t\t\tsetTimeout(\"showReel()\", 3000);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\t\n\t\tfunction showReel() {\n\t\t\tif (stop == 1) return;\n    \t\ttry {\n        \t\trequester = new XMLHttpRequest();\n    \t\t} catch (error) {\n        \t\ttry {\n          \t \t\t requester = new ActiveXObject('Microsoft.XMLHTTP');\n        \t\t} catch (error) {\n\t\t\t\t\talert(error);\n           \t \t\treturn false;\n        \t\t}\n\t\t\t}\n\t\t\turl = location.href + '&rev=' + revisions[index];\n\t\t\trequester.onreadystatechange = showRevision;\n\t\t\trequester.open('GET', url);\n           \trequester.send(null);\n\t\t}\t\n\t\tsetTimeout(\"showReel()\", 1000);\n</script>\n\t\t<div style='border: 1px solid #ccc; padding: 5px;'>\n\t\t\t<input type='button' value='Stop!' onclick='stop = 1; this.value=\"Stopped.\";'>\n\t\t\t<input type='button' value='Go back 5' onclick='if (index > 5) index =- 5; else index = 0;'>\n\t\t\t<input type='button' value='Go forward 5' onclick='index += 5'>\n<span id='revision_date' style='margin-left:20px; font-weight: bold;'> </span>\n\t\t</div>\n\n\t\t\t<br/>\n\t\t\t<div id='output_html' style='margin-top: 20px;'>\n\t\t\t\tGenerating slideshow....\n\t\t\t</div>\n\t\t");
        return;
    }
}
Esempio n. 26
0
 protected function setup($par)
 {
     global $wgRequest, $wgUser;
     // Options
     $opts = new FormOptions();
     $this->opts = $opts;
     // bind
     $opts->add('page1', '');
     $opts->add('page2', '');
     $opts->add('rev1', '');
     $opts->add('rev2', '');
     $opts->add('action', '');
     // Set values
     $opts->fetchValuesFromRequest($wgRequest);
     $title1 = Title::newFromText($opts->getValue('page1'));
     $title2 = Title::newFromText($opts->getValue('page2'));
     if ($title1 && $title1->exists() && $opts->getValue('rev1') == '') {
         $pda = new Article($title1);
         $pdi = $pda->getID();
         $pdLastRevision = Revision::loadFromPageId(wfGetDB(DB_SLAVE), $pdi);
         $opts->setValue('rev1', $pdLastRevision->getId());
     } elseif ($opts->getValue('rev1') != '') {
         $pdrev = Revision::newFromId($opts->getValue('rev1'));
         if ($pdrev) {
             $opts->setValue('page1', $pdrev->getTitle()->getPrefixedText());
         }
     }
     if ($title2 && $title2->exists() && $opts->getValue('rev2') == '') {
         $pda = new Article($title2);
         $pdi = $pda->getID();
         $pdLastRevision = Revision::loadFromPageId(wfGetDB(DB_SLAVE), $pdi);
         $opts->setValue('rev2', $pdLastRevision->getId());
     } elseif ($opts->getValue('rev2') != '') {
         $pdrev = Revision::newFromId($opts->getValue('rev2'));
         if ($pdrev) {
             $opts->setValue('page2', $pdrev->getTitle()->getPrefixedText());
         }
     }
     // Store some objects
     $this->skin = $wgUser->getSkin();
 }
 public function getData()
 {
     $db = wfGetDB(DB_MASTER);
     $conds = array('rt_page' => $this->handle->getTitle()->getArticleID(), 'rt_type' => RevTag::getType('tp:transver'));
     $options = array('ORDER BY' => 'rt_revision DESC');
     $translationRevision = $db->selectField('revtag', 'rt_value', $conds, __METHOD__, $options);
     if ($translationRevision === false) {
         throw new TranslationHelperException("No definition revision recorded");
     }
     $definitionTitle = Title::makeTitleSafe($this->handle->getTitle()->getNamespace(), $this->handle->getKey() . '/' . $this->group->getSourceLanguage());
     if (!$definitionTitle || !$definitionTitle->exists()) {
         throw new TranslationHelperException("Definition page doesn't exist");
     }
     // Using newFromId instead of newFromTitle, because the page might have been renamed
     $oldrev = Revision::newFromId($translationRevision);
     if (!$oldrev) {
         throw new TranslationHelperException("Old definition version doesn't exist anymore");
     }
     $oldContent = $oldrev->getContent();
     $newContent = $this->getDefinitionContent();
     if (!$oldContent) {
         throw new TranslationHelperException("Old definition version doesn't exist anymore");
     }
     if (!$oldContent instanceof WikitextContent || !$newContent instanceof WikitextContent) {
         throw new TranslationHelperException('Can only work on Wikitext content');
     }
     if ($oldContent->equals($newContent)) {
         throw new TranslationHelperException('No changes');
     }
     $diff = new DifferenceEngine($this->context);
     if (method_exists('DifferenceEngine', 'setTextLanguage')) {
         $diff->setTextLanguage($this->group->getSourceLanguage());
     }
     $diff->setContent($oldContent, $newContent);
     $diff->setReducedLineNumbers();
     $diff->showDiffStyle();
     $html = $diff->getDiff($this->context->msg('tpt-diff-old')->escaped(), $this->context->msg('tpt-diff-new')->escaped());
     return array('value_old' => $oldContent->getNativeData(), 'value_new' => $newContent->getNativeData(), 'revisionid_old' => $oldrev->getId(), 'revisionid_new' => $definitionTitle->getLatestRevId(), 'language' => $this->group->getSourceLanguage(), 'html' => $html);
 }
function do_revert_by_time($num)
{
    global $mvDryRun;
    $dbr = wfGetDB(DB_READ);
    $dbw = wfGetDB(DB_WRITE);
    $sql = " SELECT *\nFROM `recentchanges`\nORDER BY `recentchanges`.`rc_timestamp` DESC\nLIMIT 0, {$num}";
    $result = $dbr->query($sql);
    //get the first last 10
    while ($rc_edit = $dbr->fetchObject($result)) {
        //if(!$mvDryRun)
        //get the -1 revision
        if ($rc_edit->rc_last_oldid != 0) {
            $rev = Revision::newFromId($rc_edit->rc_last_oldid);
            $rTitle = Title::makeTitle($rc_edit->rc_namespace, $rc_edit->rc_title);
            //$rev = Revision::newFromTitle( $title, $rc_edit->rc_this_oldid );
            $old_text = $rev->getRawText();
            print "Revert one edit on: " . $rc_edit->rc_title . "\n";
            if (!$mvDryRun) {
                do_update_wiki_page($rTitle, $old_text, MV_NS_STREAM, $force = true);
            }
        }
        //do_update_wiki_page( $streamTitle, $out, MV_NS_STREAM, $force = true );
    }
}
Esempio n. 29
0
 function execute()
 {
     if ($this->hasOption('tpl-time')) {
         $this->templateTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('tpl-time')));
         Hooks::register('BeforeParserFetchTemplateAndtitle', array($this, 'onFetchTemplate'));
     }
     $title = Title::newFromText($this->getArg());
     if (!$title) {
         $this->error("Invalid title");
         exit(1);
     }
     if ($this->hasOption('page-time')) {
         $pageTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('page-time')));
         $id = $this->getRevIdForTime($title, $pageTimestamp);
         if (!$id) {
             $this->error("The page did not exist at that time");
             exit(1);
         }
         $revision = Revision::newFromId($id);
     } else {
         $revision = Revision::newFromTitle($title);
     }
     if (!$revision) {
         $this->error("Unable to load revision, incorrect title?");
         exit(1);
     }
     if (!$this->hasOption('cold')) {
         $this->runParser($revision);
     }
     $startUsage = getrusage();
     $startTime = microtime(true);
     $this->runParser($revision);
     $endUsage = getrusage();
     $endTime = microtime(true);
     printf("CPU time = %.3f s, wall clock time = %.3f s\n", $endUsage['ru_utime.tv_sec'] + $endUsage['ru_utime.tv_usec'] * 1.0E-6 - $startUsage['ru_utime.tv_sec'] - $startUsage['ru_utime.tv_usec'] * 1.0E-6, $endTime - $startTime);
 }
Esempio n. 30
0
 /**
  * Patrols the article or provides the reason the patrol failed.
  */
 public function execute()
 {
     $params = $this->extractRequestParams();
     $this->requireOnlyOneParameter($params, 'rcid', 'revid');
     if (isset($params['rcid'])) {
         $rc = RecentChange::newFromId($params['rcid']);
         if (!$rc) {
             $this->dieUsageMsg(['nosuchrcid', $params['rcid']]);
         }
     } else {
         $rev = Revision::newFromId($params['revid']);
         if (!$rev) {
             $this->dieUsageMsg(['nosuchrevid', $params['revid']]);
         }
         $rc = $rev->getRecentChange();
         if (!$rc) {
             $this->dieUsage('The revision ' . $params['revid'] . " can't be patrolled as it's too old", 'notpatrollable');
         }
     }
     $user = $this->getUser();
     $tags = $params['tags'];
     // Check if user can add tags
     if (!is_null($tags)) {
         $ableToTag = ChangeTags::canAddTagsAccompanyingChange($tags, $user);
         if (!$ableToTag->isOK()) {
             $this->dieStatus($ableToTag);
         }
     }
     $retval = $rc->doMarkPatrolled($user, false, $tags);
     if ($retval) {
         $this->dieUsageMsg(reset($retval));
     }
     $result = ['rcid' => intval($rc->getAttribute('rc_id'))];
     ApiQueryBase::addTitleInfo($result, $rc->getTitle());
     $this->getResult()->addValue(null, $this->getModuleName(), $result);
 }