/**
  * Generate service output json format
  * @param ApiResult $result
  */
 public static function generateOutput($result)
 {
     assert('$result instanceof ApiResult');
     $output = $result->convertToArray();
     echo json_encode($output);
     return;
 }
Example #2
0
 /**
  * @covers ApiErrorFormatter_BackCompat
  */
 public function testErrorFormatterBC()
 {
     $mainpagePlain = wfMessage('mainpage')->useDatabase(false)->plain();
     $parensPlain = wfMessage('parentheses', 'foobar')->useDatabase(false)->plain();
     $result = new ApiResult(8388608);
     $formatter = new ApiErrorFormatter_BackCompat($result);
     $formatter->addWarning('string', 'mainpage');
     $formatter->addError('err', 'mainpage');
     $this->assertSame(array('error' => array('code' => 'mainpage', 'info' => $mainpagePlain), 'warnings' => array('string' => array('warnings' => $mainpagePlain, ApiResult::META_CONTENT => 'warnings')), ApiResult::META_TYPE => 'assoc'), $result->getResultData(), 'Simple test');
     $result->reset();
     $formatter->addWarning('foo', 'mainpage');
     $formatter->addWarning('foo', 'mainpage');
     $formatter->addWarning('foo', array('parentheses', 'foobar'));
     $msg1 = wfMessage('mainpage');
     $formatter->addWarning('message', $msg1);
     $msg2 = new ApiMessage('mainpage', 'overriddenCode', array('overriddenData' => true));
     $formatter->addWarning('messageWithData', $msg2);
     $formatter->addError('errWithData', $msg2);
     $this->assertSame(array('error' => array('code' => 'overriddenCode', 'info' => $mainpagePlain, 'overriddenData' => true), 'warnings' => array('messageWithData' => array('warnings' => $mainpagePlain, ApiResult::META_CONTENT => 'warnings'), 'message' => array('warnings' => $mainpagePlain, ApiResult::META_CONTENT => 'warnings'), 'foo' => array('warnings' => "{$mainpagePlain}\n{$parensPlain}", ApiResult::META_CONTENT => 'warnings')), ApiResult::META_TYPE => 'assoc'), $result->getResultData(), 'Complex test');
     $result->reset();
     $status = Status::newGood();
     $status->warning('mainpage');
     $status->warning('parentheses', 'foobar');
     $status->warning($msg1);
     $status->warning($msg2);
     $status->error('mainpage');
     $status->error('parentheses', 'foobar');
     $formatter->addMessagesFromStatus('status', $status);
     $this->assertSame(array('error' => array('code' => 'parentheses', 'info' => $parensPlain), 'warnings' => array('status' => array('warnings' => "{$mainpagePlain}\n{$parensPlain}", ApiResult::META_CONTENT => 'warnings')), ApiResult::META_TYPE => 'assoc'), $result->getResultData(), 'Status test');
     $I = ApiResult::META_INDEXED_TAG_NAME;
     $this->assertSame(array(array('type' => 'error', 'message' => 'mainpage', 'params' => array($I => 'param')), array('type' => 'error', 'message' => 'parentheses', 'params' => array('foobar', $I => 'param')), $I => 'error'), $formatter->arrayFromStatus($status, 'error'), 'arrayFromStatus test for error');
     $this->assertSame(array(array('type' => 'warning', 'message' => 'mainpage', 'params' => array($I => 'param')), array('type' => 'warning', 'message' => 'parentheses', 'params' => array('foobar', $I => 'param')), array('message' => 'mainpage', 'params' => array($I => 'param'), 'type' => 'warning'), array('message' => 'mainpage', 'params' => array($I => 'param'), 'type' => 'warning'), $I => 'warning'), $formatter->arrayFromStatus($status, 'warning'), 'arrayFromStatus test for warning');
 }
Example #3
0
 /**
  * Generate service output json format
  * @param ApiResult $result
  */
 public static function generateOutput($result)
 {
     assert('$result instanceof ApiResult');
     $data = $result->convertToArray();
     $xml = Array2XML::createXML('zurmoMessage', $data);
     echo $xml->saveXML();
     return;
 }
 /**
  * Add page properties to an ApiResult, adding a continue
  * parameter if it doesn't fit.
  *
  * @param ApiResult $result
  * @param int $page
  * @param array $props
  * @return bool True if it fits in the result
  */
 private function addPageProps($result, $page, $props)
 {
     ApiResult::setArrayType($props, 'assoc');
     $fit = $result->addValue(['query', 'pages', $page], 'pageprops', $props);
     if (!$fit) {
         $this->setContinueEnumParameter('continue', $page);
     }
     return $fit;
 }
