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


PHP MWHttpRequest类代码示例

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


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

示例1: getNoticeIdFromResponse

 /**
  * Get the resulting notice ID from the reponse header of the API
  * request.
  *
  * @param  MWHttpRequest $response The response from the API request.
  * @return int|boolean             The ID of the resulting notice or
  *                                 false on failure.
  */
 public function getNoticeIdFromResponse(\MWHttpRequest $response)
 {
     $location = $response->getResponseHeader('Location');
     if (empty($location)) {
         return false;
     }
     $path = parse_url($location, PHP_URL_PATH);
     $matches = [];
     if (preg_match('/^\\/notices\\/(\\d+)$/', $path, $matches)) {
         return (int) $matches[1];
     }
     return false;
 }
开发者ID:Tjorriemorrie,项目名称:app,代码行数:21,代码来源:ChillingEffectsClient.class.php

示例2: request

 /**
  * The general method for handling the communication with the service.
  */
 public function request($resourceName, $getParams = [], $postData = [], $extraRequestOptions = [])
 {
     // Crash if we cannot make HTTP requests.
     \Wikia\Util\Assert::true(\MWHttpRequest::canMakeRequests());
     // Add client_id and client_secret to the GET data.
     $getParams['client_id'] = $this->clientId;
     $getParams['client_secret'] = $this->clientSecret;
     // Request URI pre-processing.
     $uri = "{$this->baseUri}{$resourceName}?" . http_build_query($getParams);
     // Request options pre-processing.
     $options = ['method' => 'GET', 'timeout' => 5, 'postData' => $postData, 'noProxy' => true, 'followRedirects' => false, 'returnInstance' => true, 'internalRequest' => true];
     $options = array_merge($options, $extraRequestOptions);
     /*
      * MediaWiki's MWHttpRequest class heavily relies on Messaging API
      * (wfMessage()) which happens to rely on the value of $wgLang.
      * $wgLang is set after $wgUser. On per-request authentication with
      * an access token we use MWHttpRequest before wgUser is created so
      * we need $wgLang to be present. With GlobalStateWrapper we can set
      * the global variable in the local, function's scope, so it is the
      * same as the already existing $wgContLang.
      */
     global $wgContLang;
     $wrapper = new GlobalStateWrapper(['wgLang' => $wgContLang]);
     // Request execution.
     /** @var \MWHttpRequest $request */
     $request = $wrapper->wrap(function () use($options, $uri) {
         return \Http::request($options['method'], $uri, $options);
     });
     $this->status = $request->status;
     $output = json_decode($request->getContent());
     if (!$output) {
         throw new ClientException('Invalid response.');
     }
     return $output;
 }
开发者ID:Tjorriemorrie,项目名称:app,代码行数:38,代码来源:Client.class.php

示例3: getData

	public function getData () {

		// Crazy workaround for HttpRequest not accepting user options
		$req = MWHttpRequest::factory( $this->summaryDataURL, array ('method' => "GET", 'timeout' => 'default') );
		$req->setHeader("http-x-license-key", $this->licenceKey);
		$status = $req->execute();
		$response = $req->getContent();
		$data = array();

		if ($response) {
			// chop up xml
			$xml = simplexml_load_string($response);
			$data = array();
			foreach ($xml->threshold_value as $node) {
				$label = (string)$node['name'];

				// just grab the time from the first field since we are rounding to the nearest hour anyway
				if (empty($data['Time'])) {
					$time = (string)$node['end_time'];
					$date = strtotime($time);  // raw mysql date format should parse ok
					$data['Time'] = $date;
				}
				// we only want to use some of the fields returned from new relic
				if (in_array($label, array('Errors', 'Response Time', 'Throughput')))
					$data[$label] = (string)$node['metric_value'];
			}
		} else {
//			print_pre("null response from newrelic");
		}
		return $data;
	}
开发者ID:schwarer2006,项目名称:wikia,代码行数:31,代码来源:ResponsetimeNewrelic.php

