예제 #1
0
 /**
  * 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;
 }
예제 #2
0
 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);
     }
 }
예제 #3
0
 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);
     }
 }
예제 #4
0
 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);
 }
 /** @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']);
     }
 }
예제 #6
0
 /**
  * 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;
 }
예제 #7
0
 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;
    }
 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);
 }
예제 #10
0
 /**
  * Test that the API will accept a FauxRequest and execute.
  */
 public function testApi()
 {
     $api = new ApiMain(new FauxRequest(array('action' => 'query', 'meta' => 'siteinfo')));
     $api->execute();
     $data = $api->getResult()->getResultData();
     $this->assertInternalType('array', $data);
     $this->assertArrayHasKey('query', $data);
 }
예제 #11
0
 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);
 }
예제 #12
0
 /**
  * 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);
     }
 }
	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 );
		}
	}
예제 #14
0
 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;
 }
예제 #16
0
 /**
  * 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();
 }
예제 #17
0
 /**
  * @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');
     }
 }
 /**
  * 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;
 }
예제 #19
0
 /**
  * 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"));
 }
 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;
 }
예제 #21
0
 /**
  * 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;
 }
 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;
 }
예제 #23
0
 protected function doApiRequest($params, $session = null, $appendModule = false, $user = null)
 {
     if (is_null($session)) {
         $session = array();
     }
     $context = $this->apiContext->newTestContext($params, $session, $user);
     $module = new ApiMain($context, true);
     $module->execute();
     $results = array($module->getResultData(), $context->getRequest(), $context->getRequest()->getSessionArray());
     if ($appendModule) {
         $results[] = $module;
     }
     return $results;
 }
예제 #24
0
 protected function doApiRequest($params, $session = null, $appendModule = false)
 {
     if (is_null($session)) {
         $session = array();
     }
     $request = new FauxRequest($params, true, $session);
     $module = new ApiMain($request, true);
     $module->execute();
     $results = array($module->getResultData(), $request, $request->getSessionArray());
     if ($appendModule) {
         $results[] = $module;
     }
     return $results;
 }
 /**
  * @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;
 }
예제 #26
0
 /**
  * Get HTML email message and list of email recipients from given email
  * info.
  *
  * @param ORMRow $emailInfo
  * @return array With 'message' and 'recipients' items.
  */
 protected function prepareTemplate($emailInfo)
 {
     $template = $emailInfo->getField('template');
     $params = $emailInfo->getField('params');
     $fauxreq = new FauxRequest(array('action' => 'parse', 'text' => $this->getTemplate($template, $params), 'contentmodel' => 'wikitext'));
     $api = new ApiMain($fauxreq);
     $api->execute();
     $data = $api->getResultData();
     $message = $data['parse']['text']['*'];
     $recipients = array();
     foreach ($params['To'] as $to) {
         $recipients[] = new MailAddress($to);
     }
     return array('message' => $message, 'recipients' => $recipients);
 }
 private function doTest(array $params, $expected)
 {
     $params += array('action' => 'parse');
     $req = new FauxRequest($params);
     $api = new ApiMain($req);
     $api->execute();
     if (defined('ApiResult::META_CONTENT')) {
         $data = $api->getResult()->getResultData(null, array('BC' => array(), 'Types' => array()));
     } else {
         $data = $api->getResultData();
     }
     $this->assertFalse(isset($data['errors']));
     $text = preg_replace("/[\r\n]/", '', trim($data['parse']['text']['*']));
     $expected = preg_replace("/[\r\n]/", '', trim($expected));
     $this->assertEquals($expected, $text);
 }
예제 #28
0
function wfMsUploadSaveKat($name, $kat)
{
    global $wgContLang, $wgUser;
    $mediaString = strtolower($wgContLang->getNsText(NS_FILE));
    $title = $mediaString . ':' . $name;
    $text = "\n[[" . $kat . "]]";
    $wgEnableWriteAPI = true;
    $params = new FauxRequest(array('action' => 'edit', 'section' => 'new', 'title' => $title, 'text' => $text, 'token' => $wgUser->editToken()));
    $enableWrite = true;
    // This is set to false by default, in the ApiMain constructor
    $api = new ApiMain($params, $enableWrite);
    #$api = new ApiMain($params);
    $api->execute();
    $data =& $api->getResultData();
    return $mediaString;
}
예제 #29
0
 protected function saveWikitext($title, $wikitext, $params)
 {
     $apiParams = array('action' => 'edit', 'title' => $title->getPrefixedDBkey(), 'text' => $wikitext, 'summary' => $params['summary'], 'basetimestamp' => $params['basetimestamp'], 'starttimestamp' => $params['starttimestamp'], 'token' => $params['token']);
     if ($params['minor']) {
         $apiParams['minor'] = true;
     } else {
         $apiParams['notminor'] = true;
     }
     // FIXME add some way that the user's preferences can be respected
     $apiParams['watchlist'] = $params['watch'] ? 'watch' : 'unwatch';
     if ($params['g-recaptcha-response']) {
         $apiParams['g-recaptcha-response'] = $params['g-recaptcha-response'];
     }
     $api = new ApiMain(new DerivativeRequest($this->getRequest(), $apiParams + $this->getRequest()->getValues(), true), true);
     $api->execute();
     return $api->getResultData();
 }
 /**
  * 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, $wgSitename, $wgContLanguageCode;
     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 nested request
         $fauxReq = new FauxRequest(array('action' => 'query', 'meta' => 'siteinfo', 'siprop' => 'general', 'list' => 'watchlist', 'wlprop' => 'title|user|comment|timestamp', 'wldir' => 'older', 'wlend' => $endTime, 'wllimit' => 50));
         // Execute
         $module = new ApiMain($fauxReq);
         $module->execute();
         // Get data array
         $data = $module->getResultData();
         $feedItems = array();
         foreach ($data['query']['watchlist'] as $info) {
             $feedItems[] = $this->createFeedItem($info);
         }
         $feedTitle = $wgSitename . ' - ' . wfMsgForContent('watchlist') . ' [' . $wgContLanguageCode . ']';
         $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') . ' [' . $wgContLanguageCode . ']';
         $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);
     }
 }