Example #5
0
 /**
  * @dataProvider provideRedirectMergePolicy
  */
 public function testRedirectMergePolicyWithApiResult($mergePolicy, $expect)
 {
     list($target, $pageSet) = $this->createPageSetWithRedirect();
     $pageSet->setRedirectMergePolicy($mergePolicy);
     $result = new ApiResult(false);
     $result->addValue(null, 'pages', [$target->getArticleID() => []]);
     $pageSet->populateGeneratorData($result, ['pages']);
     $this->assertEquals($expect, $result->getResultData(['pages', $target->getArticleID()]));
 }
 /**
  * Call this method to initialize output data. See execute()
  * @param ApiResult $result
  * @param object $feed An instance of one of the $wgFeedClasses classes
  * @param array $feedItems Array of FeedItem objects
  */
 public static function setResult($result, $feed, $feedItems)
 {
     // Store output in the Result data.
     // This way we can check during execution if any error has occurred
     // Disable size checking for this because we can't continue
     // cleanly; size checking would cause more problems than it'd
     // solve
     $result->addValue(null, '_feed', $feed, ApiResult::NO_VALIDATE);
     $result->addValue(null, '_feeditems', $feedItems, ApiResult::NO_VALIDATE);
 }
Example #7
0
 public function execute()
 {
     $prop = null;
     extract($this->extractRequestParams());
     foreach ($prop as $p) {
         switch ($p) {
             case 'general':
                 global $wgSitename, $wgVersion, $wgCapitalLinks;
                 $data = array();
                 $mainPage = Title::newFromText(wfMsgForContent('mainpage'));
                 $data['mainpage'] = $mainPage->getText();
                 $data['base'] = $mainPage->getFullUrl();
                 $data['sitename'] = $wgSitename;
                 $data['generator'] = "MediaWiki {$wgVersion}";
                 $data['case'] = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
                 // 'case-insensitive' option is reserved for future
                 $this->getResult()->addValue('query', $p, $data);
                 break;
             case 'namespaces':
                 global $wgContLang;
                 $data = array();
                 foreach ($wgContLang->getFormattedNamespaces() as $ns => $title) {
                     $data[$ns] = array('id' => $ns);
                     ApiResult::setContent($data[$ns], $title);
                 }
                 ApiResult::setIndexedTagName($data, 'ns');
                 $this->getResult()->addValue('query', $p, $data);
                 break;
             default:
                 ApiBase::dieDebug(__METHOD__, "Unknown prop={$p}");
         }
     }
 }
 public function execute()
 {
     if (!$this->hasAnyRoutes()) {
         $this->dieUsage('No password reset routes are available.', 'moduledisabled');
     }
     $params = $this->extractRequestParams() + ['user' => null, 'email' => null];
     $this->requireOnlyOneParameter($params, 'user', 'email');
     $passwordReset = new PasswordReset($this->getConfig(), AuthManager::singleton());
     $status = $passwordReset->isAllowed($this->getUser(), $params['capture']);
     if (!$status->isOK()) {
         $this->dieStatus(Status::wrap($status));
     }
     $status = $passwordReset->execute($this->getUser(), $params['user'], $params['email'], $params['capture']);
     if (!$status->isOK()) {
         $status->value = null;
         $this->dieStatus(Status::wrap($status));
     }
     $result = $this->getResult();
     $result->addValue(['resetpassword'], 'status', 'success');
     if ($params['capture']) {
         $passwords = $status->getValue() ?: [];
         ApiResult::setArrayType($passwords, 'kvp', 'user');
         ApiResult::setIndexedTagName($passwords, 'p');
         $result->addValue(['resetpassword'], 'passwords', $passwords);
     }
 }
 public function execute()
 {
     $this->addFields(array('ll_from', 'll_lang', 'll_title'));
     $this->addTables('langlinks');
     $this->addWhereFld('ll_from', array_keys($this->getPageSet()->getGoodTitles()));
     $this->addOption('ORDER BY', "ll_from, ll_lang");
     $res = $this->select(__METHOD__);
     $data = array();
     $lastId = 0;
     // database has no ID 0
     $db = $this->getDB();
     while ($row = $db->fetchObject($res)) {
         if ($lastId != $row->ll_from) {
             if ($lastId != 0) {
                 $this->addPageSubItems($lastId, $data);
                 $data = array();
             }
             $lastId = $row->ll_from;
         }
         $entry = array('lang' => $row->ll_lang);
         ApiResult::setContent($entry, $row->ll_title);
         $data[] = $entry;
     }
     if ($lastId != 0) {
         $this->addPageSubItems($lastId, $data);
     }
     $db->freeResult($res);
 }
 /**
  * If the type is requested in parameters, adds a section to res with module info.
  * @param array $params user parameters array
  * @param string $type parameter name
  * @param array $res store results in this array
  * @param ApiResult $resultObj results object to set indexed tag.
  */
 private function addModulesInfo($params, $type, &$res, $resultObj)
 {
     if (!is_array($params[$type])) {
         return;
     }
     $isQuery = $type === 'querymodules';
     if ($isQuery) {
         $mgr = $this->queryObj->getModuleManager();
     } else {
         $mgr = $this->getMain()->getModuleManager();
     }
     $res[$type] = array();
     foreach ($params[$type] as $mod) {
         if (!$mgr->isDefined($mod)) {
             $res[$type][] = array('name' => $mod, 'missing' => '');
             continue;
         }
         $obj = $mgr->getModule($mod);
         $item = $this->getClassInfo($obj);
         $item['name'] = $mod;
         if ($isQuery) {
             $item['querytype'] = $mgr->getModuleGroup($mod);
         }
         $res[$type][] = $item;
     }
     $resultObj->setIndexedTagName($res[$type], 'module');
 }
 /**
  * main function
  */
 public function execute()
 {
     #--- blank variables
     $wikia = $group = $variable = null;
     extract($this->extractRequestParams());
     #--- database instance
     $db =& $this->getDB();
     $db->selectDB('wikicities');
     list($tbl_cvg, $tbl_cvp, $tbl_cv) = $db->tableNamesN("city_variables_groups", "city_variables_pool", "city_variables");
     if (!is_null($wikia)) {
         $this->addTables("{$tbl_cvp} JOIN {$tbl_cvg} ON cv_variable_group = cv_group_id JOIN {$tbl_cv} ON cv_id = cv_variable_id");
         $this->addFields(array("cv_group_id", "cv_group_name"));
         $this->addWhereFld("cv_city_id", $wikia);
         if (!is_null($wikia)) {
             $this->addWhereFld("cv_id", $variable);
         }
     } else {
         $this->addTables("{$tbl_cvg}");
         $this->addFields(array("cv_group_id", "cv_group_name"));
     }
     $data = array();
     $res = $this->select(__METHOD__);
     while ($row = $db->fetchObject($res)) {
         $data[$row->cv_group_id] = array("id" => $row->cv_group_id, "name" => $row->cv_group_name);
         ApiResult::setContent($data[$row->cv_group_id], $row->cv_group_name);
     }
     $db->freeResult($res);
     $this->getResult()->setIndexedTagName($data, 'item');
     $this->getResult()->addValue('query', $this->getModuleName(), $data);
 }