示例4: passCaptcha

 /**
  * Check, if the user solved the captcha.
  *
  * Based on reference implementation:
  * https://github.com/google/recaptcha#php
  *
  * @return boolean
  */
 function passCaptcha()
 {
     global $wgRequest, $wgReCaptchaSecretKey, $wgReCaptchaSendRemoteIP;
     $url = 'https://www.google.com/recaptcha/api/siteverify';
     // Build data to append to request
     $data = array('secret' => $wgReCaptchaSecretKey, 'response' => $wgRequest->getVal('g-recaptcha-response'));
     if ($wgReCaptchaSendRemoteIP) {
         $data['remoteip'] = $wgRequest->getIP();
     }
     $url = wfAppendQuery($url, $data);
     $request = MWHttpRequest::factory($url, array('method' => 'GET'));
     $status = $request->execute();
     if (!$status->isOK()) {
         $this->error = 'http';
         $this->logStatusError($status);
         return false;
     }
     $response = FormatJson::decode($request->getContent(), true);
     if (!$response) {
         $this->error = 'json';
         $this->logStatusError($this->error);
         return false;
     }
     if (isset($response['error-codes'])) {
         $this->error = 'recaptcha-api';
         $this->logCheckError($response['error-codes']);
         return false;
     }
     return $response['success'];
 }
开发者ID:jpena88,项目名称:mediawiki-dokku-deploy,代码行数:38,代码来源:ReCaptchaNoCaptcha.class.php

示例5: streamAppleTouch

function streamAppleTouch()
{
    global $wgAppleTouchIcon;
    wfResetOutputBuffers();
    if ($wgAppleTouchIcon === false) {
        # That's not very helpful, that's where we are already
        header('HTTP/1.1 404 Not Found');
        faviconShowError('$wgAppleTouchIcon is configured incorrectly, ' . 'it must be set to something other than false \\n');
        return;
    }
    $req = RequestContext::getMain()->getRequest();
    if ($req->getHeader('X-Favicon-Loop') !== false) {
        header('HTTP/1.1 500 Internal Server Error');
        faviconShowError('Proxy forwarding loop detected');
        return;
    }
    $url = wfExpandUrl($wgAppleTouchIcon, PROTO_CANONICAL);
    $client = MWHttpRequest::factory($url);
    $client->setHeader('X-Favicon-Loop', '1');
    $status = $client->execute();
    if (!$status->isOK()) {
        header('HTTP/1.1 500 Internal Server Error');
        faviconShowError("Failed to fetch URL \"{$url}\"");
        return;
    }
    $content = $client->getContent();
    header('Content-Length: ' . strlen($content));
    header('Content-Type: ' . $client->getResponseHeader('Content-Type'));
    header('Cache-Control: public');
    header('Expires: ' . gmdate('r', time() + 86400));
    echo $content;
}
开发者ID:nomoa,项目名称:operations-mediawiki-config,代码行数:32,代码来源:touch.php

示例6: checkContactLink

 protected function checkContactLink($name, $url, &$countOk)
 {
     global $wgVersion;
     $ok = false;
     if (Sanitizer::validateEmail($url)) {
         $ok = true;
         // assume OK
     } else {
         $bits = wfParseUrl($url);
         if ($bits && isset($bits['scheme'])) {
             if ($bits['scheme'] == 'mailto') {
                 $ok = true;
                 // assume OK
             } elseif (in_array($bits['scheme'], array('http', 'https'))) {
                 $req = MWHttpRequest::factory($url, array('method' => 'GET', 'timeout' => 8, 'sslVerifyHost' => false, 'sslVerifyCert' => false));
                 $req->setUserAgent("MediaWiki {$wgVersion}, CheckCongressLinks Checker");
                 $ok = $req->execute()->isOK();
             }
         }
     }
     if ($ok) {
         ++$countOk;
     } else {
         $this->output("Broken: [{$name}] [{$url}]\n");
     }
 }
开发者ID:schwarer2006,项目名称:wikia,代码行数:26,代码来源:checkContacts.php

示例7: getInterfaceObjectFromType

 protected function getInterfaceObjectFromType($type)
 {
     wfProfileIn(__METHOD__);
     $apiUrl = $this->getApiUrl();
     if (empty($this->videoId)) {
         throw new EmptyResponseException($apiUrl);
     }
     $memcKey = wfMemcKey(static::$CACHE_KEY, $apiUrl, static::$CACHE_KEY_VERSION);
     $processedResponse = F::app()->wg->memc->get($memcKey);
     if (empty($processedResponse)) {
         $req = MWHttpRequest::factory($apiUrl, array('noProxy' => true));
         $req->setHeader('User-Agent', self::$REQUEST_USER_AGENT);
         $status = $req->execute();
         if ($status->isOK()) {
             $response = $req->getContent();
             $this->response = $response;
             // Only for migration purposes
             if (empty($response)) {
                 throw new EmptyResponseException($apiUrl);
             } else {
                 if ($req->getStatus() == 301) {
                     throw new VideoNotFoundException($req->getStatus(), $this->videoId . ' Moved Permanently.', $apiUrl);
                 }
             }
         } else {
             $this->checkForResponseErrors($req->status, $req->getContent(), $apiUrl);
         }
         $processedResponse = $this->processResponse($response, $type);
         F::app()->wg->memc->set($memcKey, $processedResponse, static::$CACHE_EXPIRY);
     }
     wfProfileOut(__METHOD__);
     return $processedResponse;
 }
