/** * Perform request to the Alma server. * * @param string $method * The REST method to call e.g. 'patron/status'. borrCard and pinCode * are required for all request related to library patrons. * @param array $params * Query string parameters in the form of key => value. * @return DOMDocument * A DOMDocument object with the response. */ public function request($method, $params = array()) { // For use with a non-Drupal-system, we should have a way to swap // the HTTP client out. $request = drupal_http_request(url($this->base_url . $method, array('query' => $params))); if ($request->code == 200) { // Since we currently have no neat for the more advanced stuff // SimpleXML provides, we'll just use DOM, since that is a lot // faster in most cases. $doc = new DOMDocument(); $doc->loadXML($request->data); if ($doc->getElementsByTagName('status')->item(0)->getAttribute('value') == 'ok') { return $doc; } else { $message = $doc->getElementsByTagName('status')->item(0)->getAttribute('key'); switch ($message) { case '': case 'borrCardNotFound': throw new AlmaClientBorrCardNotFound('Invalid borrower credentials'); break; default: throw new AlmaClientCommunicationError('Status is not okay: ' . $message); } } } else { throw new AlmaClientHTTPError('Request error: ' . $request->code . $request->error); } }
private function sendRequest($action, $query = NULL, $type = 'GET') { $headers_string = $_COOKIE['vmapi_session_headers']; if (!empty($headers_string)) { self::$lastHeaders = json_decode($headers_string); } if (empty(self::$lastHeaders)) { // need to recreate our headers $timestamp = time(); $nonce = hash('sha1', openssl_random_pseudo_bytes(20)); $date = date('Y-m-d\\TH:i:sO', $timestamp); $digest = base64_encode(hash('sha256', $nonce . $date . self::$key, TRUE)); $header_array = array('Content-Type' => 'application/json', 'Authorization' => 'WSSE profile="UsernameToken"', 'X-WSSE' => 'UsernameToken Username="******", PasswordDigest="' . $digest . '", Nonce="' . $nonce . '", Created="' . $date . '"'); self::$lastHeaders = $header_array; // by default, expire headers in 10 minutes setcookie('vmapi_session_headers', json_encode(self::$lastHeaders), $timestamp + 600, '/'); } $json_query = json_encode($query); //print_r($json_query); $url = self::$path; $url .= '?action=' . $action; if ($query != NULL) { $url .= '&query=' . urlencode($json_query); } // upon reviewing the code for this class, drupal_http_request() is the only method // dependant upon drupal. in order to make the entire class drupal-independant // we would have to use a native PHP method for sending HTTP requests. self::$lastResponse = drupal_http_request($url, self::$lastHeaders, $type); if (self::$lastResponse->code > 200) { print_r(self::$lastResponse); } }
function takeshi_get_favicon($url) { $request = drupal_http_request($url, 'r'); if ($request) { if (preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $request->data, $matches)) { $linkUrl = html_entity_decode($matches[1]); if (substr($linkUrl, 0, 1) == '/') { $urlParts = parse_url($url); $faviconURL = $urlParts['scheme'] . '://' . $urlParts['host'] . $linkUrl; } elseif (substr($linkUrl, 0, 7) == 'http://') { $faviconURL = $linkUrl; } elseif (substr($url, -1, 1) == '/') { $faviconURL = $url . $linkUrl; } else { $faviconURL = $url . '/' . $linkUrl; } } else { $urlParts = parse_url($url); $faviconURL = $urlParts['scheme'] . '://' . $urlParts['host'] . '/favicon.ico'; } $HTTPRequest = @fopen($faviconURL, 'r'); if ($HTTPRequest) { stream_set_timeout($HTTPRequest, 0.1); $favicon = fread($HTTPRequest, 8192); $HTTPRequestData = stream_get_meta_data($HTTPRequest); fclose($HTTPRequest); if (!$HTTPRequestData['timed_out'] && strlen($favicon) < 8192) { return $faviconURL; } } } return "false"; }
private static function send_with_drupal($url, $options, $ignore_error) { ShareaholicUtilities::log($url); ShareaholicUtilities::log($options); ShareaholicUtilities::log('-----------------'); $request = array(); $result = array(); $request['method'] = isset($options['method']) ? $options['method'] : 'GET'; $request['headers'] = isset($options['headers']) ? $options['headers'] : array(); $request['max_redirects'] = isset($options['redirection']) ? $options['redirection'] : 5; $request['timeout'] = isset($options['timeout']) ? $options['timeout'] : 15; $request['headers']['User-Agent'] = isset($options['user-agent']) ? $options['user-agent'] : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0'; if (isset($options['body'])) { if (isset($request['headers']['Content-Type']) && $request['headers']['Content-Type'] === 'application/json') { $request['data'] = json_encode($options['body']); } else { $request['data'] = http_build_query($options['body']); } } else { $request['body'] = NULL; } $response = drupal_http_request($url, $request); if (isset($response->error)) { ShareaholicUtilities::log($response->error); if (!$ignore_error) { ShareaholicUtilities::log_event('CurlRequestFailure', array('error_message' => $response->error, 'url' => $url)); } return false; } $result['headers'] = $response->headers; $result['body'] = $response->data; $result['response'] = array('code' => $response->code, 'message' => $response->status_message); return $result; }
/** * Add custom PHPTemplate variable into the page template */ function ninesixtyrobots_preprocess_page(&$vars) { // Check if the theme is using Twitter. $use_twitter = theme_get_setting('use_twitter'); if (is_null($use_twitter)) { $use_twitter = 1; } // If the theme uses Twitter pull it in and display it in the slogan. if ($use_twitter) { if ($cache = cache_get('ninesixtyrobots_tweets')) { $data = $cache->data; } else { $query = theme_get_setting('twitter_search_term'); if (is_null($query)) { $query = 'lullabot'; } $query = drupal_urlencode($query); $response = drupal_http_request('http://search.twitter.com/search.json?q=' . $query); if ($response->code == 200) { $data = json_decode($response->data); // Set a 5 minute cache on retrieving tweets. // Note if this isn't updating on your site *run cron*. cache_set('ninesixtyrobots_tweets', $data, 'cache', 300); } } $tweet = $data->results[array_rand($data->results)]; // Create the actual variable finally. $vars['site_slogan'] = check_plain(html_entity_decode($tweet->text)); } }
public function import(&$form_state, $docid = NULL) { $url = $form_state['values'][$this->fieldname]; if (empty($url)) { return FALSE; } $response = drupal_http_request($url); // drupal_set_message("URL request ($url) returned status code $response->code."); if ($response->code != 200) { drupal_set_message("URL request ({$url}) returned unexpected status code {$response->code}.", 'error'); return FALSE; } // else $content = $response->data; if (empty($docid)) { $docid = hash($this->hashAlgorithm, $content); } $pubpath = $this->constructPubPath($docid); file_check_directory($pubpath, FILE_CREATE_DIRECTORY); $savename = $this->savename; if (empty($savename)) { $savename = preg_replace('{[\\#\\?].*\\Z}', '', $url); $savename = preg_replace('{\\.([^.])+\\Z}', '\\#$1', $savename); $savename = preg_replace('/[^a-zA-Z0-9_\\#-]/', '_', $savename); $savename = preg_replace('/\\#/', '.', $savename); } $destfile = "{$pubpath}/{$savename}"; file_save_data($content, $destfile, FILE_EXISTS_REPLACE); drupal_set_message(t("Saved !num bytes to file !file", array('!num' => strlen($content), '!file' => $destfile))); $this->pubpath = $pubpath; $this->docpath = $savename; return TRUE; }
function verify() { $vars = $this->ipn_vars; $this->ipn = $this->ipn_vars; $vars['cmd'] = '_notify-validate'; $options = array('headers' => array('Content-Type' => 'application/x-www-form-urlencoded'), 'method' => 'POST', 'data' => drupal_http_build_query($vars)); $result = drupal_http_request($this->ipnLink, $options); $this->ipnResult = $result->data; if (!empty($result->error)) { $this->lastError = t('IPN Validation Error: @error', array('@error' => $result->error)); return FALSE; } else { if ($result->code == 200) { if ($result->data == 'VERIFIED') { return TRUE; } else { $this->lastError = t('IPN Validation Failed: @error', array('@error' => $result->data)); return FALSE; } } else { // The server might be down, let's log an error but still pass the // validation. ms_core_log_error('ms_paypal_wps', 'The Validation Server had an error processing a request. Request: !request Response: !response', array('!request' => ms_core_print_r($options), '!response' => ms_core_print_r($result)), WATCHDOG_CRITICAL); return TRUE; } } }
public static function cachedRequest($url, array $options = array(), $cache_errors = FALSE) { $cid = static::cachedRequestGetCid($url, $options); $bin = isset($options['cache']['bin']) ? $options['cache']['bin'] : 'cache'; if ($cid && ($cache = CacheHelper::get($cid, $bin))) { return $cache->data; } else { $response = drupal_http_request($url, $options); $response->request_url = $url; $response->request_options = $options; if (!empty($response->error)) { trigger_error("Error on request to {$url}: {$response->code} {$response->error}.", E_USER_WARNING); } if (!$cache_errors && !empty($response->error)) { $cid = FALSE; } if ($cid) { $expire = static::cachedRequestGetExpire($response, $options); if ($expire !== FALSE) { cache_set($cid, $response, $bin, $expire); } } return $response; } }
public function fetch() { $this->query = $this->url . '?pid=' . $this->pid . '&noredirect=true&format=unixref&id=doi%3A' . $this->doi; $request_options = array('method' => 'POST'); $result = drupal_http_request($this->query, $request_options); if ($result->code != 200) { drupal_set_message(t('HTTP error: !error when trying to contact crossref.org for XML input', array('!error' => $result->code)), 'error'); return; } if (empty($result->data)) { drupal_set_message(t('Did not get any data from crossref.org'), 'error'); return; } $sxml = @simplexml_load_string($result->data); if ($error = (string) $sxml->doi_record->crossref->error) { drupal_set_message($error, 'error'); return; } $this->nodes = array(); $this->parser = drupal_xml_parser_create($result->data); // use case-folding so we are sure to find the tag in xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, FALSE); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, TRUE); xml_set_object($this->parser, $this); xml_set_element_handler($this->parser, 'unixref_startElement', 'unixref_endElement'); xml_set_character_data_handler($this->parser, 'unixref_characterData'); if (!xml_parse($this->parser, $result->data)) { drupal_set_message(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($this->parser)), xml_get_current_line_number($this->parser)), 'error'); } xml_parser_free($this->parser); return $this->node; }
public function executeRequest(TingClientHttpRequest $request) { $result = drupal_http_request($request->getUrl(), array(), $request->getMethod(), NULL, $this->numRetries); if (isset($result->error)) { throw new TingClientException('Unable to excecute Drupal HTTP request: ' . $result->error, $result->code); } return $result->data; }
public static function authenticateInstagramCredentials($instagramBookModel, $code) { global $base_url; $url = "https://api.instagram.com/oauth/access_token"; $data = array('client_id' => $instagramBookModel->instagram_client_id, 'client_secret' => $instagramBookModel->instagram_client_secret, 'grant_type' => 'authorization_code', 'redirect_uri' => $base_url . "/" . ADMIN_URL, 'code' => $code); $options = array('method' => 'POST', 'data' => drupal_http_build_query($data), 'timeout' => 15, 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded')); $response = drupal_http_request($url, $options); return json_decode($response->data); }
/** * Wrapper for the Shareaholic Content Manager Single Page worker API * * @param Object $node The content that was created/updated/deleted */ public static function single_page_worker($node) { $page_link = url('node/' . $node->nid, array('absolute' => TRUE)); if (isset($page_link)) { $single_page_job_url = ShareaholicUtilities::CM_API_URL . '/jobs/uber_single_page'; $data = '{"args":["' . $page_link . '", {"force": true}]}'; $options = array('method' => 'POST', 'data' => $data, 'headers' => array('Content-Type' => 'application/json')); $response = drupal_http_request($single_page_job_url, $options); } }
/** * Validate the input URI. * @param string $uri * the URL to validate. */ public function validate($uri) { // build the callUrl to call W3C validator $callUrl = $this->makeCallUrl($uri); // call the W3Cvalidator WS $result = drupal_http_request($callUrl); if (!isset($result->error)) { return $this->parseSOAP12Response($result->data); } else { return null; } }
/** * Perform request to the Alma server. * * @param string $method * The REST method to call e.g. 'patron/status'. borrCard and pinCode * are required for all request related to library patrons. * @param array $params * Query string parameters in the form of key => value. * @param bool $check_status * Check the status element, and throw an exception if it is not ok. * * @return DOMDocument * A DOMDocument object with the response. */ public function request($method, $params = array(), $check_status = TRUE) { $start_time = explode(' ', microtime()); // For use with a non-Drupal-system, we should have a way to swap // the HTTP client out. $request = drupal_http_request(url($this->base_url . $method, array('query' => $params)), array('secure_socket_transport' => 'sslv3')); $stop_time = explode(' ', microtime()); // For use with a non-Drupal-system, we should have a way to swap // logging and logging preferences out. if (variable_get('alma_enable_logging', FALSE)) { $seconds = floatval($stop_time[1] + $stop_time[0] - ($start_time[1] + $start_time[0])); // Filter params to avoid logging sensitive data. // This can be disabled by setting alma_logging_filter_params = 0. There // is no UI for setting this variable // It is intended for settings.php in development environments only. $params = variable_get('alma_logging_filter_params', 1) ? self::filter_request_params($params) : $params; // Log the request. watchdog('alma', 'Sent request: @url (@seconds s)', array('@url' => url($this->base_url . $method, array('query' => $params)), '@seconds' => $seconds), WATCHDOG_DEBUG); } if ($request->code == 200) { // Since we currently have no need for the more advanced stuff // SimpleXML provides, we'll just use DOM, since that is a lot // faster in most cases. $doc = new DOMDocument(); $doc->loadXML($request->data); if (!$check_status || $doc->getElementsByTagName('status')->item(0)->getAttribute('value') == 'ok') { return $doc; } else { $message = $doc->getElementsByTagName('status')->item(0)->getAttribute('key'); switch ($message) { case '': case 'borrCardNotFound': throw new AlmaClientBorrCardNotFound('Invalid borrower credentials'); case 'reservationNotFound': throw new AlmaClientReservationNotFound('Reservation not found'); case 'invalidPatron': if ($method == 'patron/selfReg') { throw new AlmaClientUserAlreadyExistsError(); } else { throw new AlmaClientInvalidPatronError(); } default: throw new AlmaClientCommunicationError('Status is not okay: ' . $message); } } } else { throw new AlmaClientHTTPError('Request error: ' . $request->code . $request->error); } }
/** * Gather hook documentation files. * * This retrieves a list of api hook documentation files from drupal.org's * version control server. */ protected function gatherHookDocumentationFiles() { $directory = \ModuleBuilder\Factory::getEnvironment()->getHooksDirectory(); // Fetch data about the files we need to download. $hook_files = $this->getHookFileUrls($directory); //print_r($hook_files); // Retrieve each file and store it in the hooks directory, overwriting what's currently there foreach ($hook_files as $file_name => $data) { $file_contents = drupal_http_request($data['url']); // TODO: replace with call to environment output. //_module_builder_drush_print("writing $directory/$file_name", 2); file_put_contents("{$directory}/{$file_name}", $destination . $file_contents->data); } return $hook_files; }
/** * The callback for running checks and returning responses. * * Required for each status handler unless 'use_callback' is set to FALSE in * the info declaration. * * @return array * - 'success' (bool, required) * Whether or not the status check was a success or failure. * - 'messages' (array, required) * A list of string messages to be added to the response information * for the test. */ public function callback() { // Perform a request on an example url. $url = 'http://exampleurl.com'; $response = drupal_http_request($url); // Check for a 200 response and the word 'text' in the response. if ($response->code == '200' && strpos($response->data, 'text') !== FALSE) { $success = TRUE; $messages[] = t('@url retrieved successfully.', ['@url' => $url]); } else { $success = FALSE; $messages[] = t('@url not retrieved successfully.', ['@url' => $url]); } return ['success' => $success, 'messages' => $messages]; }
/** * {@inheritdoc} */ public function request(RequestInterface $request) { $url = (string) $request->getUri(); $body = $request->getBody(); $body->seek(0); $headers = $request->getHeaders(); foreach ($headers as $name => $value) { $headers[$name] = implode(', ', $value); } $headers['Accept'] = 'application/json'; $headers['Content-Type'] = 'application/json'; $options = array('method' => $request->getMethod(), 'headers' => $headers, 'data' => $body->getContents()); $res = drupal_http_request($url, $options); $response = (new Response(new Stream('php://memory', 'w')))->withStatus($res->code, $res->status_message); $response->getBody()->write($res->data); return $response; }
function ninesixtyrobots_preprocess_page(&$vars) { $use_twitter = theme_get_setting('use_twitter'); if (is_null($use_twitter)) { $use_twitter = 1; } $query = theme_get_setting('twitter_search_term'); if (is_null($query)) { $query = 'lullabot'; } $query = urlencode($query); if ($use_twitter) { $response = drupal_http_request('http://search.twitter.com/search.json?q=' . $query); $data = json_decode($response->data); $tweet = $data->results[array_rand($data->results)]; $vars['site_slogan'] = check_plain($tweet->text); } }
/** * Central method for making the actual http request to the Solr Server * * This is just a wrapper around drupal_http_request(). */ protected function _makeHttpRequest($url, array $options = array()) { if (!isset($options['method']) || $options['method'] == 'GET' || $options['method'] == 'HEAD') { // Make sure we are not sending a request body. $options['data'] = NULL; } // Default timeout of 30s is insufficient for luke requests and indexing. $options += array('timeout' => variable_get('apachesolr_connection_timeout', '600.0')); $result = drupal_http_request($url, $options); if (!isset($result->code) || $result->code < 0) { $result->code = 0; $result->status_message = 'Request failed'; $result->protocol = 'HTTP/1.0'; } // Additional information may be in the error property. if (isset($result->error)) { $result->status_message .= ': ' . check_plain($result->error); } if (!isset($result->data)) { $result->data = ''; $result->response = NULL; } else { // @see http://wiki.apache.org/solr/SolJSON // "Using a JSON object (essentially a map or hash) for a NamedList results // in the loss of some information." // That's the reason why the multiple language specific spell check results // get lost during json_decode(), because they are all named "spellcheck". // Therefor we rename the the language specific spell checks. // The language unspecific spellcheck is the last one in the list // and therefor not touched. $language_ids = array_keys(apachesolr_multilingual_language_list()); foreach ($language_ids as $language_id) { $result->data = preg_replace('@"spellcheck"@', '"spellcheck_' . $language_id . '"', $result->data, 1); } $response = json_decode($result->data); if (is_object($response)) { foreach ($response as $key => $value) { $result->{$key} = $value; } } } return $result; }
/** * Get a user from GitHub. * * @todo: Deal with the case that an existing user has revoked Github access * so we need to re-set their key. * * @return array * Array from RESTful token authentication resource. * * @throws \RestfulUnauthorizedException */ protected function getUser() { $request = $this->getRequest(); if (empty($request['code'])) { throw new \RestfulUnauthorizedException('code property is missing.'); } $options = array('method' => 'POST', 'data' => http_build_query(array('client_id' => variable_get('hedley_github_client_id'), 'client_secret' => variable_get('hedley_github_client_secret'), 'code' => $request['code']))); // Pantheon has a nasty bug that causes http_build_query() to build the // query incorrectly. $options['data'] = 'client_id=' . variable_get('hedley_github_client_id') . '&client_secret=' . variable_get('hedley_github_client_secret') . '&code=' . $request['code']; // Allow mocking the login to Github. $url = variable_get('hedley_github_api_login_url', 'https://github.com/login/oauth/access_token'); $result = drupal_http_request($url, $options); hedley_github_check_response_http_error($url, $result); $access_token = hedley_github_get_data_from_http_result($result); $options = array('headers' => array('Authorization' => 'token ' . $access_token)); $data = hedley_github_http_request('user', $options); $data = $data['data']; $name = $data['login']; // Get the username from Github and compare with ours. $query = new EntityFieldQuery(); $result = $query->entityCondition('entity_type', 'user')->propertyCondition('name', $name)->range(0, 1)->execute(); if (empty($result['user'])) { // Create a new user. $account = $this->createUser($data, $options, $access_token); } else { $id = key($result['user']); $account = user_load($id); // Make sure GitHub's access token is updated. $wrapper = entity_metadata_wrapper('user', $id); if ($wrapper->field_github_access_token->value() != $access_token) { $wrapper->field_github_access_token->set($access_token); $wrapper->save(); } } if ($account->status == FALSE) { // User is blocked. throw new \RestfulUnauthorizedException('You are blocked from the site.'); } $this->setAccount($account); return $this->getOrCreateToken(); }
public function get($key) { // get the file name $filename = $this->getCacheFilename($key); // if the file does not exist, return null if (!file_exists($filename)) { return NULL; } // if the file is expired, invalidate it and return null if (time() - filemtime($filename) > $this->expiryTime) { $this->invalidate($key); return NULL; } #$this->obtainLock($filename, LOCK_SH); // read the file $content = drupal_http_request($filename); // unlock the file #$this->releaseLock($filename); // return the content return $content->data; }
/** * Post answer data to creative commons web api, return xml response. */ function post_answers($questions) { $id = $this->license_type; if (isset($id) && $id != 'none') { // required header $headers = array(); $headers['Content-Type'] = 'application/x-www-form-urlencoded'; // request $uri = 'http://api.creativecommons.org/rest/license/' . $id . '/issue'; foreach ($questions as $q => $a) { $answer_xml .= "<{$q}>" . $a['selected'] . "</{$q}>"; } $answer_xml = "<answers><license-{$id}>{$answer_xml}</license-{$id}></answers>"; // post to cc api $post_data = 'answers=' . urlencode($answer_xml) . "\n"; $response = drupal_http_request($uri, $headers, 'POST', $post_data); if ($response->code == 200) { return $response->data; } } return; }
/** * Gather hook documentation files. * * This retrieves a list of api hook documentation files from drupal.org's * version control server. */ protected function gatherHookDocumentationFiles() { $directory = \ModuleBuilder\Factory::getEnvironment()->getHooksDirectory(); // Fetch data about the files we need to download. $hook_files = $this->getHookFileUrls($directory); //print_r($hook_files); // For testing only: skip downloading, just process. /* module_builder_process_hook_data($hook_files); return $hook_files; */ // Retrieve each file and store it in the hooks directory, overwriting what's currently there foreach ($hook_files as $file_name => $data) { $file_contents = drupal_http_request($data['url']); // TODO: replace with call to environment output. //_module_builder_drush_print("writing $directory/$file_name", 2); file_put_contents("{$directory}/{$file_name}", $destination . $file_contents->data); } // inform that hook documentation has been downloaded. drupal_set_message(t("Module Builder has just downloaded hook documentation to your %dir directory from CVS. This documentation contains detailed descriptions and usage examples of each of Drupal's hooks. Please view the files for more information, or view them online at the <a href=\"!api\">Drupal API documentation</a> site.", array('%dir' => 'files/' . variable_get('module_builder_hooks_directory', 'hooks'), '!api' => url('http://api.drupal.org/')))); return $hook_files; }
/** * Sends an HTTP request to Solr. * * This is just a wrapper around drupal_http_request(). * * Overridden by Pantheon to set a timeout and possibly other improvements. */ protected function makeHttpRequest($url, array $options = array()) { if (empty($options['method']) || $options['method'] == 'GET' || $options['method'] == 'HEAD') { // Make sure we are not sending a request body. $options['data'] = NULL; } if ($this->http_auth) { $options['headers']['Authorization'] = $this->http_auth; } if ($this->stream_context) { $options['context'] = $this->stream_context; } // Specify timeout. $options['timeout'] = 5; $result = drupal_http_request($url, $options); if (!isset($result->code) || $result->code < 0) { $result->code = 0; $result->status_message = 'Request failed'; $result->protocol = 'HTTP/1.0'; } // Additional information may be in the error property. if (isset($result->error)) { $result->status_message .= ': ' . check_plain($result->error); } if (!isset($result->data)) { $result->data = ''; $result->response = NULL; } else { $response = json_decode($result->data); if (is_object($response)) { foreach ($response as $key => $value) { $result->{$key} = $value; } } } return $result; }
/** * Work horse. Every API call use this function to actually make the request to Mandrill's servers. * * @link https://mandrillapp.com/api/docs/ * * @param string $method API method name * @param array $args query arguments * @param string $http GET or POST request type * @param string $output API response format (json,php,xml,yaml). json and xml are decoded into arrays automatically. * * @return array|string|Mandrill_Exception */ function request($method, $args = array(), $http = 'POST', $output = 'json') { if (!isset($args['key'])) { $args['key'] = $this->api; } $api_version = self::API_VERSION; $dot_output = 'json' == $output ? '' : ".{$output}"; $url = self::END_POINT . "{$api_version}/{$method}{$dot_output}"; $params = json_encode($args); switch ($http) { case 'GET': $url .= '?' . $params; $response = drupal_http_request($url, array(), 'GET', NULL, 3, $this->timeout); break; case 'POST': $response = drupal_http_request($url, array(), 'POST', $params, 3, $this->timeout); break; default: throw new Mandrill_Exception('Unknown request type'); } $response_code = $response->code; $body = $response->data; switch ($output) { case 'json': $body = json_decode($body, TRUE); break; case 'php': $body = unserialize($body); break; } if (200 == $response_code) { return $body; } else { $message = isset($body['message']) ? $body['message'] : ''; throw new Mandrill_Exception($message . ' - ' . $body, $response_code); } }
// </ul> if ($i == $json_count or $i == $json_last_in_first) { $output .= '</ul>'; } $i++; } $output .= '</li>'; } } /////////////////////////////////////////////////////// ////////////// I D R Æ T S C E N T E R ////////////// /////////////////////////////////////////////////////// if ($_GET['idraetscenter'] == '1') { $url = "http://prod.booksys.dk/infoapi/rest/rfv/YY0002"; // json fra Kiehn (må efter aftale max hentes hvert 5. minut) $request = drupal_http_request($url); $json_response = drupal_json_decode($request->data); if ($json_response) { $data = $json_response['bookings']; // var_dump($data); // $data_length = sizeof($data); // antallet af elementer // Antallet af aktuelle aktiviteter (aktiviteter som er i gang og fremtidige aktiviteter på dagen) $current_time = time(); // Unix Epoch $current_elements = 0; foreach ($data as $response_data) { if ($response_data['s**t'] >= $current_time) { $current_elements++; } } // Antallet af sider (8 elementer pr. side)
protected function _makeHttpRequest($url, $method = 'GET', $headers = array(), $content = '', $timeout = FALSE) { // Set a response timeout if ($timeout) { $default_socket_timeout = ini_set('default_socket_timeout', $timeout); } $result = drupal_http_request($url, $headers, $method, $content); // Restore the response timeout if ($timeout) { ini_set('default_socket_timeout', $default_socket_timeout); } // This will no longer be needed after http://drupal.org/node/345591 is committed $responses = array(0 => 'Request failed', 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'); if (!isset($result->code) || $result->code < 0) { $result->code = 0; } if (isset($result->error)) { $responses[0] .= ': ' . check_plain($result->error); } if (!isset($result->data)) { $result->data = ''; } if (!isset($responses[$result->code])) { $result->code = floor($result->code / 100) * 100; } $protocol = "HTTP/1.1"; $headers[] = "{$protocol} {$result->code} {$responses[$result->code]}"; if (isset($result->headers)) { foreach ($result->headers as $name => $value) { $headers[] = "{$name}: {$value}"; } } return array($result->data, $headers); }
/** * Define actions for search engines. * @param $op: * - form: * Add search engine to form at admin/settings/xmlsitemap. * - ping: * Submit site map to search engine. * - access: * Log search engine access. * @param $type: * If $op is 'access', one of the following strings will indicate what was * downloaded: * - Site map: * The site map was downloaded. * - Site map index * The site map index was downloaded. * - Site map $chunk * Chunk $chunk was downloaded. * @return * - form: * Array of form elements for search engine settings * - ping: * None * - access: * Message string for access log */ function hook_xmlsitemap_engines($op, $type = NULL) { switch ($op) { case 'form': $form['google'] = array('#type' => 'fieldset', '#title' => t('Google'), '#collapsible' => TRUE, '#collapsed' => TRUE); $form['google']['xmlsitemap_engines_google_submit'] = array('#type' => 'checkbox', '#title' => t('Submit site map to Google.'), '#default_value' => variable_get('xmlsitemap_engines_google_submit', TRUE)); $form['google']['xmlsitemap_engines_google_url'] = array('#type' => 'textfield', '#title' => t('Submission URL'), '#default_value' => variable_get('xmlsitemap_engines_google_url', 'http://www.google.com/webmasters/tools/ping?sitemap=' . xmlsitemap_url('sitemap.xml', drupal_lookup_path('alias', 'sitemap.xml') ? drupal_lookup_path('alias', 'sitemap.xml') : NULL, NULL, NULL, TRUE)), '#description' => t('The URL to submit the site map to.')); $form['google']['xmlsitemap_engines_google_verify'] = array('#type' => 'textfield', '#title' => t('Verification link'), '#default_value' => variable_get('xmlsitemap_engines_google_verify', ''), '#description' => t('In order to show statistics, Google will ask you to verify that you control this site by creating a file with a certain name. Enter that name here and the XML Sitemap module will create a path to that file name. This will only work if you have clean URLs enabled.')); return $form; case 'ping': if (variable_get('xmlsitemap_engines_google_submit', TRUE)) { $result = drupal_http_request(variable_get('xmlsitemap_engines_google_url', 'http://www.google.com/webmasters/tools/ping?sitemap=' . xmlsitemap_url('sitemap.xml', drupal_lookup_path('alias', 'sitemap.xml') ? drupal_lookup_path('alias', 'sitemap.xml') : NULL, NULL, NULL, TRUE))); if ($result->code == 200) { watchdog('xmlsitemap', t('Sitemap successfully submitted to Google.')); } else { watchdog('xmlsitemap', t('Error occurred submitting sitemap to Google: @code', array('@code' => $result->code)), WATCHDOG_ERROR); } } break; case 'access': if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== FALSE) { return t('!sitemap downloaded by Google.', array('!sitemap' => $type)); } break; } }
/** * Actually performs a request. * * This method can be easily overriden through inheritance. * * @param string $url * The url of the endpoint. * @param array $headers * Array of headers. * @param string $method * The HTTP method to use (normally POST or GET). * @param array $data * An array of parameters * @return * stdClass response object. */ protected function doRequest($url, $headers, $method, $data) { $response = drupal_http_request($url, array('headers' => $headers, 'method' => $method, 'data' => $data)); return $response; }
function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) { global $db_prefix; $result = new stdClass(); // Parse the URL and make sure we can handle the schema. $uri = parse_url($url); if ($uri == FALSE) { $result->error = 'unable to parse URL'; $result->code = -1001; return $result; } if (!isset($uri['scheme'])) { $result->error = 'missing schema'; $result->code = -1002; return $result; } switch ($uri['scheme']) { case 'http': $port = isset($uri['port']) ? $uri['port'] : 80; $host = $uri['host'] . ($port != 80 ? ':' . $port : ''); $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15); break; case 'https': // Note: Only works for PHP 4.3 compiled with OpenSSL. $port = isset($uri['port']) ? $uri['port'] : 443; $host = $uri['host'] . ($port != 443 ? ':' . $port : ''); $fp = @fsockopen('ssl://' . $uri['host'], $port, $errno, $errstr, 20); break; default: $result->error = 'invalid schema ' . $uri['scheme']; $result->code = -1003; return $result; } // Make sure the socket opened properly. if (!$fp) { // When a network error occurs, we use a negative number so it does not // clash with the HTTP status codes. $result->code = -$errno; $result->error = trim($errstr); // Mark that this request failed. This will trigger a check of the web // server's ability to make outgoing HTTP requests the next time that // requirements checking is performed. // @see system_requirements() variable_set('drupal_http_request_fails', TRUE); return $result; } // Construct the path to act on. $path = isset($uri['path']) ? $uri['path'] : '/'; if (isset($uri['query'])) { $path .= '?' . $uri['query']; } // Create HTTP request. $defaults = array('Host' => "Host: {$host}", 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)'); // Only add Content-Length if we actually have any content or if it is a POST // or PUT request. Some non-standard servers get confused by Content-Length in // at least HEAD/GET requests, and Squid always requires Content-Length in // POST/PUT requests. $content_length = strlen($data); if ($content_length > 0 || $method == 'POST' || $method == 'PUT') { $defaults['Content-Length'] = 'Content-Length: ' . $content_length; } // If the server url has a user then attempt to use basic authentication if (isset($uri['user'])) { $defaults['Authorization'] = 'Authorization: Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : '')); } // If the database prefix is being used by SimpleTest to run the tests in a copied // database then set the user-agent header to the database prefix so that any // calls to other Drupal pages will run the SimpleTest prefixed database. The // user-agent is used to ensure that multiple testing sessions running at the // same time won't interfere with each other as they would if the database // prefix were stored statically in a file or database variable. if (is_string($db_prefix) && preg_match("/^simpletest\\d+\$/", $db_prefix, $matches)) { $defaults['User-Agent'] = 'User-Agent: ' . $matches[0]; } foreach ($headers as $header => $value) { $defaults[$header] = $header . ': ' . $value; } $request = $method . ' ' . $path . " HTTP/1.0\r\n"; $request .= implode("\r\n", $defaults); $request .= "\r\n\r\n"; $request .= $data; $result->request = $request; fwrite($fp, $request); // Fetch response. $response = ''; while (!feof($fp) && ($chunk = fread($fp, 1024))) { $response .= $chunk; } fclose($fp); // Parse response. list($split, $result->data) = explode("\r\n\r\n", $response, 2); $split = preg_split("/\r\n|\n|\r/", $split); list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3); $result->headers = array(); // Parse headers. while ($line = trim(array_shift($split))) { list($header, $value) = explode(':', $line, 2); if (isset($result->headers[$header]) && $header == 'Set-Cookie') { // RFC 2109: the Set-Cookie response header comprises the token Set- // Cookie:, followed by a comma-separated list of one or more cookies. $result->headers[$header] .= ',' . trim($value); } else { $result->headers[$header] = trim($value); } } $responses = array(100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'); // RFC 2616 states that all unknown HTTP codes must be treated the same as the // base code in their class. if (!isset($responses[$code])) { $code = floor($code / 100) * 100; } switch ($code) { case 200: // OK // OK case 304: // Not modified break; case 301: // Moved permanently // Moved permanently case 302: // Moved temporarily // Moved temporarily case 307: // Moved temporarily $location = $result->headers['Location']; if ($retry) { $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry); $result->redirect_code = $result->code; } $result->redirect_url = $location; break; default: $result->error = $text; } $result->code = $code; return $result; }