Example #12
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $modules = array();
     foreach ($params['modules'] as $path) {
         $modules[] = $this->getModuleFromPath($path);
     }
     // Get the help
     $context = new DerivativeContext($this->getMain()->getContext());
     $context->setSkin(SkinFactory::getDefaultInstance()->makeSkin('apioutput'));
     $context->setLanguage($this->getMain()->getLanguage());
     $context->setTitle(SpecialPage::getTitleFor('ApiHelp'));
     $out = new OutputPage($context);
     $out->setCopyrightUrl('https://www.mediawiki.org/wiki/Special:MyLanguage/Copyright');
     $context->setOutput($out);
     self::getHelp($context, $modules, $params);
     // Grab the output from the skin
     ob_start();
     $context->getOutput()->output();
     $html = ob_get_clean();
     $result = $this->getResult();
     if ($params['wrap']) {
         $data = array('mime' => 'text/html', 'help' => $html);
         ApiResult::setSubelementsList($data, 'help');
         $result->addValue(null, $this->getModuleName(), $data);
     } else {
         $result->reset();
         $result->addValue(null, 'text', $html, ApiResult::NO_SIZE_CHECK);
         $result->addValue(null, 'mime', 'text/html', ApiResult::NO_SIZE_CHECK);
     }
 }
 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);
 }