开发者ID:Tjorriemorrie,项目名称:app,代码行数:33,代码来源:GamestarApiWrapper.class.php

示例8: testApiLoginGotCookie

 /**
  * @group Broken
  */
 public function testApiLoginGotCookie()
 {
     $this->markTestIncomplete("The server can't do external HTTP requests, " . "and the internal one won't give cookies");
     global $wgServer, $wgScriptPath;
     if (!isset($wgServer)) {
         $this->markTestIncomplete('This test needs $wgServer to be set in LocalSettings.php');
     }
     $user = self::$users['sysop'];
     $req = MWHttpRequest::factory(self::$apiUrl . "?action=login&format=xml", array("method" => "POST", "postData" => array("lgname" => $user->username, "lgpassword" => $user->password)), __METHOD__);
     $req->execute();
     libxml_use_internal_errors(true);
     $sxe = simplexml_load_string($req->getContent());
     $this->assertNotInternalType("bool", $sxe);
     $this->assertThat($sxe, $this->isInstanceOf("SimpleXMLElement"));
     $this->assertNotInternalType("null", $sxe->login[0]);
     $a = $sxe->login[0]->attributes()->result[0];
     $this->assertEquals(' result="NeedToken"', $a->asXML());
     $token = (string) $sxe->login[0]->attributes()->token;
     $req->setData(array("lgtoken" => $token, "lgname" => $user->username, "lgpassword" => $user->password));
     $req->execute();
     $cj = $req->getCookieJar();
     $serverName = parse_url($wgServer, PHP_URL_HOST);
     $this->assertNotEquals(false, $serverName);
     $serializedCookie = $cj->serializeToHttpRequest($wgScriptPath, $serverName);
     $this->assertNotEquals('', $serializedCookie);
     $this->assertRegexp('/_session=[^;]*; .*UserID=[0-9]*; .*UserName=' . $user->userName . '; .*Token=/', $serializedCookie);
 }
开发者ID:lourinaldi,项目名称:mediawiki,代码行数:30,代码来源:ApiLoginTest.php

示例9: getImage

 /**
  * getImage method
  *
  */
 public function getImage()
 {
     $this->wf->profileIn(__METHOD__);
     if ($this->wg->User->isLoggedIn()) {
         # make proper thumb path: c/central/images/thumb/....
         $path = sprintf("%s/%s/images", substr($this->wg->DBname, 0, 1), $this->wg->DBname);
         # take thumb request from request
         $img = $this->getVal('image');
         if (preg_match('/^(\\/?)thumb\\//', $img)) {
             # build proper thumb url for thumbnailer
             $thumb_url = sprintf("%s/%s/%s", $this->wg->ThumbnailerService, $path, $img);
             # call thumbnailer
             $options = array('method' => 'GET', 'timeout' => 'default', 'noProxy' => 1);
             $thumb_request = MWHttpRequest::factory($thumb_url, $options);
             $status = $thumb_request->execute();
             $headers = $thumb_request->getResponseHeaders();
             if ($status->isOK()) {
                 if (!empty($headers)) {
                     foreach ($headers as $header_name => $header_value) {
                         if (is_array($header_value)) {
                             list($value) = $header_value;
                         } else {
                             $value = $header_value;
                         }
                         header(sprintf("%s: %s", $header_name, $value));
                     }
                 }
                 echo $thumb_request->getContent();
             } else {
                 $this->wf->debug("Cannot generate auth thumb");
                 $this->_access_forbidden('img-auth-accessdenied', 'img-auth-nofile', $img);
             }
         } else {
             # serve original image
             $filename = realpath(sprintf("%s/%s", $this->wg->UploadDirectory, $img));
             $stat = @stat($filename);
             if ($stat) {
                 $this->wf->ResetOutputBuffers();
                 $fileinfo = finfo_open(FILEINFO_MIME_TYPE);
                 $imageType = finfo_file($fileinfo, $filename);
                 header(sprintf("Content-Disposition: inline;filename*=utf-8'%s'%s", $this->wg->ContLanguageCode, urlencode(basename($filename))));
                 header(sprintf("Content-Type: %s", $imageType));
                 header(sprintf("Content-Length: %d" . $stat['size']));
                 readfile($filename);
             } else {
                 $this->_access_forbidden('img-auth-accessdenied', 'img-auth-nopathinfo', $img);
             }
         }
     } else {
         $this->_access_forbidden('img-auth-accessdenied', 'img-auth-public', '');
     }
     $this->wf->profileOut(__METHOD__);
     exit;
 }
