当前位置: 首页>>代码示例>>PHP>>正文


PHP ApiMain类代码示例

本文整理汇总了PHP中ApiMain的典型用法代码示例。如果您正苦于以下问题:PHP ApiMain类的具体用法?PHP ApiMain怎么用?PHP ApiMain使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ApiMain类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: doApiRequest

 /**
  * 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;
 }
开发者ID:lourinaldi,项目名称:mediawiki,代码行数:42,代码来源:ApiTestCase.php

示例2: parseWikitext

 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);
 }
开发者ID:sammykumar,项目名称:TheVRForums,代码行数:27,代码来源:ApiVisualEditorEdit.php

示例3: execute

 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);
 }
开发者ID:negabaro,项目名称:alfresco,代码行数:30,代码来源:ApiOpenSearch.php

示例4: getInputs

    /**
     * @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;
    }
开发者ID:realsoc,项目名称:mediawiki-extensions,代码行数:33,代码来源:SpecialApiSandbox.php

示例5: getPreviewImage

 /**
  * 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;
 }
开发者ID:whysasse,项目名称:kmwiki,代码行数:35,代码来源:SF_TextInput.php

示例6: execute

 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);
     }
 }
开发者ID:Tjorriemorrie,项目名称:app,代码行数:25,代码来源:ApiTemplateSuggestions.php

示例7: execute

 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);
     }
 }
开发者ID:Tjorriemorrie,项目名称:app,代码行数:30,代码来源:ApiFeedActivityFeed.php

示例8: testTokenRetrieval

 /** @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']);
     }
 }
开发者ID:HuijiWiki,项目名称:mediawiki-extensions-Translate,代码行数:30,代码来源:ApiTokensTest.php

示例9: saveCat

 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;
     */
 }
开发者ID:Reasno,项目名称:MsUpload,代码行数:32,代码来源:MsUpload.body.php

示例10: execute

    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;
    }
开发者ID:klml,项目名称:Boilerplatefactory,代码行数:27,代码来源:Boilerplatefactory_body.php

示例11: testCrossDomainMangling

 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');
     }
 }
开发者ID:ngertrudiz,项目名称:mediawiki,代码行数:34,代码来源:ApiFormatPhpTest.php

示例12: encodeData

 /**
  * 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;
     }
 }
开发者ID:MediaWiki-stable,项目名称:1.26.1,代码行数:33,代码来源:ApiFormatTestBase.php

示例13: run

 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;
 }
开发者ID:Tarendai,项目名称:spring-website,代码行数:59,代码来源:PublishStashedFileJob.php

示例14: doApiRequest

 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);
 }
开发者ID:paladox,项目名称:2,代码行数:8,代码来源:UploadFromUrlTest.php

示例15: getMain

 /**
  * 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;
 }
开发者ID:paladox,项目名称:2,代码行数:12,代码来源:ApiDocumentationTest.php


注:本文中的ApiMain类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。