Example #14
0
 public function execute()
 {
     $this->addFields(array('el_from', 'el_to'));
     $this->addTables('externallinks');
     $this->addWhereFld('el_from', array_keys($this->getPageSet()->getGoodTitles()));
     $db = $this->getDB();
     $res = $this->select(__METHOD__);
     $data = array();
     $lastId = 0;
     // database has no ID 0
     while ($row = $db->fetchObject($res)) {
         if ($lastId != $row->el_from) {
             if ($lastId != 0) {
                 $this->addPageSubItems($lastId, $data);
                 $data = array();
             }
             $lastId = $row->el_from;
         }
         $entry = array();
         ApiResult::setContent($entry, $row->el_to);
         $data[] = $entry;
     }
     if ($lastId != 0) {
         $this->addPageSubItems($lastId, $data);
     }
     $db->freeResult($res);
 }
 private function doTag($tagName, $hitcount)
 {
     static $count = 0;
     static $doneTags = array();
     if (in_array($tagName, $doneTags)) {
         return true;
     }
     if (++$count > $this->limit) {
         $this->setContinueEnumParameter('continue', $tagName);
         return false;
     }
     $tag = array();
     $tag['name'] = $tagName;
     if ($this->fld_displayname) {
         $tag['displayname'] = ChangeTags::tagDescription($tagName);
     }
     if ($this->fld_description) {
         $msg = wfMessage("tag-{$tagName}-description");
         $tag['description'] = $msg->exists() ? $msg->text() : '';
     }
     if ($this->fld_hitcount) {
         $tag['hitcount'] = $hitcount;
     }
     $doneTags[] = $tagName;
     $fit = $this->result->addValue(array('query', $this->getModuleName()), null, $tag);
     if (!$fit) {
         $this->setContinueEnumParameter('continue', $tagName);
         return false;
     }
     return true;
 }
 public function execute()
 {
     global $wgUser;
     // Before doing anything at all, let's check permissions
     if (!$wgUser->isAllowed('codereview-use')) {
         $this->dieUsage('You don\'t have permission to view code paths', 'permissiondenied');
     }
     $params = $this->extractRequestParams();
     $repo = CodeRepository::newFromName($params['repo']);
     if (!$repo instanceof CodeRepository) {
         $this->dieUsage("Invalid repo ``{$params['repo']}''", 'invalidrepo');
     }
     $this->addTables('code_paths');
     $this->addFields('DISTINCT cp_path');
     $this->addWhere(array('cp_repo_id' => $repo->getId()));
     $db = $this->getDB();
     $this->addWhere('cp_path ' . $db->buildLike($params['path'], $db->anyString()));
     $this->addOption('USE INDEX', 'repo_path');
     $this->addOption('LIMIT', 10);
     $res = $this->select(__METHOD__);
     $result = $this->getResult();
     $data = array();
     foreach ($res as $row) {
         $item = array();
         ApiResult::setContent($item, $row->cp_path);
         $data[] = $item;
     }
     $result->setIndexedTagName($data, 'paths');
     $result->addValue('query', $this->getModuleName(), $data);
 }
Example #17
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']);
     $de = new DifferenceEngine($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');
     } else {
         ApiResult::setContent($vals, $difftext);
     }
     $this->getResult()->addValue(null, $this->getModuleName(), $vals);
 }
 public function execute()
 {
     if ($this->getPageSet()->getGoodTitleCount() == 0) {
         return;
     }
     $params = $this->extractRequestParams();
     $this->addFields(array('el_from', 'el_to'));
     $this->addTables('externallinks');
     $this->addWhereFld('el_from', array_keys($this->getPageSet()->getGoodTitles()));
     // Don't order by el_from if it's constant in the WHERE clause
     if (count($this->getPageSet()->getGoodTitles()) != 1) {
         $this->addOption('ORDER BY', 'el_from');
     }
     $this->addOption('LIMIT', $params['limit'] + 1);
     if (!is_null($params['offset'])) {
         $this->addOption('OFFSET', $params['offset']);
     }
     $res = $this->select(__METHOD__);
     $count = 0;
     foreach ($res as $row) {
         if (++$count > $params['limit']) {
             // We've reached the one extra which shows that
             // there are additional pages to be had. Stop here...
             $this->setContinueEnumParameter('offset', @$params['offset'] + $params['limit']);
             break;
         }
         $entry = array();
         ApiResult::setContent($entry, $row->el_to);
         $fit = $this->addPageSubItem($row->el_from, $entry);
         if (!$fit) {
             $this->setContinueEnumParameter('offset', @$params['offset'] + $count - 1);
             break;
         }
     }
 }