开发者ID:schwarer2006,项目名称:wikia,代码行数:58,代码来源:AuthImageSpecialPageController.class.php

示例10: makeRequest

 public function makeRequest($url, $method = 'POST')
 {
     $options = array('method' => $method);
     if ($this->followRedirects) {
         $options['followRedirects'] = true;
         $this->followRedirects = false;
         # Reset the flag
     }
     $req = MWHttpRequest::factory($url, $options);
     $req->setUserAgent($this->userAgent);
     $req->setCookieJar($this->cookie_jar);
     return $req;
 }
开发者ID:ATCARES,项目名称:mediawiki-moderation,代码行数:13,代码来源:ModerationTestsuiteHTTP.php

示例11: importVideosForKeyphrase

 protected function importVideosForKeyphrase($keyword, $params = array())
 {
     wfProfileIn(__METHOD__);
     $addlCategories = !empty($params['addlCategories']) ? $params['addlCategories'] : array();
     $debug = !empty($params['debug']);
     $startDate = !empty($params['startDate']) ? $params['startDate'] : '';
     $endDate = !empty($params['endDate']) ? $params['endDate'] : '';
     $articlesCreated = 0;
     $page = 1;
     do {
         $numVideos = 0;
         // connect to provider API
         $url = $this->initFeedUrl($keyword, $startDate, $endDate, $page++);
         print "Connecting to {$url}...\n";
         $req = MWHttpRequest::factory($url);
         $status = $req->execute();
         if ($status->isOK()) {
             $response = $req->getContent();
         } else {
             print "ERROR: problem downloading content!\n";
             wfProfileOut(__METHOD__);
             return 0;
         }
         // parse response
         $videos = json_decode($response, true);
         $numVideos = sizeof($videos['videos']);
         print "Found {$numVideos} videos...\n";
         for ($i = 0; $i < $numVideos; $i++) {
             $clipData = array();
             $video = $videos['videos'][$i];
             $clipData['clipTitle'] = trim($video['title']);
             $clipData['videoId'] = $video['guid'];
             $clipData['thumbnail'] = $video['image'];
             $clipData['duration'] = $video['duration'];
             $clipData['published'] = $video['date'];
             $clipData['category'] = $video['category_name'];
             $clipData['keywords'] = trim($video['tags']);
             $clipData['description'] = trim($video['description']);
             $clipData['aspectRatio'] = $video['aspect_ratio'];
             $msg = '';
             $createParams = array('addlCategories' => $addlCategories, 'debug' => $debug);
             $articlesCreated += $this->createVideo($clipData, $msg, $createParams);
             if ($msg) {
                 print "ERROR: {$msg}\n";
             }
         }
     } while ($numVideos == self::API_PAGE_SIZE);
     wfProfileOut(__METHOD__);
     return $articlesCreated;
 }
开发者ID:schwarer2006,项目名称:wikia,代码行数:50,代码来源:RealgravityFeedIngester.class.php

