public function retrieve_user_details() { // Get the stream to the user page via the Snipt API $request = new HTTPRequest(SNIPT_API . SNIPT_USER . SNIPT_FORMAT, HTTP_METH_GET); echo "Connecting to Snipt API....\n"; $request->send(); if ($request->getResponseCode() == 200) { $this->user_details = json_decode($request->getResponseBody()); echo "Snipt entries to retrieve : {$this->user_details->count}\n"; foreach ($this->user_details->snipts as $snipt) { // Retrieve the snipt entry $request = new HTTPRequest(SNIPT_API . SNIPT_SNIPT . $snipt . "." . SNIPT_FORMAT . SNIPT_STYLE); $request->send(); if ($request->getResponseCode() == 200) { $this->snipts[$snipt] = json_decode($request->getResponseBody()); } else { echo "[ERROR] Could not retrieve the data for snipt entry {$snipt}\n"; } } return true; } else { echo "Invalid data received, exiting....\n"; return false; } }
/** * Sends the HTTP message [Request] to a remote server and processes * the response. * * @param Request $request request to send * @param Response $request response to send * @return Response */ public function _send_message(Request $request, Response $response) { $http_method_mapping = array(HTTP_Request::GET => HTTPRequest::METH_GET, HTTP_Request::HEAD => HTTPRequest::METH_HEAD, HTTP_Request::POST => HTTPRequest::METH_POST, HTTP_Request::PUT => HTTPRequest::METH_PUT, HTTP_Request::DELETE => HTTPRequest::METH_DELETE, HTTP_Request::OPTIONS => HTTPRequest::METH_OPTIONS, HTTP_Request::TRACE => HTTPRequest::METH_TRACE, HTTP_Request::CONNECT => HTTPRequest::METH_CONNECT); // Create an http request object $http_request = new HTTPRequest($request->uri(), $http_method_mapping[$request->method()]); if ($this->_options) { // Set custom options $http_request->setOptions($this->_options); } // Set headers $http_request->setHeaders($request->headers()->getArrayCopy()); // Set cookies $http_request->setCookies($request->cookie()); // Set query data (?foo=bar&bar=foo) $http_request->setQueryData($request->query()); // Set the body if ($request->method() == HTTP_Request::PUT) { $http_request->addPutData($request->body()); } else { $http_request->setBody($request->body()); } try { $http_request->send(); } catch (HTTPRequestException $e) { throw new Request_Exception($e->getMessage()); } catch (HTTPMalformedHeaderException $e) { throw new Request_Exception($e->getMessage()); } catch (HTTPEncodingException $e) { throw new Request_Exception($e->getMessage()); } // Build the response $response->status($http_request->getResponseCode())->headers($http_request->getResponseHeader())->cookie($http_request->getResponseCookies())->body($http_request->getResponseBody()); return $response; }
/** * Call the API * * @param string $routeName The route name to call * @param array $param The URL parameter to set * @param array $data An associative array of the data to send in the request : 'params', 'body', 'files' * * @return mixed The API response body */ private function callApi($routeName, $param = array(), $data = array()) { $route = self::$routes[$routeName]; $data = array_merge(array('params' => array(), 'body' => array(), 'files' => array()), $data); $uri = $route['uri']; foreach ($param as $key => $value) { $uri = str_replace('{' . $key . '}', $value, $uri); } if (!empty($data['params'])) { $uri .= '?' . http_build_query($data['params']); } $request = new HTTPRequest(array('url' => HAWK_SITE_URL . '/api' . $uri, 'headers' => array('X-Requested-With' => 'XMLHttpRequest'), 'method' => $route['method'], 'contentType' => 'json', 'dataType' => isset($route['dataType']) ? $route['dataType'] : 'json', 'body' => $data['body'], 'files' => $data['files'])); $request->send(); if ($request->getStatusCode() === 200) { $result = $request->getResponse(); $contentType = $request->getResponseHeaders('Content-Type'); if ($contentType == 'application/octet-stream') { $tmpName = TMP_DIR . uniqid() . '.zip'; file_put_contents($tmpName, base64_decode($result)); return $tmpName; } else { return $result; } } else { throw new HawkApiException((string) $request->getResponse(), (int) $request->getStatusCode()); } }
function checkCronJob() { $context = Model_Context::getInstance(); /* Cron, only in single page request, not in a page dead link */ if (!empty($_SERVER['HTTP_REFERER']) || !dumbCronScheduler(true)) { return; } $request = new HTTPRequest('GET', $context->getProperty('uri.default') . '/cron'); $request->timeout = 2; $request->send(); }
public static function leave($link) { return false; $link = trim($link); if (empty($link)) { return false; } $request = new HTTPRequest('POST', TEXTCUBE_SYNC_URL); $request->contentType = 'application/x-www-form-urlencoded; charset=utf-8'; return $request->send("mode=0&path=" . urlencode($link)) && checkResponseXML($request->responseText) === 0; }
public function decode($point = array('lat' => null, 'lng' => null)) { $uri = 'http://apis.map.qq.com/ws/geocoder/v1?location=' . $point['lat'] . ',' . $point['lng'] . '&output=json&key=' . $this->conf['key']; $http = new \HTTPRequest($uri, HTTP_METH_GET); $http->send(); $code = $http->getResponseCode(); if ($code != 200) { throw new Exception('http error', $code); } $r = json_decode($http->getResponseBody(), true); if (!isset($r['result']['address'])) { throw new Exception($r['message'], $r['status']); } return array('address' => $r['result']['address']); }
function call() { if (func_num_args() < 1) { return false; } $request = new HTTPRequest(); $request->method = 'POST'; $request->url = $this->url; $request->contentType = 'text/xml'; $request->async = $this->async; ob_start(); echo '<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>' . func_get_arg(0) . '</methodName><params>'; for ($i = 1; $i < func_num_args(); $i++) { echo '<param>'; echo $this->_encodeValue(func_get_arg($i)); echo '</param>'; } echo '</params></methodCall>'; $request->content = ob_get_contents(); ob_end_clean(); if (!$request->send()) { return false; } if ($this->async) { return true; } if (!is_null($request->getResponseHeader('Content-Type')) && $request->getResponseHeader('Content-Type') != 'text/xml') { return false; } $xmls = new XMLStruct(); $request->responseText = preg_replace_callback('/&#([0-9a-fx]+);/mi', 'replace_num_entity', $request->responseText); $xmls->open($request->responseText); if ($xmls->error) { return false; } if (isset($xmls->struct['methodResponse'][0]['fault'][0]['value'])) { $this->fault = $this->_decodeValue($xmls->struct['methodResponse'][0]['fault'][0]['value'][0]); } else { if (isset($xmls->struct['methodResponse'][0]['params'][0]['param'][0]['value'])) { $this->result = $this->_decodeValue($xmls->struct['methodResponse'][0]['params'][0]['param'][0]['value'][0]); } else { return false; } } return true; }
public function decode($point = array('lat' => null, 'lng' => null)) { $uri = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&latlng=' . $point['lat'] . ',' . $point['lng']; $http = new \HTTPRequest($uri, HTTP_METH_GET); if (isset($this->conf['lang'])) { $http->addHeaders(array('Accept-Language' => $this->conf['lang'])); } $http->send(); $code = $http->getResponseCode(); if ($code != 200) { throw new Exception('http error', $code); } $r = json_decode($http->getResponseBody(), true); if (!isset($r['results'][0]['formatted_address'])) { throw new Exception($r['status'], -1); } return array('address' => $r['results'][0]['formatted_address']); }
function GoogleBlogSearchPinging_ping($target) { /* TODO : do not send ping when private entry/post is added / modified */ static $lastPing = null; $ctx = Model_Context::getInstance(); $pingUrl = 'http://blogsearch.google.com/ping'; $ping = $pingUrl . '?name=' . rawurlencode($ctx->getProperty('blog.title')) . '&url=' . rawurlencode($ctx->getProperty('uri.default') . "/"); if (!isset($lastPing) || $ping != $lastPing) { if (ini_get('allow_url_fopen')) { file_get_contents($ping); } else { $request = new HTTPRequest($ping); $request->send(); } $lastPing = $ping; } return $target; }
/** * 上传文件,要token认证 * @example shell curl -i -F 'file=@2.jpg' -F 'token=asdf' -F 'key=2.jpg' 'http://up.qiniu.com/' * @example shell ./qrsync ./conf.json * @return array array( "httpUri" => "http://com-163-sinkcup-test.qiniudn.com/1.jpg", "httpsUri" => "https://dn-com-163-sinkcup-test.qbox.me/1.jpg", } */ public function uploadFile($localPath, $remoteFileName, $headers = array()) { $remoteFileName = str_replace('/', '', $remoteFileName); $uri = 'http://' . str_replace('//', '/', $this->conf['host']['up'] . '/'); //scope中指定文件,就可以覆盖。如果只写bucket,则重复上传会出现错误:614 文件已存在。 $policy = array('scope' => $this->bucket . ':' . $remoteFileName, 'deadline' => time() + 3600); $pics = array('image/jpeg', 'image/webp', 'image/png'); //如果是图片,则需要返回分辨率 if (isset($headers['Content-Type']) && in_array($headers['Content-Type'], $pics)) { $policy['returnBody'] = json_encode(array('width' => '$(imageInfo.width)', 'height' => '$(imageInfo.height)')); } $data = $this->encode(json_encode($policy)); $token = $this->sign($data) . ':' . $data; //$hash = hash_file('crc32b', $localPath); //$tmp = unpack('N', pack('H*', $hash)); $fields = array('token' => $token, 'key' => $remoteFileName); $http = new \HTTPRequest($uri, HTTP_METH_POST); $contentType = isset($headers['Content-Type']) ? $headers['Content-Type'] : 'multipart/form-data'; $http->addPostFile('file', $localPath, $contentType); $http->addPostFields($fields); //$http->setHeader($headers); $http->send(); $body = json_decode($http->getResponseBody(), true); $code = $http->getResponseCode(); if ($code == 200) { //自定义域名一定是http,因为证书不能跨域名 if (!isset($this->conf['customDomain']) || empty($this->conf['customDomain'])) { $httpUri = 'http://' . str_replace('//', '/', $this->bucket . $this->conf['httpUriSuffix'] . '/' . $remoteFileName); } else { $httpUri = 'http://' . $this->conf['customDomain'] . '/' . $remoteFileName; } $r = array('httpUri' => $httpUri, 'httpsUri' => 'https://' . str_replace('//', '/', $this->conf['httpsUriPrefix'] . $this->bucket . $this->conf['httpsUriSuffix'] . '/' . $remoteFileName)); if (isset($body['width'])) { $r['width'] = $body['width']; } if (isset($body['height'])) { $r['height'] = $body['height']; } return $r; } throw new Exception($body['error'], $code); }
/** * Execute the request using the PECL HTTP extension. (recommended) * * @param Request $request Request to execute * @return Response */ protected function _http_execute(Request $request) { $http_method_mapping = array(HTTP_Request::GET => HTTPRequest::METH_GET, HTTP_Request::HEAD => HTTPRequest::METH_HEAD, HTTP_Request::POST => HTTPRequest::METH_POST, HTTP_Request::PUT => HTTPRequest::METH_PUT, HTTP_Request::DELETE => HTTPRequest::METH_DELETE, HTTP_Request::OPTIONS => HTTPRequest::METH_OPTIONS, HTTP_Request::TRACE => HTTPRequest::METH_TRACE, HTTP_Request::CONNECT => HTTPRequest::METH_CONNECT); // Create an http request object $http_request = new HTTPRequest($request->uri(), $http_method_mapping[$request->method()]); // Set custom options $http_request->setOptions($this->_options); // Set headers $http_request->setHeaders($request->headers()->getArrayCopy()); // Set cookies $http_request->setCookies($request->cookie()); // Set body $http_request->setBody($request->body()); try { $http_request->send(); } catch (HTTPRequestException $e) { throw new Kohana_Request_Exception($e->getMessage()); } catch (HTTPMalformedHeaderException $e) { throw new Kohana_Request_Exception($e->getMessage()); } catch (HTTPEncodingException $e) { throw new Kohana_Request_Exception($e->getMessage()); } // Create the response $response = $request->create_response(); // Build the response $response->status($http_request->getResponseCode())->headers($http_request->getResponseHeader())->cookie($http_request->getResponseCookies())->body($http_request->getResponseBody()); return $response; }
function notifyComment() { global $database, $service, $blog, $defaultURL; $blogid = getBlogId(); $sql = "SELECT\n\t\t\t\tCN.*,\n\t\t\t\tCNQ.id AS queueId,\n\t\t\t\tCNQ.commentid AS commentid,\n\t\t\t\tCNQ.sendstatus AS sendstatus,\n\t\t\t\tCNQ.checkdate AS checkdate,\n\t\t\t\tCNQ.written AS queueWritten\n\t\t\tFROM\n\t\t\t\t{$database['prefix']}CommentsNotifiedQueue AS CNQ\n\t\t\tLEFT JOIN\n\t\t\t\t{$database['prefix']}Comments AS CN ON CNQ.commentid = CN.id\n\t\t\tWHERE\n\t\t\t\tCNQ.sendstatus = 0\n\t\t\t\tand CN.parent is not null\n\t\t\tORDER BY CNQ.id ASC LIMIT 1 OFFSET 0"; $queue = POD::queryRow($sql); if (empty($queue) && empty($queue['queueId'])) { return false; } $comments = POD::queryRow("SELECT * FROM {$database['prefix']}Comments WHERE blogid = {$blogid} AND id = {$queue['commentid']}"); if (empty($comments['parent']) || $comments['secret'] == 1) { POD::execute("DELETE FROM {$database['prefix']}CommentsNotifiedQueue WHERE id={$queue['queueId']}"); return false; } $parentComments = POD::queryRow("SELECT * FROM {$database['prefix']}Comments WHERE blogid = {$blogid} AND id = {$comments['parent']}"); if (empty($parentComments['homepage'])) { POD::execute("DELETE FROM {$database['prefix']}CommentsNotifiedQueue WHERE id={$queue['queueId']}"); return false; } $entry = POD::queryRow("SELECT * FROM {$database['prefix']}Entries WHERE blogid = {$blogid} AND id={$comments['entry']}"); if (is_null($entry)) { $r1_comment_check_url = rawurlencode("{$defaultURL}/guestbook/" . $parentComments['id'] . "#guestbook" . $parentComments['id']); $r2_comment_check_url = rawurlencode("{$defaultURL}/guestbook/" . $comments['id'] . "#guestbook" . $comments['id']); $entry['title'] = _textf('%1 블로그의 방명록', $blog['title']); $entryPermaLink = "{$defaultURL}/guestbook/"; $entry['id'] = 0; } else { $r1_comment_check_url = rawurlencode("{$defaultURL}/" . ($blog['useSloganOnPost'] ? "entry/{$entry['slogan']}" : $entry['id']) . "#comment" . $parentComments['id']); $r2_comment_check_url = rawurlencode("{$defaultURL}/" . ($blog['useSloganOnPost'] ? "entry/{$entry['slogan']}" : $entry['id']) . "#comment" . $comments['id']); $entryPermaLink = "{$defaultURL}/" . ($blog['useSloganOnPost'] ? "entry/{$entry['slogan']}" : $entry['id']); } $data = "url=" . rawurlencode($defaultURL) . "&mode=fb" . "&s_home_title=" . rawurlencode($blog['title']) . "&s_post_title=" . rawurlencode($entry['title']) . "&s_name=" . rawurlencode($comments['name']) . "&s_no=" . rawurlencode($comments['entry']) . "&s_url=" . rawurlencode($entryPermaLink) . "&r1_name=" . rawurlencode($parentComments['name']) . "&r1_no=" . rawurlencode($parentComments['id']) . "&r1_pno=" . rawurlencode($comments['entry']) . "&r1_rno=0" . "&r1_homepage=" . rawurlencode($parentComments['homepage']) . "&r1_regdate=" . rawurlencode($parentComments['written']) . "&r1_url=" . $r1_comment_check_url . "&r2_name=" . rawurlencode($comments['name']) . "&r2_no=" . rawurlencode($comments['id']) . "&r2_pno=" . rawurlencode($comments['entry']) . "&r2_rno=" . rawurlencode($comments['parent']) . "&r2_homepage=" . rawurlencode($comments['homepage']) . "&r2_regdate=" . rawurlencode($comments['written']) . "&r2_url=" . $r2_comment_check_url . "&r1_body=" . rawurlencode($parentComments['comment']) . "&r2_body=" . rawurlencode($comments['comment']); if (strpos($parentComments['homepage'], "http://") === false) { $homepage = 'http://' . $parentComments['homepage']; } else { $homepage = $parentComments['homepage']; } $request = new HTTPRequest('POST', $homepage); $request->contentType = 'application/x-www-form-urlencoded; charset=utf-8'; $request->content = $data; if ($request->send()) { $xmls = new XMLStruct(); if ($xmls->open($request->responseText)) { $result = $xmls->selectNode('/response/error/'); if ($result['.value'] != '1' && $result['.value'] != '0') { $homepage = rtrim($homepage, '/') . '/index.php'; $request = new HTTPRequest('POST', $homepage); $request->contentType = 'application/x-www-form-urlencoded; charset=utf-8'; $request->content = $data; if ($request->send()) { } } } } else { } POD::execute("DELETE FROM {$database['prefix']}CommentsNotifiedQueue WHERE id={$queue['queueId']}"); }
function importOPMLFromURL($blogid, $url) { global $database, $service; $request = new HTTPRequest($url); if (!$request->send()) { return array('error' => 1); } $result = importOPMLFromFile($blogid, $request->responseText); if ($result[0] == 0) { return array('error' => 0, 'total' => $result[1]['total'], 'success' => $result[1]['success']); } else { return array('error' => $result[0] + 1); } }
function notifyComment() { $blogid = getBlogId(); $context = Model_Context::getInstance(); $pool = DBModel::getInstance(); $pool->init("CommentsNotifiedQueue"); $pool->setAlias("CommentsNotifiedQueue", "CNQ"); $pool->setAlias("Comments", "CN"); $pool->join("Comments", "left", array(array("CNQ.commentid", "eq", "CN.id"))); $pool->setQualifier("CNQ.sendstatus", "eq", 0); $pool->setQualifier("CN.parent", "neq", null); $pool->setOrder("CNQ.id", "asc"); $pool->setLimit(1); $queue = $pool->getRow("CN.*,\n\t\t\t\tCNQ.id AS queueId,\n\t\t\t\tCNQ.commentid AS commentid,\n\t\t\t\tCNQ.sendstatus AS sendstatus,\n\t\t\t\tCNQ.checkdate AS checkdate,\n\t\t\t\tCNQ.written AS queueWritten"); if (empty($queue) && empty($queue['queueId'])) { return false; } $pool->init("Comments"); $pool->setQualifier("blogid", "eq", $blogid); $pool->setQualifier("id", "eq", $queue['commentid']); $comments = $pool->getRow(); if (empty($comments['parent']) || $comments['secret'] == 1) { $pool->init("CommentsNotifiedQueue"); $pool->setQualifier("id", "eq", $queue['queueId']); $pool->delete(); return false; } $pool->init("Comments"); $pool->setQualifier("blogid", "eq", $blogid); $pool->setQualifier("id", "eq", $queue['parent']); $parentComments = $pool->getRow(); if (empty($parentComments['homepage'])) { $pool->init("CommentsNotifiedQueue"); $pool->setQualifier("id", "eq", $queue['queueId']); $pool->delete(); return false; } $pool->init("Entries"); $pool->setQualifier("blogid", "eq", $blogid); $pool->setQualifier("id", "eq", $comments['entry']); $entry = $pool->getRow(); if (is_null($entry)) { $r1_comment_check_url = rawurlencode($context->getProperty('uri.default') . "/guestbook/" . $parentComments['id'] . "#guestbook" . $parentComments['id']); $r2_comment_check_url = rawurlencode($context->getProperty('uri.default') . "/guestbook/" . $comments['id'] . "#guestbook" . $comments['id']); $entry['title'] = _textf('%1 블로그의 방명록', $context->getProperty('blog.title')); $entryPermaLink = $context->getProperty('uri.default') . "/guestbook/"; $entry['id'] = 0; } else { $r1_comment_check_url = rawurlencode($context->getProperty('uri.default') . "/" . ($context->getProperty('blog.useSloganOnPost') ? "entry/{$entry['slogan']}" : $entry['id']) . "#comment" . $parentComments['id']); $r2_comment_check_url = rawurlencode($context->getProperty('uri.default') . "/" . ($context->getProperty('blog.useSloganOnPost') ? "entry/{$entry['slogan']}" : $entry['id']) . "#comment" . $comments['id']); $entryPermaLink = $context->getProperty('uri.default') . "/" . ($context->getProperty('blog.useSloganOnPost') ? "entry/{$entry['slogan']}" : $entry['id']); } $data = "url=" . rawurlencode($context->getProperty('uri.default')) . "&mode=fb" . "&s_home_title=" . rawurlencode($context->getProperty('blog.title')) . "&s_post_title=" . rawurlencode($entry['title']) . "&s_name=" . rawurlencode($comments['name']) . "&s_no=" . rawurlencode($comments['entry']) . "&s_url=" . rawurlencode($entryPermaLink) . "&r1_name=" . rawurlencode($parentComments['name']) . "&r1_no=" . rawurlencode($parentComments['id']) . "&r1_pno=" . rawurlencode($comments['entry']) . "&r1_rno=0" . "&r1_homepage=" . rawurlencode($parentComments['homepage']) . "&r1_regdate=" . rawurlencode($parentComments['written']) . "&r1_url=" . $r1_comment_check_url . "&r2_name=" . rawurlencode($comments['name']) . "&r2_no=" . rawurlencode($comments['id']) . "&r2_pno=" . rawurlencode($comments['entry']) . "&r2_rno=" . rawurlencode($comments['parent']) . "&r2_homepage=" . rawurlencode($comments['homepage']) . "&r2_regdate=" . rawurlencode($comments['written']) . "&r2_url=" . $r2_comment_check_url . "&r1_body=" . rawurlencode($parentComments['comment']) . "&r2_body=" . rawurlencode($comments['comment']); if (strpos($parentComments['homepage'], "http://") === false) { $homepage = 'http://' . $parentComments['homepage']; } else { $homepage = $parentComments['homepage']; } $request = new HTTPRequest('POST', $homepage); $request->contentType = 'application/x-www-form-urlencoded; charset=utf-8'; $request->content = $data; if ($request->send()) { $xmls = new XMLStruct(); if ($xmls->open($request->responseText)) { $result = $xmls->selectNode('/response/error/'); if ($result['.value'] != '1' && $result['.value'] != '0') { $homepage = rtrim($homepage, '/') . '/index.php'; $request = new HTTPRequest('POST', $homepage); $request->contentType = 'application/x-www-form-urlencoded; charset=utf-8'; $request->content = $data; if ($request->send()) { } } } } $pool->init("CommentsNotifiedQueue"); $pool->setQualifier("id", "eq", $queue['queueId']); $pool->delete(); }
/** * 发送notification或message。请阅读友盟文档。 */ public function send($data) { $token = $this->grantToken(); $newData = $data; foreach ($token as $k => $v) { $newData[$k] = $v; } //必填 消息发送类型,其值为unicast,listcast,broadcast,groupcast或customizedcast if (!isset($data['type'])) { throw new Exception('need param: type'); } // 可选 当type=customizedcast时,开发者填写自己的alias,友盟根据alias进行反查找,得到对应的device_token。多个alias时用英文逗号分,不能超过50个。 if (isset($data['alias']) && !empty($data['alias'])) { if (is_array($data['alias'])) { $newData['alias'] = implode(',', $data['alias']); } else { $newData['alias'] = $data['alias']; } } // 必填 消息类型,值为notification或者message if (!isset($data['payload']['display_type'])) { $newData['payload']['display_type'] = 'notification'; } // 必填 通知栏提示文字。但实际没有用,todo确认 if (!isset($data['payload']['body']['ticker'])) { $newData['payload']['body']['ticker'] = $data['payload']['body']['title']; } //可选 消息描述。用于友盟推送web管理后台,便于查看。 if (!isset($data['description'])) { $newData['description'] = $data['payload']['body']['title']; } $defaultTrueParams = array('play_vibrate', 'play_lights', 'play_sound'); foreach ($defaultTrueParams as $one) { if (isset($data['payload']['body'][$one]) && ($data['payload']['body'][$one] == false || $data['payload']['body'][$one] == 'false')) { $newData['payload']['body'][$one] = 'false'; } } $http = new \HTTPRequest($this->conf['api_uri_prefix'] . 'api/send', HTTP_METH_POST); $http->setBody(json_encode($newData)); $http->send(); $body = $http->getResponseBody(); if ($http->getResponseCode() != 200) { throw new Exception($body); } $tmp = json_decode($body, true); if (!isset($tmp['ret']) || $tmp['ret'] != 'SUCCESS') { throw new Exception($body); } return true; }
// LiveAddress API expects JSON input by default, but you could send XML // if you set the Content-Type header to "text/xml". $post = json_encode($addresses); // Prepare the POST request, and set the body of it. $request = new HTTPRequest($url, HTTP_METH_POST); $request->setBody($post); // Simple statistic variables $max = 0; $min = 99999999; $sum = 0; $requests = 100; echo "<pre>"; // Do the requests, and time it for ($i = 0; $i < $requests; $i++) { $start = microtime(true); $request->send(); // In a real case, you'd call setBody() before this, to do the next 100 addresses $end = microtime(true); $ms = ($end - $start) * 1000; // For the record, you can get the response with: // $response = $request->getResponseBody(); // Then json_decode() to use the values in PHP. $max = $ms > $max ? $ms : $max; $min = $ms < $min ? $ms : $min; $sum += $ms; echo $ms . "<br>"; } // Show the cumulative results echo "<br><b>MAX:</b> {$max}ms<br>"; echo "<b>MIN:</b> {$min}ms<br>"; echo "<b>AVG:</b> " . $sum / $requests . "ms<br>";
function getRDFfromURL($url) { requireComponent('Needlworks.PHP.HTTPRequest'); $request = new HTTPRequest($url); if (!$request->send() || !$request->responseText) { return false; } if (!preg_match('!<rdf:RDF\\s+([^>]+)>\\s*(<rdf:Description\\s+([^>]+)>)\\s*</rdf:RDF>!s', $request->responseText, $match)) { return false; } if (class_exists('DOMDocument')) { $doc = DOMDocument::loadXML($match[0]); if (!$doc) { return false; } $desc = $doc->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'Description'); $desc = $desc->item(0); if ($desc === null) { return false; } return array('title' => $desc->getAttributeNS('http://purl.org/dc/elements/1.1/', 'title'), 'url' => $desc->getAttributeNS('http://purl.org/dc/elements/1.1/', 'identifier'), 'trackbackURL' => $desc->getAttributeNS('http://madskills.com/public/xml/rss/module/trackback/', 'ping')); } else { preg_match_all('/(\\S+?)=(["\']?)(.*?)\\2/', $match[1], $attribs, PREG_SET_ORDER); $namespace = array('rdf' => 'rdf', 'dc' => 'dc', 'trackback' => 'trackback'); foreach ($attribs as $attrib) { if (substr(strtolower($attrib[1]), 0, 6) == 'xmlns:') { $name = substr($attrib[1], 6); switch (trim($attrib[3])) { case 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': $namespace['rdf'] = $name; break; case 'http://purl.org/dc/elements/1.1/': $namespace['dc'] = $name; break; case 'http://madskills.com/public/xml/rss/module/trackback/': $namespace['trackback'] = $name; break; } } } preg_match_all('/(\\S+?)=(["\']?)(.*?)\\2/', $match[2], $attribs, PREG_SET_ORDER); $result = array('title' => null, 'url' => null, 'trackbackURL' => null); foreach ($attribs as $attrib) { switch ($attrib[1]) { case $namespace['dc'] . ':title': $result['title'] = $attrib[3]; break; case $namespace['dc'] . ':identifier': $result['url'] = $attrib[3]; break; case $namespace['trackback'] . ':ping': $result['trackbackURL'] = $attrib[3]; } } return isset($result['trackbackURL']) ? $result : false; } }
header("Content-type: text/html; charset=utf-8"); error_reporting(E_ALL | E_NOTICE); $newsRSS = ""; $CacheDir = "cache/"; $LineLength = 40; $ReturnData = new stdClass(); $QuotesData = ""; // choose a RSS host $Site = $RSS[rand(0, count($RSS) - 1)]; // load news file if older than 15 minutes $time = file_exists($CacheDir . $Site["cache"]) ? filemtime($CacheDir . $Site["cache"]) : 0; if ($time < time() - 15 * 60 || true) { $fp = fopen($CacheDir . $Site["cache"], "w"); try { $hrp = new HTTPRequest($Site["url"]); $hrp->send(); } catch (HttpException $x) { echo $x; } $newsRSS = $hrp->getResponseBody(); fwrite($fp, $newsRSS); fclose($fp); } else { $newsRSS = file_get_contents($CacheDir . $Site["cache"]); } $news = simplexml_load_string(trim($newsRSS)); $QuotesData .= "<img src=\"" . $Site["logo"] . "\" id='content-logo'/>"; $QuotesData .= "<ul>"; $i = 1; foreach ($news->channel->item as $k => $it) { if ($i > 4) {
<?php /// Copyright (c) 2004-2015, Needlworks / Tatter Network Foundation /// All rights reserved. Licensed under the GPL. /// See the GNU General Public License for more details. (/documents/LICENSE, /documents/COPYRIGHT) $IV = array('GET' => array('url' => array('url'))); require ROOT . '/library/preprocessor.php'; if (preg_match('/\\.jpe?g/i', $_GET['url'])) { header('Content-type: image/jpeg'); } else { if (preg_match('/\\.gif/i', $_GET['url'])) { header('Content-type: image/gif'); } else { if (preg_match('/\\.png/i', $_GET['url'])) { header('Content-type: image/png'); } } } $request = new HTTPRequest($_GET['url']); if ($request->send()) { echo $request->responseText; } else { Respond::NotFoundPage(); }
finish(_t('업로드가 취소되었거나 업로드 용량 제한을 초과하였습니다.')); } $backup = $_FILES['backupPath']['tmp_name']; break; case 'web': if (!file_exists(__TEXTCUBE_CACHE_DIR__ . '/import')) { mkdir(__TEXTCUBE_CACHE_DIR__ . '/import'); @chmod(__TEXTCUBE_CACHE_DIR__ . '/import', 0777); } if (!is_dir(__TEXTCUBE_CACHE_DIR__ . '/import')) { finish(_t('백업파일을 저장할 공간에 권한이 없습니다.')); } $request = new HTTPRequest($_POST['backupURL']); $backup = __TEXTCUBE_CACHE_DIR__ . "/import/{$blogid}.xml"; $request->pathToSave = $backup; if (!$request->send()) { finish(_t('백업파일이 손상되었거나 가져올 수 없습니다.')); } break; } $migrational = false; $items = 0; $item = 0; $xmls = new XMLStruct(); set_time_limit(0); setProgress(0, _t('백업파일을 확인하고 있습니다.')); $xmls->setStream('/blog/setting/banner/content'); $xmls->setStream('/blog/post/attachment/content'); $xmls->setStream('/blog/notice/attachment/content'); $xmls->setStream('/blog/keyword/attachment/content'); $xmls->setConsumer('scanner');