Example #19
0
 /**
  * Purges the cache of a page
  */
 public function execute()
 {
     $params = $this->extractRequestParams();
     $continuationManager = new ApiContinuationManager($this, array(), array());
     $this->setContinuationManager($continuationManager);
     $forceLinkUpdate = $params['forcelinkupdate'];
     $forceRecursiveLinkUpdate = $params['forcerecursivelinkupdate'];
     $pageSet = $this->getPageSet();
     $pageSet->execute();
     $result = $pageSet->getInvalidTitlesAndRevisions();
     foreach ($pageSet->getGoodTitles() as $title) {
         $r = array();
         ApiQueryBase::addTitleInfo($r, $title);
         $page = WikiPage::factory($title);
         $page->doPurge();
         // Directly purge and skip the UI part of purge().
         $r['purged'] = true;
         if ($forceLinkUpdate || $forceRecursiveLinkUpdate) {
             if (!$this->getUser()->pingLimiter('linkpurge')) {
                 $popts = $page->makeParserOptions('canonical');
                 # Parse content; note that HTML generation is only needed if we want to cache the result.
                 $content = $page->getContent(Revision::RAW);
                 $enableParserCache = $this->getConfig()->get('EnableParserCache');
                 $p_result = $content->getParserOutput($title, $page->getLatest(), $popts, $enableParserCache);
                 # Update the links tables
                 $updates = $content->getSecondaryDataUpdates($title, null, $forceRecursiveLinkUpdate, $p_result);
                 DataUpdate::runUpdates($updates);
                 $r['linkupdate'] = true;
                 if ($enableParserCache) {
                     $pcache = ParserCache::singleton();
                     $pcache->save($p_result, $page, $popts);
                 }
             } else {
                 $error = $this->parseMsg(array('actionthrottledtext'));
                 $this->setWarning($error['info']);
                 $forceLinkUpdate = false;
             }
         }
         $result[] = $r;
     }
     $apiResult = $this->getResult();
     ApiResult::setIndexedTagName($result, 'page');
     $apiResult->addValue(null, $this->getModuleName(), $result);
     $values = $pageSet->getNormalizedTitlesAsResult($apiResult);
     if ($values) {
         $apiResult->addValue(null, 'normalized', $values);
     }
     $values = $pageSet->getConvertedTitlesAsResult($apiResult);
     if ($values) {
         $apiResult->addValue(null, 'converted', $values);
     }
     $values = $pageSet->getRedirectTitlesAsResult($apiResult);
     if ($values) {
         $apiResult->addValue(null, 'redirects', $values);
     }
     $this->setContinuationManager(null);
     $continuationManager->setContinuationIntoResult($apiResult);
 }
Example #20
0
 public static function getFromValue($value)
 {
     $output = null;
     if (ApiResult::success()->getValue() == $value) {
         $output = ApiResult::success();
     } elseif (ApiResult::error()->getValue() == $value) {
         $output = ApiResult::error();
     }
     return $output;
 }
 /**
  * @covers MWDebug::appendDebugInfoToApiResult
  */
 public function testAppendDebugInfoToApiResultXmlFormat()
 {
     $request = $this->newApiRequest(array('action' => 'help', 'format' => 'xml'), '/api.php?action=help&format=xml');
     $context = new RequestContext();
     $context->setRequest($request);
     $apiMain = new ApiMain($context);
     $result = new ApiResult($apiMain);
     $result->setRawMode(true);
     MWDebug::appendDebugInfoToApiResult($context, $result);
     $this->assertInstanceOf('ApiResult', $result);
     $data = $result->getData();
     $expectedKeys = array('mwVersion', 'phpEngine', 'phpVersion', 'gitRevision', 'gitBranch', 'gitViewUrl', 'time', 'log', 'debugLog', 'queries', 'request', 'memory', 'memoryPeak', 'includes', 'profile', '_element');
     foreach ($expectedKeys as $expectedKey) {
         $this->assertArrayHasKey($expectedKey, $data['debuginfo'], "debuginfo has {$expectedKey}");
     }
     $xml = ApiFormatXml::recXmlPrint('help', $data);
     // exception not thrown
     $this->assertInternalType('string', $xml);
 }