示例12: requestParsoid

 protected function requestParsoid($method, $title, $params)
 {
     global $wgVisualEditorParsoidURL, $wgVisualEditorParsoidTimeout, $wgVisualEditorParsoidForwardCookies;
     $url = $wgVisualEditorParsoidURL . '/' . urlencode($this->getApiSource()) . '/' . urlencode($title->getPrefixedDBkey());
     $data = array_merge($this->getProxyConf(), array('method' => $method, 'timeout' => $wgVisualEditorParsoidTimeout));
     if ($method === 'POST') {
         $data['postData'] = $params;
     } else {
         $url = wfAppendQuery($url, $params);
     }
     $req = MWHttpRequest::factory($url, $data);
     // Forward cookies, but only if configured to do so and if there are read restrictions
     if ($wgVisualEditorParsoidForwardCookies && !User::isEveryoneAllowed('read')) {
         $req->setHeader('Cookie', $this->getRequest()->getHeader('Cookie'));
     }
     $status = $req->execute();
     if ($status->isOK()) {
         // Pass thru performance data from Parsoid to the client, unless the response was
         // served directly from Varnish, in  which case discard the value of the XPP header
         // and use it to declare the cache hit instead.
         $xCache = $req->getResponseHeader('X-Cache');
         if (is_string($xCache) && strpos(strtolower($xCache), 'hit') !== false) {
             $xpp = 'cached-response=true';
             $hit = true;
         } else {
             $xpp = $req->getResponseHeader('X-Parsoid-Performance');
             $hit = false;
         }
         WikiaLogger::instance()->debug('ApiVisualEditor', array('hit' => $hit, 'method' => $method, 'url' => $url));
         if ($xpp !== null) {
             $resp = $this->getRequest()->response();
             $resp->header('X-Parsoid-Performance: ' . $xpp);
         }
     } elseif ($status->isGood()) {
         $this->dieUsage($req->getContent(), 'parsoidserver-http-' . $req->getStatus());
     } elseif ($errors = $status->getErrorsByType('error')) {
         $error = $errors[0];
         $code = $error['message'];
         if (count($error['params'])) {
             $message = $error['params'][0];
         } else {
             $message = 'MWHttpRequest error';
         }
         $this->dieUsage($message, 'parsoidserver-' . $code);
     }
     // TODO pass through X-Parsoid-Performance header, merge with getHTML above
     return $req->getContent();
 }
开发者ID:Tjorriemorrie,项目名称:app,代码行数:48,代码来源:ApiVisualEditor.php

示例13: hitUrl

 public function hitUrl($zip, $attempt = 0)
 {
     $url = $this->makeUrl($zip);
     //$this->output( "*Trying to hit $url\n" );
     $req = MWHttpRequest::factory($url, array('method' => 'GET', 'timeout' => 2, 'sslVerifyHost' => false, 'sslVerifyCert' => false));
     if ($req->execute()->isOK()) {
         $this->isOK++;
     } else {
         sleep(2);
         $attempt++;
         if ($attempt < 3) {
             $this->hitUrl($zip, $attempt);
         } else {
             $this->isBad++;
         }
     }
 }
开发者ID:schwarer2006,项目名称:wikia,代码行数:17,代码来源:populateCache.php

示例14: get

 public function get($url, $postData = false)
 {
     $this->log("Connect: {$url} ", 1);
     $options = array('followRedirects' => true, 'noProxy' => true, 'timeout' => 220);
     if ($postData !== false) {
         $options['postData'] = $postData;
         print_r($postData);
     }
     $req = MWHttpRequest::factory($url, $options);
     $status = $req->execute();
     $decodedResponse = null;
     if ($status->isOK()) {
         $response = $req->getContent();
         $response = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($response));
         $responseCode = $req->getStatus();
         $decodedResponse = json_decode($response);
     }
     return array('code' => $responseCode, 'response' => $decodedResponse);
 }
开发者ID:Tjorriemorrie,项目名称:app,代码行数:19,代码来源:EntityAPIClient.class.php

示例15: hitThumbUrl

 protected function hitThumbUrl($file, $transformParams)
 {
     global $wgUploadThumbnailRenderHttpCustomHost, $wgUploadThumbnailRenderHttpCustomDomain;
     $thumbName = $file->thumbName($transformParams);
     $thumbUrl = $file->getThumbUrl($thumbName);
     if ($wgUploadThumbnailRenderHttpCustomDomain) {
         $parsedUrl = wfParseUrl($thumbUrl);
         if (!$parsedUrl || !isset($parsedUrl['path']) || !strlen($parsedUrl['path'])) {
             return false;
         }
         $thumbUrl = '//' . $wgUploadThumbnailRenderHttpCustomDomain . $parsedUrl['path'];
     }
     wfDebug(__METHOD__ . ": hitting url {$thumbUrl}\n");
     $request = MWHttpRequest::factory($thumbUrl, array('method' => 'HEAD', 'followRedirects' => true), __METHOD__);
     if ($wgUploadThumbnailRenderHttpCustomHost) {
         $request->setHeader('Host', $wgUploadThumbnailRenderHttpCustomHost);
     }
     $status = $request->execute();
     return $request->getStatus();
 }
开发者ID:eliagbayani,项目名称:LiteratureEditor,代码行数:20,代码来源:ThumbnailRenderJob.php


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