/** * Does the API request and returns the result. * * The returned value is an array containing * - the result data (array) * - the request (WebRequest) * - the session data of the request (array) * - if $appendModule is true, the Api module $module * * @param array $params * @param array|null $session * @param bool $appendModule * @param User|null $user * * @return array */ protected function doApiRequest(array $params, array $session = null, $appendModule = false, User $user = null) { global $wgRequest, $wgUser; if (is_null($session)) { // re-use existing global session by default $session = $wgRequest->getSessionArray(); } // set up global environment if ($user) { $wgUser = $user; } $wgRequest = new FauxRequest($params, true, $session); RequestContext::getMain()->setRequest($wgRequest); RequestContext::getMain()->setUser($wgUser); // set up local environment $context = $this->apiContext->newTestContext($wgRequest, $wgUser); $module = new ApiMain($context, true); // run it! $module->execute(); // construct result $results = array($module->getResult()->getResultData(null, array('Strip' => 'all')), $context->getRequest(), $context->getRequest()->getSessionArray()); if ($appendModule) { $results[] = $module; } return $results; }
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); }
public function execute() { $search = null; extract($this->ExtractRequestParams()); // Open search results may be stored for a very long time $this->getMain()->setCacheMaxAge(1200); $title = Title::newFromText($search); if (!$title) { return; } // Return empty result // Prepare nested request $params = new FauxRequest(array('action' => 'query', 'list' => 'allpages', 'apnamespace' => $title->getNamespace(), 'aplimit' => 10, 'apprefix' => $title->getDBkey())); // Execute $module = new ApiMain($params); $module->execute(); // Get resulting data $data = $module->getResultData(); // Reformat useful data for future printing by JSON engine $srchres = array(); foreach ($data['query']['allpages'] as &$pageinfo) { // Note: this data will no be printable by the xml engine // because it does not support lists of unnamed items $srchres[] = $pageinfo['title']; } // Set top level elements $result = $this->getResult(); $result->addValue(null, 0, $search); $result->addValue(null, 1, $srchres); }
/** * @return string */ private function getInputs() { global $wgEnableWriteAPI; $apiMain = new ApiMain(new FauxRequest(array()), $wgEnableWriteAPI); $this->apiQuery = new ApiQuery($apiMain, 'query'); $formats = array_filter(array_keys($apiMain->getFormats()), 'SpecialApiSandbox::filterFormats'); sort($formats); $modules = array_keys($apiMain->getModules()); sort($modules); $key = array_search('query', $modules); if ($key !== false) { array_splice($modules, $key, 1); array_unshift($modules, 'query'); } $queryModules = array_merge($this->getQueryModules('list'), $this->getQueryModules('prop'), $this->getQueryModules('meta')); $s = '<table class="api-sandbox-options"> <tbody> '; $s .= '<tr><td class="api-sandbox-label"><label for="api-sandbox-format">format=</label></td><td class="api-sandbox-value">' . self::getSelect('format', $formats, 'json') . '</td><td></td></tr> '; $s .= '<tr><td class="api-sandbox-label"><label for="api-sandbox-action">action=</label></td><td class="api-sandbox-value">' . self::getSelect('action', $modules) . '</td><td id="api-sandbox-help" rowspan="2"></td></tr> '; $s .= '<tr id="api-sandbox-query-row" style="display: none"><td class="api-sandbox-label">' . '</td><td class="api-sandbox-value">' . self::getSelect('query', $queryModules) . '</td></tr> </table> '; $s .= '<div id="api-sandbox-main-inputs"></div><div id="api-sandbox-query-inputs" style="display: none"></div>' . $this->openFieldset('generic-parameters') . '<div id="api-sandbox-generic-inputs" class="mw-collapsible mw-collapsed"></div></fieldset>' . $this->openFieldset('generator-parameters', array('style' => 'display: none;')) . '<div id="api-sandbox-generator-inputs"></div></fieldset> '; $s .= Html::element('input', array('type' => 'submit', 'id' => 'api-sandbox-submit', 'value' => wfMessage('apisb-submit')->text(), 'disabled' => 'disabled')) . "\n"; return $s; }
/** * Gets the HTML for the preview image or null if there is none. * * @since 2.3.3 * * @param string $imageName * * @return string|null */ protected static function getPreviewImage($imageName) { $previewImage = null; $imageTitle = Title::newFromText($imageName, NS_FILE); if (!is_object($imageTitle)) { return $previewImage; } $api = new ApiMain(new FauxRequest(array('action' => 'query', 'format' => 'json', 'prop' => 'imageinfo', 'iiprop' => 'url', 'titles' => $imageTitle->getFullText(), 'iiurlwidth' => 200), true), true); $api->execute(); $result = $api->getResultData(); $url = false; if (array_key_exists('query', $result) && array_key_exists('pages', $result['query'])) { foreach ($result['query']['pages'] as $page) { if (array_key_exists('imageinfo', $page)) { foreach ($page['imageinfo'] as $imageInfo) { $url = $imageInfo['thumburl']; break; } } } } if ($url !== false) { $previewImage = Html::element('img', array('src' => $url)); } return $previewImage; }
public function execute() { $this->mParams = $this->extractRequestParams(); $fauxRequest = new FauxRequest(['action' => 'query', 'list' => 'querypage', 'qppage' => 'Mostlinkedtemplates', 'qplimit' => 50, 'qpoffset' => $this->mParams['offset']]); $api = new ApiMain($fauxRequest); $api->execute(); $resultData = $api->getResultData(); $results = $resultData['query']['querypage']['results']; $templates = []; foreach ($results as $template) { $title = Title::newFromText($template['title']); if (is_object($title)) { $titleText = $title->getText(); if (strlen($titleText) > 1) { $templates[] = ['title' => $titleText, 'uses' => $template['value']]; } } } $this->getResult()->setIndexedTagName($templates, 'templates'); $this->getResult()->addValue(null, 'templates', $templates); if (isset($resultData['query-continue'])) { $queryContinue = $resultData['query-continue']['querypage']['qpoffset']; $this->getResult()->addValue(null, 'query-continue', $queryContinue); } }
public function execute() { global $wgFeedClasses, $wgSitename, $wgServer; try { $params = $this->extractRequestParams(); $fauxReqArr = array("action" => "query", "list" => "activityfeed"); $fauxReq = new FauxRequest($fauxReqArr); $module = new ApiMain($fauxReq); $module->execute(); $data = $module->getResultData(); $feedItems = array(); foreach ((array) $data["query"]["activityfeed"] as $info) { $feedItems[] = $this->createFeedItem($info); } $feed = new $wgFeedClasses[$params["feedformat"]]("{$wgSitename} - activity feed", "", $wgServer); ApiFormatFeedWrapper::setResult($this->getResult(), $feed, $feedItems); } catch (Exception $e) { $this->getMain()->setCacheMaxAge(0); $feedFormat = isset($params["feedformat"]) ? $params["feedformat"] : "rss"; $feed = new $wgFeedClasses[$feedFormat]("{$wgSitename} - error - activity feed", "", $wgServer); if ($e instanceof UsageException) { $errorCode = $e->getCodeString(); } else { $errorCode = "internal_api_error"; } $errorText = $e->getMessage(); $feedItems[] = new FeedItem("Error ({$errorCode})", $errorText, "", "", ""); ApiFormatFeedWrapper::setResult($this->getResult(), $feed, $feedItems); } }
/** @dataProvider provideTokenClasses */ public function testTokenRetrieval($id, $class) { // Make sure we have the right to get the token global $wgGroupPermissions; $wgGroupPermissions['*'][$class::getRight()] = true; RequestContext::getMain()->getUser()->clearInstanceCache(); // Reread above global // We should be getting anonymous user token $expected = $class::getToken(); $this->assertNotSame(false, $expected, 'We did not get a valid token'); $actionString = TranslateUtils::getTokenAction($id); $params = wfCgiToArray($actionString); $req = new FauxRequest($params); $api = new ApiMain($req); $api->execute(); if (defined('ApiResult::META_CONTENT')) { $data = $api->getResult()->getResultData(null, array('Strip' => 'all')); } else { $data = $api->getResultData(); } if (isset($data['query'])) { foreach ($data['query']['pages'] as $page) { $this->assertSame($expected, $page[$id . 'token']); } } else { $this->assertArrayHasKey('tokens', $data, 'Result has tokens'); $this->assertSame($expected, $data['tokens'][$id . 'token']); } }
static function saveCat($filename, $category) { global $wgContLang, $wgUser; $mediaString = strtolower($wgContLang->getNsText(NS_FILE)); $title = $mediaString . ':' . $filename; $text = "\n[[" . $category . "]]"; $wgEnableWriteAPI = true; $params = new FauxRequest(array('action' => 'edit', 'section' => 'new', 'title' => $title, 'text' => $text, 'token' => $wgUser->editToken()), true, $_SESSION); $enableWrite = true; // This is set to false by default, in the ApiMain constructor $api = new ApiMain($params, $enableWrite); $api->execute(); if (defined('ApiResult::META_CONTENT')) { $data = $api->getResult()->getResultData(); } else { $data =& $api->getResultData(); } return $mediaString; /* This code does the same and is better, but for some reason it doesn't update the categorylinks table global $wgContLang, $wgUser; $title = Title::newFromText( $filename, NS_FILE ); $page = new WikiPage( $title ); $text = $page->getText(); $text .= "\n\n[[" . $category . "]]"; $summary = wfMessage( 'msu-comment' ); $status = $page->doEditContent( $text, $summary, EDIT_UPDATE, false, $wgUser ); $value = $status->value; $revision = $value['revision']; $page->doEditUpdates( $revision, $wgUser ); return true; */ }
function execute($par) { global $wgRequest, $wgOut, $wgBoilerplatefactorydefaultpage, $wgBoilerplatefactorycategorie, $wgBoilerplatefactorynamespace; $this->setHeaders(); ### new page name $wgOut->addHTML(' <form name="boilerplatefactory" id="boilerplatefactory" class="boilerplatefactory" action="/index.php" method="get"> <input name="title" class="createboxInput" value="' . $wgBoilerplatefactorydefaultpage . '" type="text"><br>'); ### list of existing pages using as Boilerplate $params = new FauxRequest(array('action' => 'query', 'list' => 'categorymembers', 'cmlimit' => 100, 'cmtitle' => $wgBoilerplatefactorycategorie)); $api = new ApiMain($params); $api->execute(); $wgBoilerplatefactorycategories =& $api->getResultData(); foreach ($wgBoilerplatefactorycategories[query][categorymembers] as $categ) { $params = new FauxRequest(array('action' => 'query', 'list' => 'categorymembers', 'cmlimit' => 100, 'cmtitle' => $categ[title], 'cmnamespace' => $wgBoilerplatefactorynamespace)); $api = new ApiMain($params); $api->execute(); $boilerarray =& $api->getResultData(); $wgOut->addHTML("\n <div>\n <h2 class=\"{$categ['title']}\" >{$categ['title']}</h2>\n"); foreach ($boilerarray[query][categorymembers] as $boiler) { $wgOut->addHTML(" <input type='checkbox' name='blrchc[]' value='" . $boiler[title] . "' > <a href='http://" . $_SERVER[HTTP_HOST] . "/index.php?title=" . $boiler[title] . "' >" . $boiler[title] . "</a><br />\n"); } $wgOut->addHTML("</div>\n"); } ### subst check send $wgOut->addHTML(" <fieldset><legend>" . wfMsg('boilerplatefactory-setting') . "</legend>\n\n\t\t <input type='checkbox' name='blrsubst' value='' checked >" . wfMsg('boilerplatefactory-subst') . "<br />\n\t\t <input type='checkbox' name='blrnotoc' value='' >" . wfMsg('boilerplatefactory-notoc') . "<br />\n\t\t <input type='checkbox' name='blrndtscton' value='' checked >" . wfMsg('boilerplatefactory-noeditsection') . "<br />\n\t\t <input type='checkbox' name='blrnoNSh2' value='' checked >" . wfMsg('boilerplatefactory-nonamespaceh2') . "<br />\n\t\t <input name='action' value='edit' type='hidden' >\n \n\t\t <input name='create' class='createboxButton' value='" . wfMsg('boilerplatefactory-send') . "' type='submit'>\n </fieldset>\n </form>"); return true; }
public function testCrossDomainMangling() { $config = new HashConfig(array('MangleFlashPolicy' => false)); $context = new RequestContext(); $context->setConfig(new MultiConfig(array($config, $context->getConfig()))); $main = new ApiMain($context); $main->getResult()->addValue(null, null, '< Cross-Domain-Policy >'); if (!function_exists('wfOutputHandler')) { function wfOutputHandler($s) { return $s; } } $printer = $main->createPrinterByName('php'); ob_start('wfOutputHandler'); $printer->initPrinter(); $printer->execute(); $printer->closePrinter(); $ret = ob_get_clean(); $this->assertSame('a:1:{i:0;s:23:"< Cross-Domain-Policy >";}', $ret); $config->set('MangleFlashPolicy', true); $printer = $main->createPrinterByName('php'); ob_start('wfOutputHandler'); try { $printer->initPrinter(); $printer->execute(); $printer->closePrinter(); ob_end_clean(); $this->fail('Expected exception not thrown'); } catch (UsageException $ex) { ob_end_clean(); $this->assertSame('This response cannot be represented using format=php. See https://phabricator.wikimedia.org/T68776', $ex->getMessage(), 'Expected exception'); } }
/** * Get the formatter output for the given input data * @param array $params Query parameters * @param array $data Data to encode * @param string $class Printer class to use instead of the normal one * @return string * @throws Exception */ protected function encodeData(array $params, array $data, $class = null) { $context = new RequestContext(); $context->setRequest(new FauxRequest($params, true)); $main = new ApiMain($context); if ($class !== null) { $main->getModuleManager()->addModule($this->printerName, 'format', $class); } $result = $main->getResult(); $result->addArrayType(null, 'default'); foreach ($data as $k => $v) { $result->addValue(null, $k, $v); } $printer = $main->createPrinterByName($this->printerName); $printer->initPrinter(); $printer->execute(); ob_start(); try { $printer->closePrinter(); return ob_get_clean(); } catch (Exception $ex) { ob_end_clean(); throw $ex; } }
public function run() { $scope = RequestContext::importScopedSession($this->params['session']); $context = RequestContext::getMain(); try { $user = $context->getUser(); if (!$user->isLoggedIn()) { $this->setLastError("Could not load the author user from session."); return false; } if (count($_SESSION) === 0) { // Empty session probably indicates that we didn't associate // with the session correctly. Note that being able to load // the user does not necessarily mean the session was loaded. // Most likely cause by suhosin.session.encrypt = On. $this->setLastError("Error associating with user session. " . "Try setting suhosin.session.encrypt = Off"); return false; } UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Poll', 'stage' => 'publish', 'status' => Status::newGood())); $upload = new UploadFromStash($user); // @todo initialize() causes a GET, ideally we could frontload the antivirus // checks and anything else to the stash stage (which includes concatenation and // the local file is thus already there). That way, instead of GET+PUT, there could // just be a COPY operation from the stash to the public zone. $upload->initialize($this->params['filekey'], $this->params['filename']); // Check if the local file checks out (this is generally a no-op) $verification = $upload->verifyUpload(); if ($verification['status'] !== UploadBase::OK) { $status = Status::newFatal('verification-error'); $status->value = array('verification' => $verification); UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => $status)); $this->setLastError("Could not verify upload."); return false; } // Upload the stashed file to a permanent location $status = $upload->performUpload($this->params['comment'], $this->params['text'], $this->params['watch'], $user); if (!$status->isGood()) { UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => $status)); $this->setLastError($status->getWikiText()); return false; } // Build the image info array while we have the local reference handy $apiMain = new ApiMain(); // dummy object (XXX) $imageInfo = $upload->getImageInfo($apiMain->getResult()); // Cleanup any temporary local file $upload->cleanupTempFile(); // Cache the info so the user doesn't have to wait forever to get the final info UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Success', 'stage' => 'publish', 'filename' => $upload->getLocalFile()->getName(), 'imageinfo' => $imageInfo, 'status' => Status::newGood())); } catch (MWException $e) { UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => Status::newFatal('api-error-publishfailed'))); $this->setLastError(get_class($e) . ": " . $e->getText()); // To prevent potential database referential integrity issues. // See bug 32551. MWExceptionHandler::rollbackMasterChangesAndLog($e); return false; } return true; }
protected function doApiRequest(array $params, array $unused = null, $appendModule = false, User $user = null) { global $wgRequest; $req = new FauxRequest($params, true, $wgRequest->getSession()); $module = new ApiMain($req, true); $module->execute(); return array($module->getResult()->getResultData(null, array('Strip' => 'all')), $req); }
/** * Initialize/fetch the ApiMain instance for testing * @return ApiMain */ private static function getMain() { if (!self::$main) { self::$main = new ApiMain(RequestContext::getMain()); self::$main->getContext()->setLanguage('en'); } return self::$main; }
/** * Make a nested call to the API to request watchlist items in the last $hours. * Wrap the result as an RSS/Atom feed. */ public function execute() { global $wgFeedClasses, $wgFeedLimit, $wgSitename, $wgLanguageCode; try { $params = $this->extractRequestParams(); // limit to the number of hours going from now back $endTime = wfTimestamp(TS_MW, time() - intval($params['hours'] * 60 * 60)); // Prepare parameters for nested request $fauxReqArr = array('action' => 'query', 'meta' => 'siteinfo', 'siprop' => 'general', 'list' => 'watchlist', 'wlprop' => 'title|user|comment|timestamp', 'wldir' => 'older', 'wlend' => $endTime, 'wllimit' => 50 > $wgFeedLimit ? $wgFeedLimit : 50); if (!is_null($params['wlowner'])) { $fauxReqArr['wlowner'] = $params['wlowner']; } if (!is_null($params['wltoken'])) { $fauxReqArr['wltoken'] = $params['wltoken']; } // Support linking to diffs instead of article if ($params['linktodiffs']) { $this->linkToDiffs = true; $fauxReqArr['wlprop'] .= '|ids'; } // Check for 'allrev' parameter, and if found, show all revisions to each page on wl. if (!is_null($params['allrev'])) { $fauxReqArr['wlallrev'] = ''; } // Create the request $fauxReq = new FauxRequest($fauxReqArr); // Execute $module = new ApiMain($fauxReq); $module->execute(); // Get data array $data = $module->getResultData(); $feedItems = array(); foreach ((array) $data['query']['watchlist'] as $info) { $feedItems[] = $this->createFeedItem($info); } $feedTitle = $wgSitename . ' - ' . wfMsgForContent('watchlist') . ' [' . $wgLanguageCode . ']'; $feedUrl = SpecialPage::getTitleFor('Watchlist')->getFullURL(); $feed = new $wgFeedClasses[$params['feedformat']]($feedTitle, htmlspecialchars(wfMsgForContent('watchlist')), $feedUrl); ApiFormatFeedWrapper::setResult($this->getResult(), $feed, $feedItems); } catch (Exception $e) { // Error results should not be cached $this->getMain()->setCacheMaxAge(0); $feedTitle = $wgSitename . ' - Error - ' . wfMsgForContent('watchlist') . ' [' . $wgLanguageCode . ']'; $feedUrl = SpecialPage::getTitleFor('Watchlist')->getFullURL(); $feedFormat = isset($params['feedformat']) ? $params['feedformat'] : 'rss'; $feed = new $wgFeedClasses[$feedFormat]($feedTitle, htmlspecialchars(wfMsgForContent('watchlist')), $feedUrl); if ($e instanceof UsageException) { $errorCode = $e->getCodeString(); } else { // Something is seriously wrong $errorCode = 'internal_api_error'; } $errorText = $e->getMessage(); $feedItems[] = new FeedItem("Error ({$errorCode})", $errorText, '', '', ''); ApiFormatFeedWrapper::setResult($this->getResult(), $feed, $feedItems); } }
/** * Initialize/fetch the ApiMain instance for testing * @return ApiMain */ private static function getMain() { if (!self::$main) { self::$main = new ApiMain(RequestContext::getMain()); self::$main->getContext()->setLanguage('en'); self::$main->getContext()->setTitle(Title::makeTitle(NS_SPECIAL, 'Badtitle/dummy title for ApiDocumentationTest')); } return self::$main; }
public function execute() { $pageSet = $this->getPageSet(); $pages = $pageSet->getGoodTitles(); if ( !count( $pages ) ) { return true; } $pageNamespaceId = ProofreadPage::getPageNamespaceId(); $pageIds = array(); foreach ( $pages AS $pageId => $title ) { if ( $title->getNamespace() == $pageNamespaceId ) { $pageIds[] = $pageId; } } if ( !count( $pageIds ) ) { return true; } // Determine the categories defined in MediaWiki: pages $qualityCategories = $qualityText = array(); for ( $i = 0; $i < 5; $i++ ) { $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( "proofreadpage_quality{$i}_category" ) ); if ( $cat ) { $qualityCategories[$i] = $cat->getPrefixedText(); $qualityText[$i] = $cat->getText(); } } $qualityLevels = array_flip( $qualityCategories ); // <Reedy> johnduhart, it'd seem sane rather than duplicating the functionality $params = new FauxRequest(array( 'action' => 'query', 'prop' => 'categories', 'pageids' => implode( '|', $pageIds ), 'clcategories' => implode( '|', $qualityCategories ), 'cllimit' => 'max' )); $api = new ApiMain($params); $api->execute(); $data = $api->getResultData(); unset( $api ); $result = $this->getResult(); foreach ( $data['query']['pages'] as $pageid => $data) { $title = $data['categories'][0]['title']; if ( !isset( $qualityLevels[ $title ] ) ) { continue; } $pageQuality = $qualityLevels[ $title ]; $val = array( 'quality' => $pageQuality, 'quality_text' => $qualityText[ $pageQuality ] ); $result->addValue( array( 'query', 'pages', $pageid ), 'proofread', $val ); } }
/** * @param $talk Title * @param $subject string * @param $text string * @param $token string */ private function emailUser($talk, $subject, $text, $token) { global $wgRequest; $api = new ApiMain(new FauxRequest(array('action' => 'emailuser', 'target' => User::newFromName($talk->getSubjectPage()->getBaseText())->getName(), 'subject' => $subject, 'text' => $text, 'token' => $token), false, array('wsEditToken' => $wgRequest->getSessionData('wsEditToken'))), true); try { $api->execute(); } catch (DBQueryError $dbqe) { $this->setWarning('E-mail was not sent'); } }
protected function doApiRequest($params, $unused = null, $appendModule = false, $user = null) { $sessionId = session_id(); session_write_close(); $req = new FauxRequest($params, true, $_SESSION); $module = new ApiMain($req, true); $module->execute(); wfSetupSession($sessionId); return array($module->getResultData(), $req); }
/** * * @param <type> $params the array of keys and values that would have appeared in the URL if this were a normal request. See API documentation * @return <type> */ public function make_fake_request($params) { $request = new FauxRequest($params, true); $api = new ApiMain($request); // Process data & use an output buffer to capture the resutls $api->execute(); $result = $api->getResult(); $data =& $result->getData(); return $data; }
/** * Tracking code that calls ClickTracking * @param $event string the event name * @param $title Object */ private static function clickTracking($event, $title) { // check if ClickTracking API is enabled if (!self::trackingEnabled()) { return; } $params = new FauxRequest(array('action' => 'clicktracking', 'eventid' => self::trackingCodePrefix() . $event, 'token' => wfGenerateToken(), 'namespacenumber' => $title->getNamespace())); $api = new ApiMain($params, true); $api->execute(); }
public function run() { $scope = RequestContext::importScopedSession($this->params['session']); $this->addTeardownCallback(function () use(&$scope) { ScopedCallback::consume($scope); // T126450 }); $context = RequestContext::getMain(); $user = $context->getUser(); try { if (!$user->isLoggedIn()) { $this->setLastError("Could not load the author user from session."); return false; } UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Poll', 'stage' => 'publish', 'status' => Status::newGood()]); $upload = new UploadFromStash($user); // @todo initialize() causes a GET, ideally we could frontload the antivirus // checks and anything else to the stash stage (which includes concatenation and // the local file is thus already there). That way, instead of GET+PUT, there could // just be a COPY operation from the stash to the public zone. $upload->initialize($this->params['filekey'], $this->params['filename']); // Check if the local file checks out (this is generally a no-op) $verification = $upload->verifyUpload(); if ($verification['status'] !== UploadBase::OK) { $status = Status::newFatal('verification-error'); $status->value = ['verification' => $verification]; UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'publish', 'status' => $status]); $this->setLastError("Could not verify upload."); return false; } // Upload the stashed file to a permanent location $status = $upload->performUpload($this->params['comment'], $this->params['text'], $this->params['watch'], $user, isset($this->params['tags']) ? $this->params['tags'] : []); if (!$status->isGood()) { UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'publish', 'status' => $status]); $this->setLastError($status->getWikiText(false, false, 'en')); return false; } // Build the image info array while we have the local reference handy $apiMain = new ApiMain(); // dummy object (XXX) $imageInfo = $upload->getImageInfo($apiMain->getResult()); // Cleanup any temporary local file $upload->cleanupTempFile(); // Cache the info so the user doesn't have to wait forever to get the final info UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Success', 'stage' => 'publish', 'filename' => $upload->getLocalFile()->getName(), 'imageinfo' => $imageInfo, 'status' => Status::newGood()]); } catch (Exception $e) { UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'publish', 'status' => Status::newFatal('api-error-publishfailed')]); $this->setLastError(get_class($e) . ": " . $e->getMessage()); // To prevent potential database referential integrity issues. // See bug 32551. MWExceptionHandler::rollbackMasterChangesAndLog($e); return false; } return true; }
/** * Test if all classes in the main module manager exists */ public function testClassNamesInModuleManager() { global $wgAutoloadLocalClasses, $wgAutoloadClasses; // wgAutoloadLocalClasses has precedence, just like in includes/AutoLoader.php $classes = $wgAutoloadLocalClasses + $wgAutoloadClasses; $api = new ApiMain(new FauxRequest(array('action' => 'query', 'meta' => 'siteinfo'))); $modules = $api->getModuleManager()->getNamesWithClasses(); foreach ($modules as $name => $class) { $this->assertArrayHasKey($class, $classes, 'Class ' . $class . ' for api module ' . $name . ' not in autoloader (with exact case)'); } }
/** * Gets ApiContributionTracking's response in array format, for the given * $request params. * @global FauxRequest $wgRequest used to shoehorn in our own request vars. * @param <type> $request Request vars we are sending to * ApiContributionTracking. * @return array Values to be returned by ApiContributionTracking */ function getAPIResultData($request) { global $wgRequest; $request['format'] = 'xml'; $request['action'] = 'contributiontracking'; $wgRequest = new FauxRequest($request); $ctapi = new ApiMain($wgRequest, true); $ctapi->execute(); $api_response = $ctapi->getResult()->getData(); return $api_response; }
public static function removeAllNamespacePages($idNS, $nameNS) { $dbw = wfgetDB(DB_MASTER); $res = $dbw->select('page', array('page_id', 'page_title', 'page_len', 'page_latest'), array('page_namespace' => $idNS)); $sToken = RequestContext::getMain()->getUser()->getEditToken(); foreach ($res as $row) { $oParams = new DerivativeRequest(RequestContext::getMain()->getRequest(), array('action' => 'delete', 'pageid' => $row->page_id, 'reason' => wfMessage('bs-namespacemanager-deletens-deletepages', $nameNS)->text(), 'token' => $sToken), true); $api = new ApiMain($oParams, true); $api->execute(); } return true; }
/** * Test that the API will accept a FauxRequest and execute. The help action * (default) throws a UsageException. Just validate we're getting proper XML * * @expectedException UsageException */ function testApi() { $api = new ApiMain(new FauxRequest(array('action' => 'help', 'format' => 'xml'))); $api->execute(); $api->getPrinter()->setBufferResult(true); $api->printResult(false); $resp = $api->getPrinter()->getBuffer(); libxml_use_internal_errors(true); $sxe = simplexml_load_string($resp); $this->assertNotInternalType("bool", $sxe); $this->assertThat($sxe, $this->isInstanceOf("SimpleXMLElement")); }
/** * Simple wrapper for calling MW API * * @param array $params * * @return array|bool */ static function call(array $params) { wfProfileIn(__METHOD__); $res = false; try { $api = new ApiMain(new FauxRequest($params)); $api->execute(); $res = $api->getResultData(); } catch (Exception $e) { } wfProfileOut(__METHOD__); return $res; }
/** * @return string */ private function getInputs() { global $wgEnableWriteAPI; $apiMain = new ApiMain(new FauxRequest(array()), $wgEnableWriteAPI); $this->apiQuery = new ApiQuery($apiMain, 'query'); $formats = $apiMain->getModuleManager()->getNamesWithClasses('format'); $formats = array_filter(array_keys($formats), 'SpecialApiSandbox::filterFormats'); sort($formats); $formatOptions = array_combine($formats, $formats); $modules = array_keys($apiMain->getModuleManager()->getNamesWithClasses('action')); sort($modules); $key = array_search('query', $modules); if ($key !== false) { array_splice($modules, $key, 1); array_unshift($modules, 'query'); } $moduleOptions = array_combine($modules, $modules); $queryModules = array_merge($this->getQueryModules('list'), $this->getQueryModules('prop'), $this->getQueryModules('meta')); $format = $this->msg('apisb-label-format')->escaped(); $action = $this->msg('apisb-label-action')->escaped(); $doc = $this->msg('apisb-label-doc')->escaped(); $s = ' <table class="api-sandbox-options"> <tbody> <tr> <th><label for="api-sandbox-format">' . $format . '</label></th> <th><label for="api-sandbox-action">' . $action . '</label></th> <th class="api-sandbox-docs-col">' . $doc . '</th> </tr> <tr> <td>' . $this->getSelect('format', $formatOptions, 'json') . '</td> <td> ' . $this->getSelect('action', $moduleOptions) . ' <div id="api-sandbox-query-row" style="display: none;"> ' . $this->getSelect('query', $queryModules) . ' </div> </td> <td class="api-sandbox-docs-col"> <div id="api-sandbox-buttons"></div> <div dir="ltr" id="api-sandbox-help"></div> <div id="api-sandbox-examples" style="display: none;" dir="ltr" class="mw-content-ltr"></div> </td> </tr> </tbody> </table> '; $s .= '<div id="api-sandbox-main-inputs"></div>' . '<div id="api-sandbox-query-inputs" style="display: none"></div>' . $this->openFieldset('generic-parameters') . '<div id="api-sandbox-generic-inputs" class="mw-collapsible mw-collapsed"></div></fieldset>' . $this->openFieldset('generator-parameters', array('style' => 'display: none;')) . '<div id="api-sandbox-generator-inputs"></div></fieldset> '; return $s; }
public function get($limit = 10, User $user = null) { wfProfileIn(__METHOD__); global $wgUser; if (!$user instanceof User) { $user = $wgUser; } $result = array(); $params = array(); $params['action'] = 'query'; $params['list'] = 'usercontribs'; $params['ucuser'] = $user->getName(); $params['ucprop'] = 'ids|title|timestamp|flags|comment|wikiamode'; $params['uclimit'] = $limit; $api = new ApiMain(new FauxRequest($params)); $api->execute(); $res =& $api->GetResultData(); $i = -1; foreach ($res['query']['usercontribs'] as &$entry) { $titleObj = Title::newFromText($entry['title']); $result[++$i] = array('url' => $titleObj->getLocalURL(), 'title' => $titleObj->getText(), 'timestamp' => $entry['timestamp'], 'namespace' => $entry['ns'], 'type' => 'edit', 'new' => $entry['rev_parent_id'] == 0 ? '1' : '0', 'diff' => empty($entry['rev_parent_id']) ? '' : $titleObj->getLocalURL('diff=' . $entry['revid'] . '&oldid=' . $entry['rev_parent_id'])); if (MWNamespace::isTalk($entry['ns']) || in_array($entry['ns'], array(400, NS_USER, NS_TEMPLATE, NS_MEDIAWIKI))) { $title = $titleObj->getPrefixedText(); if (defined('ARTICLECOMMENT_PREFIX') && strpos($title, '/') !== false && strpos(end(explode('/', $title)), ARTICLECOMMENT_PREFIX) === 0) { $result[$i]['title'] = end(explode(':', reset(explode('/', $title, 2)), 2)); } else { $result[$i]['title'] = $title; } } if (defined('NS_BLOG_ARTICLE_TALK') && $entry['ns'] == NS_BLOG_ARTICLE_TALK) { $result[$i]['title'] = wfMsg('myhome-namespace-blog') . ':' . $result[$i]['title']; } if ($entry['ns'] == NS_FILE) { list(, $title) = explode(':', $entry['title'], 2); $title = str_replace(' ', '_', $title); $tsUnix = wfTimestamp(TS_UNIX, $entry['timestamp']); $tsMin = wfTimestamp(TS_MW, $tsUnix - 5); $tsMax = wfTimestamp(TS_MW, $tsUnix + 5); //get type of file operations $dbr = wfGetDB(DB_SLAVE); $type = $dbr->selectField(array('logging'), array('log_type'), array('log_type' => 'upload', 'log_namespace' => $entry['ns'], 'log_title' => $title, "log_timestamp BETWEEN {$tsMin} AND {$tsMax}"), __METHOD__); if ($type !== false) { $result[$i]['type'] = 'upload'; $result[$i]['diff'] = ''; } } } wfProfileOut(__METHOD__); return $result; }