Example #22
0
 public function execute()
 {
     if ($this->getPageSet()->getGoodTitleCount() == 0) {
         return;
     }
     $params = $this->extractRequestParams();
     $this->addFields(array('ll_from', 'll_lang', 'll_title'));
     $this->addTables('langlinks');
     $this->addWhereFld('ll_from', array_keys($this->getPageSet()->getGoodTitles()));
     if (!is_null($params['continue'])) {
         $cont = explode('|', $params['continue']);
         if (count($cont) != 2) {
             $this->dieUsage("Invalid continue param. You should pass the " . "original value returned by the previous query", "_badcontinue");
         }
         $llfrom = intval($cont[0]);
         $lllang = $this->getDB()->strencode($cont[1]);
         $this->addWhere("ll_from > {$llfrom} OR " . "(ll_from = {$llfrom} AND " . "ll_lang >= '{$lllang}')");
     }
     # Don't order by ll_from if it's constant in the WHERE clause
     if (count($this->getPageSet()->getGoodTitles()) == 1) {
         $this->addOption('ORDER BY', 'll_lang');
     } else {
         $this->addOption('ORDER BY', 'll_from, ll_lang');
     }
     $this->addOption('LIMIT', $params['limit'] + 1);
     $res = $this->select(__METHOD__);
     $data = array();
     $lastId = 0;
     // database has no ID 0
     $count = 0;
     $db = $this->getDB();
     while ($row = $db->fetchObject($res)) {
         if (++$count > $params['limit']) {
             // We've reached the one extra which shows that
             // there are additional pages to be had. Stop here...
             $this->setContinueEnumParameter('continue', "{$row->ll_from}|{$row->ll_lang}");
             break;
         }
         if ($lastId != $row->ll_from) {
             if ($lastId != 0) {
                 $this->addPageSubItems($lastId, $data);
                 $data = array();
             }
             $lastId = $row->ll_from;
         }
         $entry = array('lang' => $row->ll_lang);
         ApiResult::setContent($entry, $row->ll_title);
         $data[] = $entry;
     }
     if ($lastId != 0) {
         $this->addPageSubItems($lastId, $data);
     }
     $db->freeResult($res);
 }
 public function execute()
 {
     if ($this->getPageSet()->getGoodTitleCount() == 0) {
         return;
     }
     $params = $this->extractRequestParams();
     $query = $params['query'];
     $protocol = ApiQueryExtLinksUsage::getProtocolPrefix($params['protocol']);
     $this->addFields(array('el_from', 'el_to'));
     $this->addTables('externallinks');
     $this->addWhereFld('el_from', array_keys($this->getPageSet()->getGoodTitles()));
     $whereQuery = $this->prepareUrlQuerySearchString($query, $protocol);
     if ($whereQuery !== null) {
         $this->addWhere($whereQuery);
     }
     // Don't order by el_from if it's constant in the WHERE clause
     if (count($this->getPageSet()->getGoodTitles()) != 1) {
         $this->addOption('ORDER BY', 'el_from');
     }
     // If we're querying all protocols, use DISTINCT to avoid repeating protocol-relative links twice
     if ($protocol === null) {
         $this->addOption('DISTINCT');
     }
     $this->addOption('LIMIT', $params['limit'] + 1);
     $offset = isset($params['offset']) ? $params['offset'] : 0;
     if ($offset) {
         $this->addOption('OFFSET', $params['offset']);
     }
     $res = $this->select(__METHOD__);
     $count = 0;
     foreach ($res as $row) {
         if (++$count > $params['limit']) {
             // We've reached the one extra which shows that
             // there are additional pages to be had. Stop here...
             $this->setContinueEnumParameter('offset', $offset + $params['limit']);
             break;
         }
         $entry = array();
         $to = $row->el_to;
         // expand protocol-relative urls
         if ($params['expandurl']) {
             $to = wfExpandUrl($to, PROTO_CANONICAL);
         }
         ApiResult::setContent($entry, $to);
         $fit = $this->addPageSubItem($row->el_from, $entry);
         if (!$fit) {
             $this->setContinueEnumParameter('offset', $offset + $count - 1);
             break;
         }
     }
 }
Example #24
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $user = $this->getUrUser($params);
     $form = $this->getUserRightsPage();
     $form->setContext($this->getContext());
     $r['user'] = $user->getName();
     $r['userid'] = $user->getId();
     list($r['added'], $r['removed']) = $form->doSaveUserGroups($user, (array) $params['add'], (array) $params['remove'], $params['reason']);
     $result = $this->getResult();
     ApiResult::setIndexedTagName($r['added'], 'group');
     ApiResult::setIndexedTagName($r['removed'], 'group');
     $result->addValue(null, $this->getModuleName(), $r);
 }
