/** * Constructs a book dialog * $action - GET or POST action to take. * $inclusions - NULL (in which case it does nothing), or an array of book IDs to include. * $exclusions - NULL (in which case it does nothing), or an array of book IDs to exclude. */ public function __construct($header, $info_top, $info_bottom, $action, $inclusions, $exclusions) { $this->view = new Assets_View(__FILE__); $caller = $_SERVER["PHP_SELF"] . "?" . http_build_query(array()); $this->view->view->caller = $caller; $this->view->view->header = $header; $this->view->view->info_top = $info_top; $this->view->view->info_bottom = $info_bottom; $this->view->view->action = $action; $database_books = Database_Books::getInstance(); $book_ids = $database_books->getIDs(); if (is_array($inclusions)) { $book_ids = $inclusions; } if (is_array($exclusions)) { $book_ids = array_diff($book_ids, $exclusions); $book_ids = array_values($book_ids); } foreach ($book_ids as $id) { $book_names[] = $database_books->getEnglishFromId($id); } $this->view->view->book_ids = $book_ids; $this->view->view->book_names = $book_names; $this->view->render("books2.php"); Assets_Page::footer(); die; }
function post_location_request($url, $data) { /* $data_str = urlencode(http_build_query($data)); header("Host: $host\r\n"); header("POST $path HTTP/1.1\r\n"); header("Content-type: application/x-www-form-urlencoded\r\n"); header("Content-length: " . strlen($data_str) . "\r\n"); header("Connection: close\r\n\r\n"); header($data_str); exit();*/ $CI =& get_instance(); $params = explode("&", urldecode(http_build_query($data))); $retHTML = ''; if (!$CI->is_pjax) { $retHTML .= "<html>\n<body onLoad=\"document.send_form.submit();\">\n"; } $retHTML .= '<form method="post" name="send_form" id="send_form" action="' . $url . '">'; foreach ($params as $string) { list($key, $value) = explode("=", $string); $retHTML .= "<input type=\"hidden\" name=\"" . $key . "\" value=\"" . addslashes($value) . "\">\n"; } if ($CI->is_pjax) { $retHTML .= '</form><script>document.getElementById("send_form").submit();</script>'; } else { $retHTML .= "</form>\n</body>\n</html>"; } print $retHTML; exit; }
function mm_ux_log($args = array()) { $url = "https://ssl.google-analytics.com/collect"; global $title; if (empty($_SERVER['REQUEST_URI'])) { return; } $path = explode('wp-admin', $_SERVER['REQUEST_URI']); if (empty($path) || empty($path[1])) { $path = array("", " "); } $defaults = array('v' => '1', 'tid' => 'UA-39246514-3', 't' => 'pageview', 'cid' => md5(get_option('siteurl')), 'uid' => md5(get_option('siteurl') . get_current_user_id()), 'cn' => 'mojo_wp_plugin', 'cs' => 'mojo_wp_plugin', 'cm' => 'plugin_admin', 'ul' => get_locale(), 'dp' => $path[1], 'sc' => '', 'ua' => @$_SERVER['HTTP_USER_AGENT'], 'dl' => $path[1], 'dh' => get_option('siteurl'), 'dt' => $title, 'ec' => '', 'ea' => '', 'el' => '', 'ev' => ''); if (isset($_SERVER['REMOTE_ADDR'])) { $defaults['uip'] = $_SERVER['REMOTE_ADDR']; } $params = wp_parse_args($args, $defaults); $test = get_transient('mm_test', ''); if (isset($test['key']) && isset($test['name'])) { $params['cm'] = $params['cm'] . "_" . $test['name'] . "_" . $test['key']; } //use test account for testing if (defined('WP_DEBUG') && WP_DEBUG) { $params['tid'] = 'UA-19617272-27'; } $z = wp_rand(0, 1000000000); $query = http_build_query(array_filter($params)); $args = array('body' => $query, 'method' => 'POST', 'blocking' => false); $url = add_query_arg(array('z' => $z), $url); wp_remote_post($url, $args); }
/** * Form a redirect URI to send the user to. * * @param array $scopes * * @return string */ public function redirect($scopes = []) { $url = self::$base_url . 'oauth/authorize'; $scopes = empty($scopes) ? null : implode(' ', $scopes); $params = ['response_type' => 'code', 'redirect_uri' => $this->callback, 'client_id' => $this->client_id, 'scope' => $scopes]; return $url . '?' . http_build_query($params, null, '&', PHP_QUERY_RFC3986); }
/** * Returns a json. * * @param string $api_path The api path * @param string|array $file The filepath (string) or fileinfo ['filepath' => '', 'filetype' => ''] (array) * * @return string */ public function Put($api, $file = '', $query = []) { $ch = $this->getHandler(); $query = is_array($query) ? http_build_query($query) : $query; $this->url = $this->api_path . $api . ($query ? "?{$query}" : ''); if (is_array($file)) { if (isset($file['filepath'])) { $fp = fopen($file['filepath'], 'r'); } elseif (isset($file['fp'])) { $fp = $file['fp']; } $this->headers[] = "Content-Type: {$file['filetype']}"; } else { $fp = fopen($file, 'r'); if ($img_info = getimagesize($file)) { // get mime type wher file is a image $this->headers[] = "Content-Type: {$img_info['mime']}"; } } curl_setopt($ch, CURLOPT_PUT, 1); curl_setopt($ch, CURLOPT_INFILE, $fp); if ($this->headers) { curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); } return $this->run($ch); }
private function curlSetopts($ch, $method, $payload, $request_headers) { curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 3); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_USERAGENT, 'HAC'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); if ($this->debug) { curl_setopt($ch, CURLOPT_VERBOSE, true); } if ('GET' == $method) { curl_setopt($ch, CURLOPT_HTTPGET, true); } else { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if (!empty($request_headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers); } if (!empty($payload)) { if (is_array($payload)) { $payload = http_build_query($payload); } curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); } } }
/** * Return the url for the API request * * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event * * @return string */ public function getApiRequestUrl(Event $event) { $params = $event->getCustomParams(); $query = trim(implode(" ", $params)); $querystringParams = array('q' => $query, 'appid' => $this->appId); return sprintf("%s?%s", $this->apiUrl, http_build_query($querystringParams)); }
public function connectUrl($params = array()) { $query = Braintree_Util::camelCaseToDelimiterArray($params, '_'); $query['client_id'] = $this->_config->getClientId(); $url = $this->_config->baseUrl() . '/oauth/connect?' . http_build_query($query); return $this->signUrl($url); }
function format() { $base = $_REQUEST['_router_']; if ($this->curpage > 1) { $html[] = "<a href='{$this->router}'>首页</a>"; } $pages = array(); for ($i = 1; $i <= $this->pagenum; $i++) { if ($i <= 3 || abs($this->curpage - $i) < 3 || $this->pagenum - $i <= 3) { $pages[] = $i; continue; } } $html = array(); foreach ($pages as $i => $p) { if ($i > 1 && $p - $pages[$i - 1] > 1) { $html[] = '...'; } else { $this->query['page'] = $p; $url = $this->router; $url .= strpos($url, '?') ? '&' : '?'; $url .= http_build_query($this->query); //echo $url; $html[] = "<a href='{$url}'>{$p}</a>"; } } return "共{$this->records}记录,第{$this->curpage}/{$this->pagenum}页 " . implode('', $html); }
/** * @param string $Name * @param $Path * @param IIconInterface $Icon * @param array $Data * @param bool|string $ToolTip */ public function __construct($Name, $Path, IIconInterface $Icon = null, $Data = array(), $ToolTip = true) { $this->Name = $Name; $this->Template = $this->getTemplate(__DIR__ . '/External.twig'); $this->Template->setVariable('ElementName', $Name); $this->Template->setVariable('ElementType', 'btn btn-default'); if (null === $Icon) { $Icon = new Extern(); } $this->Template->setVariable('ElementIcon', $Icon); if (!empty($Data)) { $Signature = (new Authenticator(new Get()))->getAuthenticator(); $Data = '?' . http_build_query($Signature->createSignature($Data, $Path)); } else { $Data = ''; } $this->Template->setVariable('ElementPath', $Path . $Data); if ($ToolTip) { if (is_string($ToolTip)) { $this->Template->setVariable('ElementToolTip', $ToolTip); } else { $this->Template->setVariable('ElementToolTip', $Path); } } }
/** * Handles method spoofing. * * Callers should use this method as one of the first methods in their * scripts. This method does the following: * - The <em>real</em> HTTP method must be POST. * - Modify "environment variables" <var>$_SERVER['QUERY_STRING']</var>, * <var>$_SERVER['REQUEST_URI']</var>, * <var>$_SERVER['REQUEST_METHOD']</var>, * <var>$_SERVER['CONTENT_LENGTH']</var>, * <var>$_SERVER['CONTENT_TYPE']</var> as necessary. * @return void */ public static function handle_method_spoofing() { if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_GET['http_method'])) { $http_method = strtoupper($_GET['http_method']); unset($_GET['http_method']); if ($http_method === 'GET' && strstr(@$_SERVER['CONTENT_TYPE'], 'application/x-www-form-urlencoded') !== false) { $_GET = $_POST; $_POST = array(); } elseif ($http_method === 'PUT' && strstr(@$_SERVER['CONTENT_TYPE'], 'application/x-www-form-urlencoded') !== false && isset($_POST['entity'])) { self::$inputhandle = tmpfile(); fwrite(self::$inputhandle, $_POST['entity']); fseek(self::$inputhandle, 0); $_SERVER['CONTENT_LENGTH'] = strlen($_POST['entity']); unset($_POST['entity']); if (isset($_POST['http_content_type'])) { $_SERVER['CONTENT_TYPE'] = $_POST['http_content_type']; unset($_POST['http_content_type']); } else { $_SERVER['CONTENT_TYPE'] = 'application/octet-stream'; } } elseif ($http_method === 'PUT' && strstr(@$_SERVER['CONTENT_TYPE'], 'multipart/form-data') !== false && @$_FILES['entity']['error'] === UPLOAD_ERR_OK) { self::$inputhandle = fopen($_FILES['entity']['tmp_name'], 'r'); $_SERVER['CONTENT_LENGTH'] = $_FILES['entity']['size']; $_SERVER['CONTENT_TYPE'] = $_FILES['entity']['type']; } $_SERVER['QUERY_STRING'] = http_build_query($_GET); $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')); if ($_SERVER['QUERY_STRING'] != '') { $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING']; } $_SERVER['REQUEST_METHOD'] = $http_method; } }
/** * methodName * * @param string $url * @param array $paramToAdd * @param array $paramToRemove * @return string */ private static function urlParamsResolver($url, $paramToAdd = []) { $getArray = $_GET; $currentUrl = getUrl(); $queryString = http_build_query(array_merge(is_array($getArray) ? $getArray : [$getArray], $paramToAdd)); return $currentUrl . ($queryString ? '?' . $queryString : ''); }
public function checkUser() { if (isset($_REQUEST['code'])) { $keys = array(); $keys['code'] = $_REQUEST['code']; $keys['redirect_uri'] = U('public/Widget/displayAddons', array('type' => $_REQUEST['type'], 'addon' => 'Login', 'hook' => 'no_register_display')); try { $token = $this->_oauth->getAccessToken('code', $keys); } catch (OAuthException $e) { $token = null; } } else { $keys = array(); $keys['refresh_token'] = $_REQUEST['code']; try { $token = $this->_oauth->getAccessToken('token', $keys); } catch (OAuthException $e) { $token = null; } } if ($token) { setcookie('weibojs_' . $this->_oauth->client_id, http_build_query($token)); $_SESSION['sina']['access_token']['oauth_token'] = $token['access_token']; $_SESSION['sina']['access_token']['oauth_token_secret'] = $token['refresh_token']; $_SESSION['sina']['expire'] = time() + $token['expires_in']; $_SESSION['sina']['uid'] = $token['uid']; $_SESSION['open_platform_type'] = 'sina'; return $token; } else { return false; } }
public function actionPost($url, $params, $multipart = FALSE, $version = CURL_HTTP_VERSION_NONE) { if (function_exists('curl_init')) { $ch = curl_init(); $timeout = 60; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTP_VERSION, $version); curl_setopt($ch, CURLOPT_POST, TRUE); if ($multipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); } curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $data = curl_exec($ch); if ($data === FALSE) { throw new Exception(curl_errno($ch)); } curl_close($ch); return $data; } else { return FALSE; } }
public static function anchorActionDelete($key) { $params = array('db' => Request::factory()->getDb(), 'cmd' => 'DEL ' . urlencode($key), 'back' => Request::factory()->getBack()); $url = 'http://' . Request::factory()->getServerName() . '/?' . http_build_query($params); $title = 'DEL ' . htmlspecialchars($key); return '<a class="cmd delete" href="' . $url . '" title="' . $title . '">Delete</a>'; }
/** * Sends a request to the REST API service and does initial processing * on the response. * * @param string $op Name of the operation for the request * @param array $query Query data for the request (optional) * @throws Zend_Service_Exception * @return DOMDocument Parsed XML response */ protected function _makeRequest($op, $query = null) { if ($query != null) { $query = array_diff($query, array_filter($query, 'is_null')); $query = '?' . http_build_query($query); } $this->_http->setUri($this->_baseUri . $op . '.do' . $query); $response = $this->_http->request('GET'); if ($response->isSuccessful()) { $doc = new DOMDocument(); $doc->loadXML($response->getBody()); $xpath = new DOMXPath($doc); $list = $xpath->query('/status/code'); if ($list->length > 0) { $code = $list->item(0)->nodeValue; if ($code != 0) { $list = $xpath->query('/status/message'); $message = $list->item(0)->nodeValue; /** * @see Zend_Service_Exception */ require_once 'Zend/Service/Exception.php'; throw new Zend_Service_Exception($message, $code); } } return $doc; } /** * @see Zend_Service_Exception */ require_once 'Zend/Service/Exception.php'; throw new Zend_Service_Exception($response->getMessage(), $response->getStatus()); }
private function executeCurl($url, array $params) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); if (isset($params["POST"])) { curl_setopt($ch, CURLOPT_POST, 1); $queryString = urlencode(http_build_query($params["POST"])); curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString); } if (isset($params["PUT"])) { //@TODO throw new Exception('The PUT is currently not supported'); } if (isset($params["GET"])) { curl_setopt($ch, CURLOPT_HTTPGET, 1); $queryString = urlencode(http_build_query($params["GET"])); curl_setopt($ch, CURLOPT_URL, $url . '?' . $queryString); } if (isset($params["HEADERS"])) { curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $params["HEADERS"]); } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); curl_close($ch); return $response; }
function postContent() { if (!($user = \Idno\Core\site()->session()->currentUser())) { $this->setResponse(403); echo 'You must be logged in to approve IndieAuth requests.'; exit; } $me = $this->getInput('me'); $client_id = $this->getInput('client_id'); $redirect_uri = $this->getInput('redirect_uri'); $state = $this->getInput('state'); $scope = $this->getInput('scope'); if (!empty($me) && parse_url($me, PHP_URL_HOST) == parse_url($user->getURL(), PHP_URL_HOST)) { $indieauth_codes = $user->indieauth_codes; if (empty($indieauth_codes)) { $indieauth_codes = array(); } $code = md5(rand(0, 99999) . time() . $user->getUUID() . $client_id . $state . rand(0, 999999)); $indieauth_codes[$code] = array('me' => $me, 'redirect_uri' => $redirect_uri, 'scope' => $scope, 'state' => $state, 'client_id' => $client_id, 'issued_at' => time(), 'nonce' => mt_rand(1000000, pow(2, 30))); $user->indieauth_codes = $indieauth_codes; $user->save(); if (strpos($redirect_uri, '?') === false) { $redirect_uri .= '?'; } else { $redirect_uri .= '&'; } $redirect_uri .= http_build_query(array('code' => $code, 'state' => $state, 'me' => $me)); $this->forward($redirect_uri); } }
/** * Start the commandline to send a newsletter * This is offloaded because it could take a while and/or resources * * @param Newsletter $entity Newsletter entity to be processed * * @return void */ function newsletter_start_commandline_sending(Newsletter $entity) { if (!empty($entity) && elgg_instanceof($entity, "object", Newsletter::SUBTYPE)) { // prepare commandline settings $settings = array("entity_guid" => $entity->getGUID(), "host" => $_SERVER["HTTP_HOST"], "memory_limit" => ini_get("memory_limit"), "secret" => newsletter_generate_commanline_secret($entity->getGUID())); if (isset($_SERVER["HTTPS"])) { $settings["https"] = $_SERVER["HTTPS"]; } // ini settings $ini_param = ""; $ini_file = php_ini_loaded_file(); if (!empty($ini_file)) { $ini_param = "-c " . $ini_file . " "; } // which script to run $script_location = dirname(dirname(__FILE__)) . "/procedures/cli.php"; // convert settings to commandline params $query_string = http_build_query($settings, "", " "); // start the correct commandline if (PHP_OS === "WINNT") { pclose(popen("start /B php " . $ini_param . $script_location . " " . $query_string, "r")); } else { exec("php " . $ini_param . $script_location . " " . $query_string . " > /dev/null &"); } } }
public function get_pay_url($order_info) { $this->params = array("cmdno" => "1", "date" => date("Ymd"), "bargainor_id" => $this->_config['mem_id'], "transaction_id" => $this->_config['mem_id'] . date('YmdHis') . rand(1000, 9999), "fee_type" => "1", "return_url" => $this->_config['return_url'], "attach" => "", "spbill_create_ip" => "", "bank_type" => "0", "cs" => "utf-8", "sign" => "", "desc" => $order_info['order_desc'], "sp_billno" => $order_info['order_id'], "total_fee" => $order_info['order_amount']); $sign = $this->create_sign($this->params); $this->params['sign'] = $sign; return 'http://service.tenpay.com/cgi-bin/v3.0/payservice.cgi?' . http_build_query($this->params); }
function postToIDS($url, $data) { $agent = $_SERVER["HTTP_USER_AGENT"]; $curlData = http_build_query($data); $curlData = str_replace(" ", '%20', $curlData); $curlData = str_replace("+", '%20', $curlData); $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_USERAGENT, $agent); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $curlData); $response = curl_exec($curl); echo '<!-- CURLINFO_EFFECTIVE_URL' . PHP_EOL; var_dump(curl_getinfo($curl, CURLINFO_EFFECTIVE_URL)); echo PHP_EOL . '/-->' . PHP_EOL; if ($response === false) { echo "curl error: " . curl_error($curl); } else { $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); } curl_close($curl); return $http_status; }
/** * getUser * * read User by ID * id, int: id (required) * * @return User */ public function getUser($id) { // parse inputs $resourcePath = "/user_get_two_read1"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); $formParams = array(); $headerParams['Accept'] = '*/*'; $headerParams['Content-Type'] = 'application/json'; // query params if ($id !== null) { $queryParams['id'] = $this->apiClient->toQueryValue($id); } $body = $body ?: $formParams; if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { $body = http_build_query($body); } // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); if (!$response) { return null; } $responseObject = $this->apiClient->deserialize($response, 'User'); return $responseObject; }
public function getNavigationLinks(array $data) { $prev_link = $data; $prev_link['prev'] = isset($prev_link['prev']) ? $prev_link['prev'] + 1 : 0; $navigation_links['prev'] = "?" . http_build_query($prev_link, '', '&'); $next_link = $data; $next_link['next'] = isset($next_link['next']) ? $next_link['next'] + 1 : 0; $navigation_links['next'] = "?" . http_build_query($next_link, '', '&'); $filter_type_all = $data; $filter_type_all['type'] = null; $navigation_links['filter_type_all'] = "?" . http_build_query($filter_type_all, '', '&'); $filter_type_tarefa = $data; $filter_type_tarefa['type'] = 'tarefa'; $navigation_links['filter_type_tarefa'] = "?" . http_build_query($filter_type_tarefa, '', '&'); $filter_type_agendaevent = $data; $filter_type_agendaevent['type'] = 'agendaevent'; $navigation_links['filter_type_agendaevent'] = "?" . http_build_query($filter_type_agendaevent, '', '&'); $view_today_link = $data; $view_thisweek_link = $data; $view_thismonth_link = $data; $view_today_link['view'] = 'day'; unset($view_today_link['next'], $view_today_link['prev'], $view_today_link['date']); $navigation_links['view_today_link'] = "?" . http_build_query($view_today_link, '', '&'); $view_thisweek_link['view'] = 'week'; unset($view_thisweek_link['next'], $view_thisweek_link['prev'], $view_thisweek_link['date']); $navigation_links['view_thisweek_link'] = "?" . http_build_query($view_thisweek_link, '', '&'); $view_thismonth_link['view'] = 'month'; unset($view_thismonth_link['next'], $view_thismonth_link['prev'], $view_thismonth_link['date']); $navigation_links['view_thismonth_link'] = "?" . http_build_query($view_thismonth_link, '', '&'); // echo "<pre>"; return $navigation_links; }
/** * User authorization * @param $user * @param $pass * @return void */ protected function authenticateUser($user, $pass) { if ($user && $pass) { $postParams = http_build_query(['_method' => 'POST', 'data[User][email]' => $user, 'data[User][password]' => $pass, 'data[User][save]' => '1']); $this->executeRequest([CURLOPT_URL => self::LOGIN_URL, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postParams]); } }
public function getUserInfo() { $url = 'https://api.github.com/user?' . http_build_query(array('access_token' => $this->token->access_token)); // Create a curl handle to a non-existing location $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); # timeout after 10 seconds, you can increase it curl_setopt($ch, CURLOPT_URL, $url); #set the url and get string together curl_setopt($ch, CURLOPT_USERAGENT, 'dukt-oauth'); #set the url and get string together $json = ''; if (($json = curl_exec($ch)) === false) { throw new \Exception(curl_error($ch)); } curl_close($ch); $user = json_decode($json); if (!isset($user->id)) { throw new \Exception($json); } // Create a response from the request return array('uid' => $user->id, 'nickname' => $user->login, 'name' => $user->name, 'email' => $user->email, 'urls' => array('GitHub' => 'http://github.com/' . $user->login, 'Blog' => $user->blog)); }
/** * Tests the "popular content" block. */ function testPopularContentBlock() { // Clear the block cache to load the Statistics module's block definitions. $this->container->get('plugin.manager.block')->clearCachedDefinitions(); // Visit a node to have something show up in the block. $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->blockingUser->id())); $this->drupalGet('node/' . $node->id()); // Manually calling statistics.php, simulating ajax behavior. $nid = $node->id(); $post = http_build_query(array('nid' => $nid)); $headers = array('Content-Type' => 'application/x-www-form-urlencoded'); global $base_url; $stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php'; $client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]); $client->post($stats_path, array('headers' => $headers, 'body' => $post)); // Configure and save the block. $this->drupalPlaceBlock('statistics_popular_block', array('label' => 'Popular content', 'top_day_num' => 3, 'top_all_num' => 3, 'top_last_num' => 3)); // Get some page and check if the block is displayed. $this->drupalGet('user'); $this->assertText('Popular content', 'Found the popular content block.'); $this->assertText("Today's", "Found today's popular content."); $this->assertText('All time', 'Found the all time popular content.'); $this->assertText('Last viewed', 'Found the last viewed popular content.'); // statistics.module doesn't use node entities, prevent the node language // from being added to the options. $this->assertRaw(\Drupal::l($node->label(), $node->urlInfo('canonical', ['language' => NULL])), 'Found link to visited node.'); }
public function processRequest($method = 'POST') { $params = http_build_query($this->urlParams); if (w2p_check_url($this->url)) { if (function_exists('curl_init')) { $ch = curl_init($this->url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); } else { /* * Thanks to Wez Furlong for the core of the logic for this * method to POST data via PHP without cURL * http://netevil.org/blog/2006/nov/http-post-from-php-without-curl */ $ctx = stream_context_create($params); $fp = @fopen($this->url, 'rb', false, $ctx); if (!$fp) { throw new Exception("Problem with {$url}, {$php_errormsg}"); } $response = @stream_get_contents($fp); if ($response === false) { throw new Exception("Problem reading data from {$url}, {$php_errormsg}"); } } return $response; } else { //throw an error? } }
/** * Make an api request * * @param string $resource * @param array $params * @param string $method */ public function call($resource, $params = array()) { $queryString = 'access_token=' . $this->getAccessToken(); if (!empty($params) && is_array($params)) { $queryString .= http_build_query($params); } $requestUrl = self::API_URL . $resource . '/?' . $queryString; $curl = curl_init(); $curl_options = array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $requestUrl, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => array('Accept: application/json', 'appid: nike')); curl_setopt_array($curl, $curl_options); $response = curl_exec($curl); $curl_info = curl_getinfo($curl); //@todo test for curl error if ($response === FALSE) { throw new Exception(curl_error($curl), curl_errno($curl)); } curl_close($curl); //@todo test for any non 200 response if ($curl_info['http_code'] != 200) { throw new Exception("Response: Bad response - HTTP Code:" . $curl_info['http_code']); } $jsonArray = json_decode($response); if (!is_object($jsonArray)) { throw new Exception("Response: Response was not a valid response"); } return $jsonArray; }
/** * Gets current URI without provided query parameters * * @param array $removeParameters * * @return string */ public function getCurrentUri(array $removeParameters = array()) { if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $protocol = 'https://'; } else { $protocol = 'http://'; } $currentUri = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $parts = parse_url($currentUri); $port = isset($parts['port']) && ($protocol === 'http://' && $parts['port'] !== 80 || $protocol === 'https://' && $parts['port'] !== 443) ? ':' . $parts['port'] : ''; if (empty($parts['query'])) { $query = ''; } elseif (count($removeParameters) === 0) { $query = '?' . $parts['query']; } else { $queryParameters = array(); foreach ($this->parseHttpQuery($parts['query']) as $key => $value) { if (!in_array($key, $removeParameters)) { $queryParameters[$key] = $value; } } if (count($queryParameters) > 0) { $query = '?' . http_build_query($queryParameters, null, '&'); } else { $query = ''; } } return $protocol . $parts['host'] . $port . $parts['path'] . $query; }
/** * Make API request * * @param string $method string API method to request * @param array $params Additional request parameters * @return array / boolean Response array / boolean false on failure */ public function request($method, $params = array()) { $this->_errors = array(); if (empty($method)) { //Check if API method is not empty $this->_errors = array('API method is missing'); return false; } //Our request parameters $requestParams = array('METHOD' => $method, 'VERSION' => $this->_version) + $this->_credentials; //Building our NVP string $request = http_build_query($requestParams + $params); //cURL settings $curlOptions = array(CURLOPT_URL => $this->_endPoint, CURLOPT_VERBOSE => 1, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem', CURLOPT_RETURNTRANSFER => 1, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $request); $ch = curl_init(); curl_setopt_array($ch, $curlOptions); //Sending our request - $response will hold the API response $response = curl_exec($ch); //Checking for cURL errors if (curl_errno($ch)) { $this->_errors = curl_error($ch); curl_close($ch); return false; //Handle errors } else { curl_close($ch); $responseArray = array(); parse_str($response, $responseArray); // Break the NVP string to an array return $responseArray; } }