/** * * @return AddOn[] */ public function all() { $path = $this->_config->merchantPath() . '/add_ons'; $response = $this->_http->get($path); $addOns = ["addOn" => $response['addOns']]; return Util::extractAttributeAsArray($addOns, 'addOn'); }
/** * 获取颜色列表 * * @return array */ public function lists() { $key = 'overtrue.wechat.colors'; return $this->cache->get($key, function ($key) { $result = $this->http->get(self::API_LIST); $this->cache->set($key, $result['colors'], 86400); // 1 day return $result['colors']; }); }
protected function fetchScriptList() { $data = array('action' => 'query', 'format' => 'php', 'list' => 'allpages', 'apnamespace' => '8', 'aplimit' => '500'); $baseUrl = $this->getArg(0); $pages = array(); do { $url = wfAppendQuery($baseUrl, $data); $strResult = Http::get($url); //$result = FormatJson::decode( $strResult ); // Still broken $result = unserialize($strResult); if (!empty($result['query']['allpages'])) { foreach ($result['query']['allpages'] as $page) { if (substr($page['title'], -3) === '.js') { strtok($page['title'], ':'); $pages[] = strtok(''); } } } if (!empty($result['query-continue'])) { $data['apfrom'] = $result['query-continue']['allpages']['apfrom']; $this->output("Fetching new batch from {$data['apfrom']}\n"); } } while (isset($result['query-continue'])); return $pages; }
function render() { $group_id = Http::get("id"); $smarty = $this->registry->get("smarty"); $groups_model = DB::loadModel("users/groups"); $permissions_model = DB::loadModel("users/permissions"); $permissions = $permissions_model->getPermissions(); $permissions_group = $permissions_model->getPermissionsGroup($group_id); $ids = array(); foreach ($permissions_group as $pg) { $ids[] = $pg['permission_id']; } $pres = array(); foreach ($permissions as $permission) { if (in_array($permission["id"], $ids)) { $permission["enabled"] = 1; } else { $permission["enabled"] = 0; } $pres[] = $permission; } $group = $groups_model->get($group_id); $smarty->assign('group_id', $group_id); $smarty->assign('group', $group); $smarty->assign('permissions', $pres); return $smarty->fetch(TMPL_PATH . "admin/users/group_edit.tpl"); }
protected function getUntranslatedPages($apiUrl, $category, $targetDomain) { $this->output("Fetching pages from {$category} not present in {$targetDomain} ..."); $pages = array(); $params = array('action' => 'query', 'format' => 'json', 'generator' => 'categorymembers', 'gcmtitle' => "Category:{$category}", 'gcmnamespace' => 0, 'gcmlimit' => 500, 'gcmsort' => 'timestamp', 'prop' => 'langlinks', 'lllang' => $targetDomain, 'lllimit' => 500, 'continue' => ''); while (true) { $url = $apiUrl . http_build_query($params); $json = Http::get($url); $data = FormatJson::decode($json, true); if (!isset($data['query'])) { $this->output("\t[FAIL]\n"); return array(); } $pagesInCategory = $data['query']['pages']; foreach ($pagesInCategory as $pageId => $page) { if (!isset($page['langlinks'])) { $pages[] = $page['title']; } } if (!isset($data['continue']) || count($pages) > 5000) { break; } else { unset($params['llcontinue']); unset($params['gcmcontinue']); $params += $data['continue']; } } $this->output("\t[OK]\n"); return $pages; }
function refresh($force = false) { // How often to check for updates $interval = $this->hook->apply('product_info_refresh_interval', 60 * 60 * 12); if (!$force && isset($this->data['last_refresh']) && $this->data['last_refresh'] > time() - $interval) { return false; } $http = new Http($this->config, $this->hook, $this->router); $response = $http->get($this->config->leeflets_api_url . '/product-info?slugs=core'); if (Error::is_a($response)) { return $response; } if ((int) $response['response']['code'] < 200 || (int) $response['response']['code'] > 399) { return new Error('product_info_refresh_fail_http_status', 'Failed to refresh product info from leeflets.com. Received response ' . $response['response']['code'] . ' ' . $response['response']['message'] . '.', $response); } if (!($response_data = json_decode($response['body'], true))) { return new Error('product_info_refresh_fail_json_decode', 'Failed to refresh product info from leeflets.com. Error decoding the JSON response received from the server.', $response['body']); } $this->data = array(); $this->data['last_refresh'] = time(); $this->data['products'] = $response_data; $this->write(); $this->load(); return true; }
protected function fetchScriptList() { $data = ['action' => 'query', 'format' => 'json', 'list' => 'allpages', 'apnamespace' => '8', 'aplimit' => '500', 'continue' => '']; $baseUrl = $this->getArg(0); $pages = []; while (true) { $url = wfAppendQuery($baseUrl, $data); $strResult = Http::get($url, [], __METHOD__); $result = FormatJson::decode($strResult, true); $page = null; foreach ($result['query']['allpages'] as $page) { if (substr($page['title'], -3) === '.js') { strtok($page['title'], ':'); $pages[] = strtok(''); } } if ($page !== null) { $this->output("Fetched list up to {$page['title']}\n"); } if (isset($result['continue'])) { // >= 1.21 $data = array_replace($data, $result['continue']); } elseif (isset($result['query-continue']['allpages'])) { // <= 1.20 $data = array_replace($data, $result['query-continue']['allpages']); } else { break; } } return $pages; }
function efTSPollRender( $input, $args, $parser ) { // Control if the "id" is set. If not, it output a error if ( isset( $args['id'] ) && $args['id'] != "" ) { $id = wfUrlencode( $args['id'] ); } else { return wfMsg( 'tspoll-id-error' ); } // Control if "dev" is set. If not, it use the normal skript, else, it use the dev skript if ( isset( $args['dev'] ) && $args['dev'] == "1" ) { // If the arrgument dev is given, use the TSPoll-Dev-Version $get_server = Http::get( 'http://toolserver.org/~jan/poll/dev/main.php?page=wiki_output&id='.$id ); } else { // sonst die normale Version verwenden $get_server = Http::get( 'http://toolserver.org/~jan/poll/main.php?page=wiki_output&id='.$id ); } // If $get_server is empty it output a error if ( $get_server != '' ) { return $get_server; } else { return wfMsg( 'tspoll-fetch-error' ); } }
protected function getExternalData() { global $wgCityId; // Prevent recursive loop if ($wgCityId == self::EXTERNAL_DATA_SOURCE_WIKI_ID) { return array(); } if (self::$externalData === false) { global $wgLang, $wgMemc; $code = $wgLang->getCode(); $key = wfSharedMemcKey('user-command-special-page', 'lang', $code); $data = $wgMemc->get($key); if (empty($data)) { $data = array(); $external = Http::get($this->getExternalDataUrl($code)); $external = json_decode($external, true); if (is_array($external) && !empty($external['allOptions']) && is_array($external['allOptions'])) { foreach ($external['allOptions'] as $option) { $data[$option['id']] = $option; } } $wgMemc->set($key, $data, self::EXTERNAL_DATA_CACHE_TTL); } self::$externalData = $data; } return self::$externalData; }
/** * 获取access token * * @param string $code * * @return string */ public function getAccessPermission($code) { $access_token = new AccessTokenBiz($this->appId, $this->appSecret); $params = array('code' => $code, 'access_token' => $access_token->getToken()); Log::info($params); return $this->lastPermission = $this->http->get(self::API_USER, $params); }
function getlinksfromurl($url, $namespaceID) { $html = Http::get($url, 120); $doc = new DOMDocument(); @$doc->loadHTML($html); return $this->getlinksfromdocument($doc, $namespaceID); }
protected function extractVideoId($url) { global $wgMemc; // See if this is a valid url if (!preg_match('#/[a-zA-Z0-9\\-]+/[a-zA-Z0-9\\-]*-(\\d+)#', $url, $matches)) { return null; } $videoId = $matches[1]; $cacheKey = wfMemcKey('video', 'bliptv', $videoId); $cachedEmbedId = $wgMemc->get($cacheKey); if ($cachedEmbedId !== false) { return $cachedEmbedId; } list($apiUrl) = explode('?', $url); $apiUrl .= '?skin=api'; $apiContents = Http::get($apiUrl); if (empty($apiContents)) { return null; } $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML($apiContents); $embedId = $dom->getElementsByTagName('embedLookup')->item(0)->textContent; $wgMemc->set($cacheKey, $embedId, 60 * 60 * 24); return $embedId; }
function callback($ctx) { $jump = htmlspecialchars(trim($_GET['jump'])); self::validate_url($jump); if (!$this->appid || !$this->secret) { _redirect($jump); } $code = urlencode(htmlspecialchars(trim($_GET['code']))); if (!$code) { _redirect($jump); } $wx_url = 'https://api.weixin.qq.com/sns/oauth2/access_token'; $wx_url = "{$wx_url}?appid={$this->appid}&secret={$this->secret}&code={$code}&grant_type=authorization_code"; $resp = Http::get($wx_url); $ret = @json_decode($resp, true); if (is_array($ret) && $ret['openid']) { $connect = WxConnect::get_by('wx_openid', $ret['openid']); if ($connect) { Logger::info("wx_openid[{$ret['openid']}] oauth login, uid: {$connect->user_id}"); $profile = Profile::get($connect->user_id); if ($profile && $profile->status != Profile::STATUS_LOCK) { UC::force_login($profile); } } else { // 兼容 /weixin/bind, 因为它依赖 session 中的 openid, 所以这里设置 session_start(); $_SESSION['wx_openid'] = $ret['openid']; } } else { Logger::info("weixin oauth, code: {$code}, resp: {$resp}, " . Http::$error); } _redirect($jump); }
/** * Return PageSpeed score and page statistics for a given URL * * @see http://code.google.com/intl/pl/apis/pagespeedonline/v1/getting_started.html#examples * * @param string $url page URL * @param array $options additional options * @return mixed report */ public function getReport($url, array $options = array()) { $apiUrl = self::PAGESPPED_API_URL . '?' . http_build_query(array('url' => $url, 'key' => $this->apiKey)); $resp = Http::get($apiUrl); if (empty($resp)) { return false; } $resp = json_decode($resp, true); // prepare basic report $report = array('url' => $resp['id'], 'metrics' => array('pageSpeed' => intval($resp['score']))); // add the rest of the metrics $report['metrics'] += $resp['pageStats']; // serialized requests // "The following requests are serialized. Try to break up the dependencies to make them load in parallel." $report['metrics']['serializedRequests'] = $this->countReportedUrl($resp, 'AvoidExcessSerialization'); // count redirects $report['metrics']['redirects'] = $this->countReportedUrl($resp, 'MinimizeRedirects'); // count assets with short (less than 7 days) expiry time // "The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:" $report['metrics']['shortExpires'] = $this->countReportedUrl($resp, 'LeverageBrowserCaching'); // count assets served uncompressed $report['metrics']['notGzipped'] = $this->countReportedUrl($resp, 'EnableGzipCompression'); // count duplicated content served from different URLs $report['metrics']['duplicatedContent'] = $this->countReportedUrl($resp, 'ServeResourcesFromAConsistentUrl'); // aggregate some of the stats $report['metrics']['totalResponseBytes'] = $resp['pageStats']['htmlResponseBytes'] + $resp['pageStats']['cssResponseBytes'] + (!empty($resp['pageStats']['imageResponseBytes']) ? $resp['pageStats']['imageResponseBytes'] : 0) + (!empty($resp['pageStats']['javascriptResponseBytes']) ? $resp['pageStats']['javascriptResponseBytes'] : 0) + (!empty($resp['pageStats']['otherResponseBytes']) ? $resp['pageStats']['otherResponseBytes'] : 0); return $report; }
function render() { $user_id = Http::get("id"); $smarty = $this->registry->get("smarty"); $user_model = DB::loadModel("users/user"); $groups_model = DB::loadModel("users/groups"); $user_data = $user_model->get($user_id); $all_groups = $groups_model->getGroups(); $user_groups = $groups_model->getUserGroups($user_id); $ids = array(); foreach ($user_groups as $ug) { $ids[] = $ug["id"]; } $user_all_groups = array(); foreach ($all_groups as $group) { if (in_array($group["id"], $ids)) { $group["enabled"] = 1; } else { $group["enabled"] = 0; } $user_all_groups[] = $group; } $smarty->assign('user_id', $user_id); $smarty->assign('user_data', $user_data); $smarty->assign('user_groups', $user_all_groups); return $smarty->fetch(TMPL_PATH . "admin/users/user_edit.tpl"); }
/** * Do cross-wiki API call * * @param string $dbName database name * @param array $params API query parameters * @param string $endpoint (api.php or wikia.php, generally) * @param boolean $setUser * * @return mixed API response */ static function foreignCall($dbName, array $params, $endpoint = self::API, $setUser = false) { wfProfileIn(__METHOD__); $hostName = self::getHostByDbName($dbName); // If hostName is empty, this would make a request to the current host. if (empty($hostName)) { wfProfileOut(__METHOD__); return false; } // request JSON format of API response $params['format'] = 'json'; $url = "{$hostName}/{$endpoint}?" . http_build_query($params); wfDebug(__METHOD__ . ": {$url}\n"); $options = []; if ($setUser) { $options = self::loginAsUser(); } // send request and parse response $resp = Http::get($url, 'default', $options); if ($resp === false) { wfDebug(__METHOD__ . ": failed!\n"); $res = false; } else { $res = json_decode($resp, true); } wfProfileOut(__METHOD__); return $res; }
public function log() { global $wgFlowerUrl; $taskId = $this->request->getVal('id'); $taskLogs = json_decode(Http::get("{$wgFlowerUrl}/api/task/get-logs/{$taskId}", 'default', ['noProxy' => true]), true); $this->wg->Out->setPageTitle(wfMsg('tasks-log-title')); $this->setVal('taskLogs', $taskLogs); }
public static function showCity() { $ip = Ip::getClientIp(); $url = "http://ip.taobao.com/service/getIpInfo2.php?ip={$ip}"; $data = Http::get($url); $data = json_decode($data, true); return $data; }
public static function allowOnlyRefer($inputData) { $refer = Http::get('refer'); $inputData = str_replace('/', '\\/', $inputData); if (!preg_match('/' . $inputData . '/i', $refer)) { Alert::make('Page not found'); } }
public function getData() { //$url = "http://labiryntus.eu/supereggbert-GLGE-865b2d6/examples/collada/duck.dae"; // get contents of a file into a string $url = $this->getVal('url'); $content = Http::get($url); //header('Content-type: text/xml'); $this->data = $content; }
function getSource() { $this->mSource = false; $url = $this->getUrl(); $this->msg("Fetching source document from {$url}... "); $this->mSource = Http::get($url); $this->msgStatus($this->mSource); return (bool) $this->mSource; }
/** * Check the page source for analytics tracking and return used tag * * @param $url page address to fetch * @return string|null analytics parameter used in this page * */ private function getAnalyticsProviderTag($url) { $page = Http::get($url); if (preg_match('/<img src="([^">]+)" [^>]+ alt="szmtag"/', $page, $m)) { $path = parse_url($m[1], PHP_URL_PATH); return array_pop(explode('/', $path)); } else { $this->fail('Cannot find the analytics image on page ' . $url); } }
public function download() { $contents = Http::get($_GET["url"]); $fileInfo = new SplFileInfo($_GET["fname"]); // Add the torrent to deluge using the RPC api $tconfig = Storage::get("torrents"); $client = new HTTPClient((array) $tconfig->deluge); $client->core->add_torrent_file($tconfig->dropPath . "/" . $fileInfo->getFilename() . ".torrent", base64_encode($contents), null); return $this->redirect("/?alert=" . urlencode("Torrent download started")); }
/** * 获取jsticket * * @return string */ public function getTicket() { $key = 'overtrue.wechat.jsapi_ticket' . $this->appId; return $this->cache->get($key, function ($key) { $http = new Http(new AccessToken($this->appId, $this->appSecret)); $result = $http->get(self::API_TICKET); $this->cache->set($key, $result['ticket'], $result['expires_in']); return $result['ticket']; }); }
/** * 图片素材总数. * * @param string $type * * @return array|int */ public function stats($type = null) { $response = $this->http->get(self::API_FOREVER_COUNT); $response['voice'] = $response['voice_count']; $response['image'] = $response['image_count']; $response['video'] = $response['video_count']; $response['news'] = $response['news_count']; $response = new Collection($response); return $type ? $response->get($type) : $response; }
static function parseFeed($url, $omitDB = false) { global $wgOut; //reset array self::$data = array('feedTitle' => '', 'images' => array()); if (!$omitDB) { //check DB for this URL - we might have it already (background task will refresh it) $data = self::getDataByUrl($url); } if ($omitDB || is_null($data)) { //no data in DB - fetch from feed $itemCount = 0; $rssContent = Http::get($url); $feed = new SimplePie(); $feed->set_raw_data($rssContent); $feed->init(); self::$data['feedTitle'] = $feed->get_title(); foreach ($feed->get_items() as $item) { $enclosures = $item->get_enclosures(); $enclosuresFound = false; //we have enclosures - use them instead of content of feed (usually there are bigger image while content uses thumbnails) if (!is_null($enclosures)) { foreach ($enclosures as $enclosure) { $type = $enclosure->get_type(); if (!empty($type) && substr($type, 0, 6) === 'image/') { self::$data['images'][] = array('src' => $enclosure->get_link(), 'caption' => $item->get_title(), 'link' => $item->get_link()); $enclosuresFound = true; break; //one image per feed } } } //if enclosures has not been found or doesn't contain any images - use regular method if (!$enclosuresFound) { //look for <img /> tags $description = $item->get_description(); preg_match('/<img .*?src=([\'"])(.*?\\.(?:jpg|jpeg|gif|png))\\1/', $description, $matches); if (!empty($matches[2])) { self::$data['images'][] = array('src' => $matches[2], 'caption' => $item->get_title(), 'link' => $item->get_link()); } } if (count(self::$data['images']) >= 20 || ++$itemCount > 50) { break; //take up to 20 images, from up to 50 articles. } } //store data in DB only if valid rss (images found) if (count(self::$data['images'])) { self::setData($url, self::$data); } } else { self::$data = $data; } return self::$data; }
function passCaptcha() { global $wgRequest; $ticket = $wgRequest->getVal('Asirra_Ticket'); $api = 'http://challenge.asirra.com/cgi/Asirra?'; $params = array('action' => 'ValidateTicket', 'ticket' => $ticket); $response = Http::get($api . wfArrayToCgi($params)); $xml = simplexml_load_string($response); $result = $xml->xpath('/AsirraValidation/Result'); return strval($result[0]) === 'Pass'; }
public function testGetRequest() { $_REQUEST['_url'] = '/this/is/a/test'; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['HTTP_BAR_FOO'] = 'foo-bar'; $request = new Http(); $this->assertEquals(['this', 'is', 'a', 'test'], $request->get()); $this->assertEquals('GET', $request->getMethod()); $this->assertEquals('foo-bar', $request->getHeader('bar-foo')); $this->assertEquals(['bar-foo' => 'foo-bar'], $request->getHeader()); }
/** * Fetch data from given URL * * @param $url String: the URL * @return String: the content at $url */ function fetchFromURL($url) { wfProfileIn(__METHOD__); /** * use noProxy because we don't want to redirect this through localhost * @see includes/HttpFunctions.php proxySetup() */ $ret = Http::get($this->buildUrl($url), 'default', array('noProxy' => true)); wfProfileOut(__METHOD__); return $ret; }
/** * 缓存jsTicket。jsTicket有效期为两小时,需要在失效前请求新的jsTicket(注意:以下代码没有在失效前刷新缓存的jsTicket)。 */ public static function getTicket($accessToken) { $jsticket = Cache::getJsTicket(); if ($jsticket === "") { $response = Http::get('/get_jsapi_ticket', array('type' => 'jsapi', 'access_token' => $accessToken)); self::check($response); $ticket = $response->ticket; Cache::setJsTicket($ticket); } return $jsticket; }