Example #25
0
 public function execute()
 {
     if ($this->getPageSet()->getGoodTitleCount() == 0) {
         return;
     }
     $params = $this->extractRequestParams();
     $this->addFields(array('iwl_from', 'iwl_prefix', 'iwl_title'));
     $this->addTables('iwlinks');
     $this->addWhereFld('iwl_from', array_keys($this->getPageSet()->getGoodTitles()));
     if (!is_null($params['continue'])) {
         $cont = explode('|', $params['continue']);
         if (count($cont) != 3) {
             $this->dieUsage('Invalid continue param. You should pass the ' . 'original value returned by the previous query', '_badcontinue');
         }
         $iwlfrom = intval($cont[0]);
         $iwlprefix = $this->getDB()->strencode($cont[1]);
         $iwltitle = $this->getDB()->strencode($this->titleToKey($cont[2]));
         $this->addWhere("iwl_from > {$iwlfrom} OR " . "(iwl_from = {$iwlfrom} AND " . "(iwl_prefix > '{$iwlprefix}' OR " . "(iwl_prefix = '{$iwlprefix}' AND " . "iwl_title >= '{$iwltitle}')))");
     }
     // Don't order by iwl_from if it's constant in the WHERE clause
     if (count($this->getPageSet()->getGoodTitles()) == 1) {
         $this->addOption('ORDER BY', 'iwl_prefix');
     } else {
         $this->addOption('ORDER BY', 'iwl_from, iwl_prefix');
     }
     $this->addOption('LIMIT', $params['limit'] + 1);
     $res = $this->select(__METHOD__);
     $count = 0;
     foreach ($res as $row) {
         if (++$count > $params['limit']) {
             // We've reached the one extra which shows that
             // there are additional pages to be had. Stop here...
             $this->setContinueEnumParameter('continue', "{$row->iwl_from}|{$row->iwl_prefix}|{$row->iwl_title}");
             break;
         }
         $entry = array('prefix' => $row->iwl_prefix);
         if (!is_null($params['url'])) {
             $title = Title::newFromText("{$row->iwl_prefix}:{$row->iwl_title}");
             if ($title) {
                 $entry['url'] = $title->getFullURL();
             }
         }
         ApiResult::setContent($entry, $row->iwl_title);
         $fit = $this->addPageSubItem($row->iwl_from, $entry);
         if (!$fit) {
             $this->setContinueEnumParameter('continue', "{$row->iwl_from}|{$row->iwl_prefix}|{$row->iwl_title}");
             break;
         }
     }
 }
 /**
  * @param Title $title
  * @param string $submodule
  * @param array $request
  * @param bool $requiredBlock
  * @return array
  * @throws MWException
  */
 public function flowApi(Title $title, $submodule, array $request, $requiredBlock = false)
 {
     $request = new FauxRequest($request + array('action' => 'flow', 'submodule' => $submodule, 'page' => $title->getPrefixedText()));
     $api = new ApiMain($request);
     $api->execute();
     $flowData = $api->getResult()->getResultData(array('flow', $submodule, 'result'));
     if ($flowData === null) {
         throw new MWException("API response has no Flow data");
     }
     $flowData = ApiResult::stripMetadata($flowData);
     if ($requiredBlock !== false && !isset($flowData[$requiredBlock])) {
         throw new MWException("No {$requiredBlock} block in API response");
     }
     return $flowData;
 }
Example #27
0
 public function execute()
 {
     $user = $this->getUser();
     if (!$user->isLoggedIn()) {
         $this->dieUsage('You must be logged-in to have a watchlist', 'notloggedin');
     }
     if (!$user->isAllowed('editmywatchlist')) {
         $this->dieUsage('You don\'t have permission to edit your watchlist', 'permissiondenied');
     }
     $params = $this->extractRequestParams();
     $continuationManager = new ApiContinuationManager($this, array(), array());
     $this->setContinuationManager($continuationManager);
     $pageSet = $this->getPageSet();
     // by default we use pageset to extract the page to work on.
     // title is still supported for backward compatibility
     if (!isset($params['title'])) {
         $pageSet->execute();
         $res = $pageSet->getInvalidTitlesAndRevisions(array('invalidTitles', 'special', 'missingIds', 'missingRevIds', 'interwikiTitles'));
         foreach ($pageSet->getMissingTitles() as $title) {
             $r = $this->watchTitle($title, $user, $params);
             $r['missing'] = 1;
             $res[] = $r;
         }
         foreach ($pageSet->getGoodTitles() as $title) {
             $r = $this->watchTitle($title, $user, $params);
             $res[] = $r;
         }
         ApiResult::setIndexedTagName($res, 'w');
     } else {
         // dont allow use of old title parameter with new pageset parameters.
         $extraParams = array_keys(array_filter($pageSet->extractRequestParams(), function ($x) {
             return $x !== null && $x !== false;
         }));
         if ($extraParams) {
             $p = $this->getModulePrefix();
             $this->dieUsage("The parameter {$p}title can not be used with " . implode(", ", $extraParams), 'invalidparammix');
         }
         $this->logFeatureUsage('action=watch&title');
         $title = Title::newFromText($params['title']);
         if (!$title || !$title->isWatchable()) {
             $this->dieUsageMsg(array('invalidtitle', $params['title']));
         }
         $res = $this->watchTitle($title, $user, $params, true);
     }
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
     $this->setContinuationManager(null);
     $continuationManager->setContinuationIntoResult($this->getResult());
 }
Example #28
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $props = array_flip($params['prop']);
     $repos = array();
     $repoGroup = $this->getInitialisedRepoGroup();
     $repoGroup->forEachForeignRepo(function ($repo) use(&$repos, $props) {
         $repos[] = array_intersect_key($repo->getInfo(), $props);
     });
     $repos[] = array_intersect_key($repoGroup->getLocalRepo()->getInfo(), $props);
     $result = $this->getResult();
     ApiResult::setIndexedTagName($repos, 'repo');
     ApiResult::setArrayTypeRecursive($repos, 'assoc');
     ApiResult::setArrayType($repos, 'array');
     $result->addValue(array('query'), 'repos', $repos);
 }
 public function execute()
 {
     if ($this->getPageSet()->getGoodTitleCount() == 0) {
         return;
     }
     $params = $this->extractRequestParams();
     $this->addFields(array('el_from', 'el_to'));
     $this->addTables('externallinks');
     $this->addWhereFld('el_from', array_keys($this->getPageSet()->getGoodTitles()));
     # Don't order by el_from if it's constant in the WHERE clause
     if (count($this->getPageSet()->getGoodTitles()) != 1) {
         $this->addOption('ORDER BY', 'el_from');
     }
     $this->addOption('LIMIT', $params['limit'] + 1);
     if (!is_null($params['offset'])) {
         $this->addOption('OFFSET', $params['offset']);
     }
     $db = $this->getDB();
     $res = $this->select(__METHOD__);
     $data = array();
     $lastId = 0;
     // database has no ID 0
     $count = 0;
     while ($row = $db->fetchObject($res)) {
         if (++$count > $params['limit']) {
             // We've reached the one extra which shows that
             // there are additional pages to be had. Stop here...
             $this->setContinueEnumParameter('offset', @$params['offset'] + $params['limit']);
             break;
         }
         if ($lastId != $row->el_from) {
             if ($lastId != 0) {
                 $this->addPageSubItems($lastId, $data);
                 $data = array();
             }
             $lastId = $row->el_from;
         }
         $entry = array();
         ApiResult::setContent($entry, $row->el_to);
         $data[] = $entry;
     }
     if ($lastId != 0) {
         $this->addPageSubItems($lastId, $data);
     }
     $db->freeResult($res);
 }
Example #30
0
 public function execute()
 {
     $this->useTransactionalTimeLimit();
     $user = $this->getUser();
     $params = $this->extractRequestParams();
     $this->requireMaxOneParameter($params, 'namespace', 'rootpage');
     $isUpload = false;
     if (isset($params['interwikisource'])) {
         if (!$user->isAllowed('import')) {
             $this->dieUsageMsg('cantimport');
         }
         if (!isset($params['interwikipage'])) {
             $this->dieUsageMsg(array('missingparam', 'interwikipage'));
         }
         $source = ImportStreamSource::newFromInterwiki($params['interwikisource'], $params['interwikipage'], $params['fullhistory'], $params['templates']);
     } else {
         $isUpload = true;
         if (!$user->isAllowed('importupload')) {
             $this->dieUsageMsg('cantimport-upload');
         }
         $source = ImportStreamSource::newFromUpload('xml');
     }
     if (!$source->isOK()) {
         $this->dieStatus($source);
     }
     $importer = new WikiImporter($source->value, $this->getConfig());
     if (isset($params['namespace'])) {
         $importer->setTargetNamespace($params['namespace']);
     } elseif (isset($params['rootpage'])) {
         $statusRootPage = $importer->setTargetRootPage($params['rootpage']);
         if (!$statusRootPage->isGood()) {
             $this->dieStatus($statusRootPage);
         }
     }
     $reporter = new ApiImportReporter($importer, $isUpload, $params['interwikisource'], $params['summary']);
     try {
         $importer->doImport();
     } catch (Exception $e) {
         $this->dieUsageMsg(array('import-unknownerror', $e->getMessage()));
     }
     $resultData = $reporter->getData();
     $result = $this->getResult();
     ApiResult::setIndexedTagName($resultData, 'page');
     $result->addValue(null, $this->getModuleName(), $resultData);
 }