/** * Do CURL request with authorization. * * @param string $resource * A request action of api. * @param string $method * A method of curl request. * @param string $input * A data of curl request. * * @return array * An associate array with respond data. */ private function doRequest($resource, $method, $input) { if (!function_exists('curl_init')) { $msg = 'SendinBlue requires CURL module'; watchdog('sendinblue', $msg, NULL, WATCHDOG_ERROR); return NULL; } $called_url = $this->baseUrl . "/" . $resource; $ch = curl_init($called_url); $auth_header = 'api-key:' . $this->apiKey; $content_header = "Content-Type:application/json"; //if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { // Windows only over-ride because of our api server. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //} curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth_header, $content_header)); //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POSTFIELDS, $input); $data = curl_exec($ch); if (curl_errno($ch)) { watchdog('sendinblue', 'Curl error: @error', array('@error' => curl_error($ch)), WATCHDOG_ERROR); } curl_close($ch); return drupal_json_decode($data); }
/** * This function is handles the callback from Box API. * @return string */ function _soc_boxauth_get_code_from_box_handler() { // get query string parameters $qs = drupal_get_query_parameters(); watchdog(SOC_BOXAUTH_MODULENAME, "Got code back from Box", $qs, WATCHDOG_INFO); // Stage post data and create http query $post_data = ['grant_type' => 'authorization_code', 'code' => $qs['code'], 'client_id' => variable_get(SOC_BOXAUTH_CLIENTID_VARIABLE), 'client_secret' => variable_get(SOC_BOXAUTH_CLIENTSECRET_VARIABLE)]; $result = BoxFolderOperations::doPost('https://api.box.com/oauth2/token', $post_data, 'Content-type: application/x-www-form-urlencoded', 'QUERY'); // save to session. Decoded json object into php array $_SESSION['box'] = drupal_json_decode($result); $_SESSION['box']['expires_time'] = time() + SOC_BOXAUTH_EXPIREOFFSET; // If successful, the ['box']['access_token'] will exists. Log and report // to user. if (isset($_SESSION['box']['access_token'])) { drupal_set_message(t(variable_get(SOC_BOXAUTH_SUCCESSMESSAGE_VARIABLE))); watchdog(SOC_BOXAUTH_MODULENAME, 'Successful box access_token'); $next_steps = variable_get(SOC_BOXAUTH_NEXTSTEPS_VARIABLE, ['value' => t('Next steps...')]); return $next_steps['value']; } else { $message = t(variable_get(SOC_BOXAUTH_FAILUREMESSAGE_VARIABLE)); drupal_set_message($message, 'error'); watchdog(SOC_BOXAUTH_MODULENAME, 'Failed box access_token'); return $message; } }
/** * Tests rest calls. */ public function testRESTCalls() { // Create a user account that has the required permissions to read // the watchdog resource via the REST API. $account = $this->drupalCreateUser(); $this->drupalLogin($account); $response = $this->httpRequest('exampleGetCall', 'GET', NULL, $this->defaultMimeType); $this->assertResponse(200); $this->assertHeader('content-type', $this->defaultMimeType); $decoded_response = drupal_json_decode($response); $decoded_expected = array('message' => 'Hello World!'); $this->assertIdentical($decoded_expected, $decoded_response, 'exampleGetCall response expected'); $response = $this->httpRequest('examplePostCall', 'POST', NULL, $this->defaultMimeType); $decoded_response = drupal_json_decode($response); $decoded_expected = array('message' => array('POST call')); $this->assertIdentical($decoded_expected, $decoded_response, 'examplePostCall response expected'); $arg1 = $this->randomName(); $arg2 = $this->randomName(); $response = $this->httpRequest("getCallArguments/{$arg1}/{$arg2}", 'GET', NULL, $this->defaultMimeType); $decoded_response = drupal_json_decode($response); $decoded_expected = array('arg1' => $arg1, 'arg2' => $arg2); $this->assertIdentical($decoded_expected, $decoded_response, 'getCallArguments response expected'); $body = json_encode($decoded_expected); $response = $this->httpRequest("postCallArguments", 'POST', $body, $this->defaultMimeType); $decoded_response = drupal_json_decode($response); $this->assertIdentical($decoded_response, $decoded_expected, 'postCallArguments response is correct'); $arg3 = $this->randomName(); $arg4 = $this->randomName(); $body = json_encode(array('body_arg1' => $arg1, 'body_arg2' => $arg2)); $response = $this->httpRequest("postCallMixedArguments/{$arg3}/{$arg4}", 'POST', $body, $this->defaultMimeType); $decoded_response = drupal_json_decode($response); $decoded_expected = array('body_arg1' => $arg1, 'body_arg2' => $arg2, 'uri_arg1' => $arg3, 'uri_arg2' => $arg4); $this->assertIdentical($decoded_expected, $decoded_response, 'postCallMixedArguments response expected'); }
/** * Implements functionThatShouldNotShowUp(); */ function test_function() { // Test a normal function should work properly. normalFunction('test data'); // Test exceptions: start simple - call a function that doesn't exist with a space in between the function name // and "(". functionThatDoesNotExist('param1', 'param2'); functionThatDoesNotExist2('param1', 'param2'); // Call a function within a function. abc(def('abc')); // Use a constant, that can be misconstrued as a function potentially. $test_result = 3 - TEST_CONST; // Test referring to an object. $testJsonResponse = (object) array('data' => 'abc'); $testJsonResponse->data = 'abc'; $result = drupal_json_decode($json->data); // Create a reference to returned value $a =& reference_returner_function(); // Static method call StaticTestClass::staticFunctionCall(); // Method call $someInstance->someMetod(); // Creating a class $a = new stdClass(); }
/** * Decodes a JSON string into an array. * * @param string $json * A JSON string. * * @return array * A PHP array. * * @throws RuntimeException * Thrown if the encoded JSON does not result in an array. */ public static function decodeJsonArray($json) { $parsed = drupal_json_decode($json); if (!is_array($parsed)) { throw new RuntimeException(t('The JSON is invalid.')); } return $parsed; }
public static function getJson($url, array $options = array()) { $data = NULL; $response = static::cachedRequest($url, $options); if (empty($response->error)) { $data = drupal_json_decode($response->data); if ($data === FALSE) { trigger_error("Unable to decode JSON response from {$url}.", E_USER_WARNING); } } return $data; }
/** * Implements hook_js_alter(). */ function huoltopelaa2015_js_alter(&$js) { $theme_path = drupal_get_path('theme', 'huoltopelaa2015'); // The whitelist in case of single_js == TRUE, the blacklist otherwise $whitelist = array("sites/all/libraries/datetimepicker/jquery.datetimepicker.js", drupal_get_path('module', 'mon_scheduler') . '/mon_scheduler.js'); // single_js means we work in a production environment, so include only // our single JS file, generated by gulp, and some whitelisted ones if (variable_get('single_js', TRUE)) { foreach ($js as $name => $settings) { // Exclude all files except for our own, and Drupal.settings if ($name != 'settings' && $name != $theme_path . '/dist/script.min.js' && !in_array($name, $whitelist, TRUE)) { unset($js[$name]); } } // Change its group and weight to be the first one included. // In that way, all other scripts whitelisted don't have to take care about // group and weight regarding to this global aggregate scripts which may // contains libraries. $js[$theme_path . '/dist/script.min.js']['group'] = JS_DEFAULT; $js[$theme_path . '/dist/script.min.js']['weight'] = -100; } else { // On development environments, we will try to populate the map.json file // with JS files that are included on the fly, excluding the one we generated $path = $theme_path . '/js/map.json'; // Load previous list from map.json $contents = file_get_contents($path); $list = FALSE; if ($contents !== FALSE) { // We have a list, parse it $list = drupal_json_decode($contents); } // else reading file failed, and we won't update it programmatically, but // we will still remove our single file foreach ($js as $name => $settings) { if ($name == $theme_path . '/dist/script.min.js') { // We won't need our single file here unset($js[$name]); continue; } // If we have a list, update it if ($list !== FALSE && $name != 'settings' && !in_array($name, $whitelist, TRUE) && strstr($name, 'languages/fr') === FALSE) { // TRUE will add it, FALSE will remove it, edit the map.json file // directly if you need to exclude a file $list[$name] = isset($list[$name]) ? $list[$name] : TRUE; } } // Udpate map.json if ($list !== FALSE && defined('JSON_PRETTY_PRINT')) { file_put_contents($path, json_encode($list, JSON_PRETTY_PRINT) . "\n"); } } }
function findAgent($json) { $json_array = drupal_json_decode($json); if (!isset($json_array['mbox']) && !isset($json_array['mbox_sha1sum']) && !isset($json_array['openid']) && (!isset($json_array['account']) && !isset($json_array['account']['homePage']) && !isset($json_array['account']['name']))) { return 0; } $query = new EntityFieldQuery(); $query->entityCondition('entity_type', 'tincan_agent'); if (isset($json_array['objectType'])) { switch ($json_array['objectType']) { case 'Agent': $query->propertyCondition('object_type', 'Agent'); break; case 'Group': $query->propertyCondition('object_type', 'Group'); break; } } else { $query->propertyCondition('object_type', 'Agent'); } if (isset($json_array['mbox'])) { $query->propertyCondition('mbox', $json_array['mbox']); } if (isset($json_array['mbox_sha1sum'])) { $query->propertyCondition('mbox_sha1sum', $json_array['mbox_sha1sum']); } if (isset($json_array['openid'])) { $query->propertyCondition('openid', $json_array['openid']); } if (isset($json_array['account'])) { if (isset($json_array['account']['homePage'])) { $query->propertyCondition('account_home_page', $json_array['account']['homePage']); } if (isset($json_array['account']['name'])) { $query->propertyCondition('account_name', $json_array['account']['name']); } } $result = $query->execute(); if (isset($result['tincan_agent'])) { foreach ($result['tincan_agent'] as $key => $agent) { return $key; } } else { return 0; } }
public function send($endpoint, $payload = array()) { $this->debug('Sending data to ' . $endpoint); // Attach the transaction to the payload. $payload['transaction'] = $this->generateTransactionObject(); // Generate the full endpoint URL. $request_url = trim($this->remote->url, '/') . '/' . self::ENDPOINT_PREFIX . $endpoint; // Generate the headers. $headers = $this->generateHeaders(); // Generate the payload. $this->debug($payload); $payload = \drupal_json_encode($payload); // Set the payload. $this->payload = $payload; // Start the curl request. $handle = curl_init($request_url); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $payload); // Execute the request and debug the output. $response = curl_exec($handle); $json = \drupal_json_decode($response); if ($json === null) { $this->debug($response); throw new TransactionException('Response from server was malformed. Check the recent log messages for more details. Response: ' . $response); } else { $this->debug($json); // Update the data for the current transaction. if (isset($json['transaction']['data']) && is_array($json['transaction']['data'])) { $this->data = $json['transaction']['data']; } // If there were messages sent back from the server, forward them to drupal_set_message. if (array_key_exists('messages', $json) && is_array($json['messages']) && count($json['messages']) > 0) { foreach ($json['messages'] as $message) { drupal_set_message('[' . $this->remote->label . '] ' . $message['message'], $message['type']); } } return $json; } }
function publisher_get_payload() { return drupal_json_decode(file_get_contents('php://input')); }
/** * {@inheritdoc} */ public function parseBody($body) { if (!($decoded_json = drupal_json_decode($body))) { throw new BadRequestException(sprintf('Invalid JSON provided: %s.', $body)); } return $decoded_json; }
/** * Implements OpenIDConnectClientInterface::retrieveUserInfo(). */ public function retrieveUserInfo($access_token) { $request_options = array('headers' => array('Authorization' => 'Bearer ' . $access_token)); $endpoints = $this->getEndpoints(); $response = drupal_http_request($endpoints['userinfo'], $request_options); if (!isset($response->error) && $response->code == 200) { return drupal_json_decode($response->data); } else { openid_connect_log_request_error(__FUNCTION__, $this->name, $response); return FALSE; } }
/** * Helper function that decodes the image info from the corresponding field. * * @param stirng $field_name * The name of the field containing the image data. * * @return array|FALSE * An array of image info matching what is returned from image_get_info(), * FALSE if the data is not available. */ public function decodeImageInfo($field_name) { $info = FALSE; $info_field_name = rich_snippets_get_apachesolr_image_info_field($field_name); if (!empty($this->_solrFields[$info_field_name])) { if ($info = drupal_json_decode($this->_solrFields[$info_field_name][0])) { $info += array('width' => 0, 'height' => 0, 'extension' => '', 'mime_type' => '', 'file_size' => 0); } } return $info; }
/** * Restore Theme settings */ function md_boom_multi_restore_theme_settings($form, &$form_state) { variable_set('theme_md_boom_multi_settings', array()); if ($restore_file = file_save_upload('restore_file_upload')) { $file_content = file_get_contents($restore_file->uri); $restore_settings = drupal_json_decode(base64_decode(unserialize($file_content))); variable_set('theme_md_boom_multi_settings', $restore_settings); cache_clear_all(); drupal_set_message(t('All your theme settings have been restored')); } elseif ($restore_file_path = $form_state['values']['restore_file_path']) { $restore_file_scheme = file_uri_scheme($restore_file_path); if ($restore_file_scheme == 'http' || $restore_file_scheme == 'https') { $restore_file_url = rawurldecode($restore_file_path); $restore_file_content = file_get_contents($restore_file_url); $restore_settings = drupal_json_decode(base64_decode(unserialize($restore_file_content))); variable_set('theme_md_boom_multi_settings', $restore_settings); cache_clear_all(); drupal_set_message(t('All your theme settings have been restored')); } else { $restore_file_content = file_get_contents($restore_file_path); $restore_settings = drupal_json_decode(base64_decode(unserialize($restore_file_content))); variable_set('theme_md_boom_multi_settings', $restore_settings); cache_clear_all(); drupal_set_message(t('All your theme settings have been restored')); } } }
private function populate() { $json = $this->notation; $json_array = drupal_json_decode($json); dsm($json_array); // Object Type if (isset($json_array['objectType'])) { if ($json_array['objectType'] == 'Activity') { } else { // some kind of validation error } } else { $this->object_type = 'Activity'; } // activity_id if (isset($json_array['id'])) { $this->activity_id = $json_array['id']; } // Definition if (isset($json_array['definition'])) { // Name if (isset($json_array['definition']['name'])) { // full name language map as json $this->name_json = drupal_json_encode($json_array['definition']['name']); // US English name if (isset($json_array['definition']['name']['en-US'])) { $this->name_en_us = $json_array['definition']['name']['en-US']; } } // Description if (isset($json_array['definition']['description'])) { // full description language map as json $this->description_json = drupal_json_encode($json_array['definition']['description']); // US English description if (isset($json_array['definition']['description']['en-US'])) { $this->description_en_us = $json_array['definition']['description']['en-US']; } } // type if (isset($json_array['definition']['type'])) { $this->type = $json_array['definition']['type']; } // more_info if (isset($json_array['definition']['moreInfo'])) { $this->more_info = $json_array['definition']['moreInfo']; } // extensions if (isset($json_array['definition']['extensions'])) { $this->type = drupal_json_encode($json_array['definition']['extensions']); } //interaction_type if (isset($json_array['definition']['interactionType'])) { $this->interaction_type = $json_array['definition']['interactionType']; } // correct_responses_pattern if (isset($json_array['definition']['correctResponsesPattern'])) { $this->correct_responses_pattern = drupal_json_encode($json_array['definition']['correctResponsesPattern']); } //Next the interaction fields $this->interaction_components_json = ''; $intact_type = array('choices', 'scale', 'source', 'steps', 'target'); foreach ($intact_type as $type) { if (isset($json_array['definition'][$type]) && is_array($json_array['definition'][$type])) { if (!isset($json_array['definition'][$type][0])) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][0]['json'] = drupal_json_encode($json_array['definition'][$type]); $this->interaction_components_json .= ' ' . drupal_json_encode($item) . ' '; if (isset($json_array['definition'][$type]['id'])) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][0]['id'] = $json_array['definition'][$type]['id']; } if (isset($json_array['definition'][$type]['description'])) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][0]['description'] = drupal_json_encode($json_array['definition'][$type]['description']); } if (isset($json_array['definition'][$type]['description']['en-US'])) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][0]['description_en_us'] = $json_array['definition'][$type]['description']['en-US']; } } else { $count = 0; } foreach ($json_array['definition'][$type] as $key => $item) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][$count]['json'] = drupal_json_encode($item); $this->interaction_components_json .= ' ' . drupal_json_encode($item) . ' '; if (isset($item['id'])) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][$count]['id'] = $item['id']; } if (isset($item['description'])) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][$count]['description'] = drupal_json_encode($item['description']); } if (isset($item['description']['en-US'])) { $this->{'tincan_interaction_com_' . $type}[LANGUAGE_NONE][$count]['description_en_us'] = $item['description']['en-US']; } $count += 1; } //end else } //end if isset(type) } // end foreach type } //end if isset(definition) }
public function decode($url) { $response = drupal_http_request($url); $responseOk = $response->code == 200; return $responseOk ? drupal_json_decode($response->data) : NULL; }
/** * This function will retrieve a new * single use token from stripe. Helpful * for if you are doing a lot of repetitive testing. * * Note, you will need Guzzle for this. Hopefully you * are already using composer. If not, what are you doing? */ public static function getStripeToken($param = array()) { //$client = new \GuzzleHttp\Client(); $pubKey = variable_get('mp_stripe_public', 'pk_test_jLHDb7FuCHiWnVVr03QnyVBV'); $cardNumber = isset($param['credit_card']['number']) ? $param['credit_card']['number'] : "4242424242424242"; $cvc = isset($param['credit_card']['code']) ? $param['credit_card']['code'] : "123"; $expMonth = isset($param['credit_card']['exp_month']) ? $param['credit_card']['exp_month'] : "11"; $expYear = isset($param['credit_card']['exp_year']) ? $param['credit_card']['exp_year'] : "2018"; $headers = ['Pragma' => 'no-cache', 'Origin' => 'https://js.stripe.com', 'Accept-Encoding' => 'gzip, deflate', 'Accept-Language' => 'en-US,en;q=0.8', 'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36', 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json', 'Cache-Control' => 'no-cache', 'Referer' => 'https://js.stripe.com/v2/channel.html?stripe_xdm_e=http%3A%2F%2Fwww.beanstalk.dev&stripe_xdm_c=default176056&stripe_xdm_p=1', 'Connection' => 'keep-alive']; $postBody = ['key' => $pubKey, 'payment_user_agent' => 'stripe.js/Fbebcbe6', 'card[number]' => $cardNumber, 'card[cvc]' => $cvc, 'card[exp_month]' => $expMonth, 'card[exp_year]' => $expYear]; // if drupal_http_request not response data then we need to make this call again and again three time. for ($i = 0; $i < 3; $i++) { $response = drupal_http_request('https://api.stripe.com/v1/tokens', array('headers' => $headers, 'method' => 'POST', 'data' => drupal_http_build_query($postBody), 'timeout' => 120)); if ($response->code == 200) { $response = drupal_json_decode($response->data); return new Response(TRUE, $response['id'], ""); } } $response_date = json_decode($response->data); return new Response(FALSE, $response_date->error->message, $response_date->error->message); }
/** * Sets the raw HTML content. This can be useful when a page has been fetched * outside of the internal browser and assertions need to be made on the * returned page. * * A good example would be when testing drupal_http_request(). After fetching * the page the content can be set and page elements can be checked to ensure * that the function worked properly. */ protected function drupalSetContent($content, $url = 'internal:') { $this->content = $content; $this->url = $url; $this->plainTextContent = FALSE; $this->elements = FALSE; $this->drupalSettings = array(); if (preg_match('/jQuery\\.extend\\(Drupal\\.settings, (.*?)\\);/', $content, $matches)) { $this->drupalSettings = drupal_json_decode($matches[1]); } }
/** * Restore Theme settings */ function md_leaders_restore_theme_settings($form, &$form_state) { $values = $form_state['values']; if ($values['restore_type'] != null) { if ($values['restore_type'] == 'upload') { if ($form_state['values']['restore_file_media_upload']['fid'] != 0) { $file = file_load($form_state['values']['restore_file_media_upload']['fid']); if ($file == false) { drupal_set_message(t("Your file upload isn't found, please upload again"), 'warning'); return; } $file_content = file_get_contents($file->uri); $restore_settings = drupal_json_decode(base64_decode(unserialize($file_content))); if (is_array($restore_settings)) { variable_set('theme_md_leaders_settings', array()); variable_set('theme_md_leaders_settings', $restore_settings); file_delete($file, $force = true); cache_clear_all(); drupal_set_message(t('All your theme settings have been restored')); } else { drupal_set_message(t("Your file upload isn't correct, please upload again"), 'warning'); return; } } else { drupal_set_message(t('Please choose your file upload'), 'error'); return; } } else { if ($values['restore_from_file'] == null) { drupal_set_message('Choose your backup file in list or move back up to backup folder', 'warning'); return; } else { $file_content = file_get_contents("public://md_leaders_backup/{$values['restore_from_file']}"); $restore_settings = drupal_json_decode(base64_decode(unserialize($file_content))); if (is_array($restore_settings)) { variable_set('theme_md_leaders_settings', array()); variable_set('theme_md_leaders_settings', $restore_settings); cache_clear_all(); drupal_set_message(t('All your theme settings have been restored')); } else { drupal_set_message(t("Your choosen backup file isn't correct, please choose again"), 'warning'); return; } } } } if ($restore_file = file_save_upload('restore_file_simple_upload')) { $file_content = file_get_contents($restore_file->uri); $restore_settings = drupal_json_decode(base64_decode(unserialize($file_content))); variable_set('theme_md_leaders_settings', $restore_settings); cache_clear_all(); drupal_set_message(t('All your theme settings have been restored')); } if (isset($form_state['values']['restore_file_media_upload'])) { } }
protected function request($url, $method = 'GET', $data = '', $timeout = 60) { try { $request = drupal_http_request($url, array('headers' => array('Content-Type' => 'application/json'), 'method' => $method, 'data' => $data, 'timeout' => $timeout, 'context' => [])); if ($request->code != 200) { throw new \Exception('网络错误'); } $data = $request->data; $data = drupal_json_decode($data); return $data; if ($data['errcode'] != 0) { throw new \Exception($data['errmsg'], $data['errcode']); } return $data; } catch (\Exception $e) { watchdog_exception('微信扫一扫接口异常跟踪', $e); throw new $e(); } }
/** * Run common test to an array of package. * * @param object $result * A dkan_dataset_api result object. * @param string $text * A string to match against the returned help string. */ protected function runCommonTest($result, $text) { $data = drupal_json_decode($result->data); if (isset($data['result']) && count($data['result'])) { $this->assertTrue(count($data['result']) > 0); $this->assertTrue($data['success']); } $this->assertTrue(strpos($data['help'], $text) !== FALSE); }
function product_file_data() { $json = product_file_json(); $data = drupal_json_decode($json); return $data; }
private function populate() { $json = $this->notation; $json_array = drupal_json_decode($json); dsm($json_array); //object_type if (isset($json_array['objectType']) && $json_array['objectType'] == 'SubStatement') { $this->object_type = 'SubStatement'; if (isset($json_array['version'])) { unset($json_array['version']); } if (isset($json_array['id'])) { unset($json_array['id']); } if (isset($json_array['stored'])) { unset($json_array['version']); } if (isset($json_array['authority'])) { unset($json_array['version']); } } else { $this->object_type = 'Statement'; } //version if (isset($json_array['version'])) { $this->version = $json_array['version']; } else { if ($this->object_type != 'SubStatement') { $this->version = '1.0.0'; } } //id if (isset($json_array['id'])) { $this->statement_id = $json_array['id']; } else { // generate uuid for the statement if ($this->object_type != 'SubStatement' && $this->statement_id == '') { $this->statement_id = uuid_generate(); } } //timestamp // need to do something about saving the datetime values tincan api expects into mysql.... if (isset($json_array['timestamp'])) { $this->timestamp = $json_array['timestamp']; } // stored if (isset($json_array['stored'])) { $this->stored = $json_array['stored']; } else { if ($this->object_type != 'SubStatement') { $this->stored = date('c'); //must be in iso 8601 format; } } // Actor if (isset($json_array['actor'])) { $this->tincan_actor = array(); $this->populateActor($json_array['actor']); } // Verb if (isset($json_array['verb'])) { $this->tincan_verb = array(); $this->populateVerb($json_array['verb']); } // Object if (isset($json_array['object'])) { $this->tincan_object = array(); $this->populateObject($json_array['object']); } // Result if (isset($json_array['result'])) { $this->tincan_result = array(); $this->populateResult($json_array['result']); } // Authority if (isset($json_array['authority'])) { $this->tincan_authority = array(); $this->populateAuthority($json_array['authority']); } else { //figure out authorize default if ($this->object_type != 'SubStatement') { } } if (isset($json_array['context'])) { $this->tincan_context = array(); $this->populateContext($json_array['context']); } }
/** * Implements hook_cis_remote_entities_insert_alter(). * * @param $return * Do something with the returned data, typically * the `nid` or `uuid` created in the remote bucket. * @param $bucket * which bucket this is in reference to. */ function hook_cis_remote_entities_insert(&$return, $bucket) { // turn this into a direct link for a node $tmp = drupal_json_decode($return); $settings = _cis_connector_build_registry($bucket); $url = $settings['protocol'] . '://' . $settings['address'] . '/node/' . $return['nid']; $return = l(t('click to access item'), $url); }
/** * Performs a Web Service JSON request * * @param $request_state * @see CommerceFirstDataGGE4Controller::resolvePaymentState() * * @return * An array of response parameters */ public function request(&$request_state) { $empty_response = array('transaction_approved' => 0, 'bank_message' => ''); // Exit if request is not valid if (!$this->requestValidate($request_state)) { // merge errors into response return $empty_response + array('validation_errors' => $request_state['validation_errors']); } // Build the request $params = $this->requestBuild($request_state); // Exit if empty request if (empty($params)) { return $empty_response; } // Add some request params to empty response $empty_response['transaction_type'] = $params['transaction_type']; // Get settings $settings = $this->getSettings(); $log_settings = $this->controller->getSettings('log'); // Add API credentials $params += array('gateway_id' => $settings['gateway_id'], 'password' => $settings['gateway_password']); /** @todo: live test mode parameter for WS?**/ // if ($this->controller->getSettings('txn_mode') == FIRSTDATA_GGE4_TXN_MODE_LIVE_TEST) // Get request url $request_url = $this->getServerUrl(); // Log the request if specified. if ($log_settings['request'] == 'request') { $this->controller->log('First Data GGe4 web service request', $params); } // Prepare the JSON string. ksort($params); $request_content = drupal_json_encode($params); $request_content_type = 'application/json'; // Add content headers $request_headers = array('Content-Type' => $request_content_type . '; charset=UTF-8', 'Accept' => $request_content_type, 'Content-Length' => strlen($request_content)); // Add security headers $request_headers += $this->generateSecurityRequestHeaders($request_headers['Content-Type'], $request_content, 'POST'); // Combine header keys and values foreach ($request_headers as $header_key => &$header_value) { $header_value = $header_key . ': ' . $header_value; } // Setup the cURL request. $curl_options = array(CURLOPT_URL => $request_url, CURLOPT_VERBOSE => 0, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $request_content, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_NOPROGRESS => 1, CURLOPT_FOLLOWLOCATION => 0, CURLOPT_FRESH_CONNECT => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 60, CURLOPT_HTTPHEADER => array_values($request_headers)); $ch = curl_init(); curl_setopt_array($ch, $curl_options); $raw_response = curl_exec($ch); // Check for cURL errors. $errorno = NULL; if ($errorno = curl_errno($ch)) { watchdog('commerce_firstdata_gge4', 'Error with cURL request: (@error_no). Message: @error_message', array('@error_no' => $errorno, '@error_message' => curl_error($ch)), WATCHDOG_ERROR); curl_close($ch); return $empty_response; } curl_close($ch); // @todo: Response Hash check // First Data calculates security hash using the response body. // This would require CURLOPT_HEADER => 1 and parsing the response into a // header and body, then extracting the headers for date, etc to calcualte. // Process response $response = drupal_json_decode($raw_response); // Handle empty / non-json responses if (empty($response)) { if (is_string($raw_response) && strlen($raw_response) > 0) { $error_message = $raw_response; } else { $error_message = t('Empty response from the gateway.'); } // Add custom error property $response = array('gge4_fatal_error' => $error_message, 'bank_message' => $error_message, 'transaction_approved' => 0) + $empty_response; watchdog('commerce_firstdata_gge4', 'Request error: @error_message', array('@error_message' => $error_message), WATCHDOG_ERROR); } // Sort alphabetically ksort($response); // Create / Update Commerce payment transaction $transaction = $this->controller->saveTransaction($response, $request_state); if ($transaction) { $request_state['transaction'] = $transaction; } // Allow other plugins and modules to react to non-fatal responses if (empty($response['gge4_fatal_error'])) { $event_context = array('plugin' => $this->plugin['name'], 'response' => $response, 'state' => $request_state); $this->controller->trigger('response_process', $event_context); } // Log the response if specified. if ($log_settings['response'] == 'response') { $this->controller->log('First Data GGe4 web service response', $response); } return $this->controller->sanitizeParameters($response); }
function toArray() { return drupal_json_decode($this->json); }
/** * Execute a POST request on an AJAX path and JSON decode the result. */ protected function drupalPostAJAX($path, $edit, $triggering_element, $ajax_path = 'system/ajax', array $options = array(), array $headers = array()) { return drupal_json_decode($this->drupalPost($path, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers)); }
/** * Execute an AJAX submission. * * This executes a POST as ajax.js does. It uses the returned JSON data, an * array of commands, to update $this->content using equivalent DOM * manipulation as is used by ajax.js. It also returns the array of commands. * * @see ajax.js */ protected function drupalPostAJAX($path, $edit, $triggering_element, $ajax_path = 'system/ajax', array $options = array(), array $headers = array(), $form_html_id = NULL, $ajax_settings = array()) { // Get the content of the initial page prior to calling drupalPost(), since // drupalPost() replaces $this->content. if (isset($path)) { $this->drupalGet($path, $options); } $content = $this->drupalGetContent(); $return = drupal_json_decode($this->drupalPost(NULL, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers, $form_html_id)); // We need $ajax_settings['wrapper'] to perform DOM manipulation. if (!empty($ajax_settings) && !empty($return)) { // DOM can load HTML soup. But, HTML soup can throw warnings, suppress // them. @($dom = DOMDocument::loadHTML($content)); foreach ($return as $command) { // @todo ajax.js can process commands other than 'insert' and can // process commands that include a 'selector', but these are hard to // emulate with DOMDocument. For now, we only implement 'insert' // commands that use $ajax_settings['wrapper']. if ($command['command'] == 'insert' && !isset($command['selector'])) { // $dom->getElementById() doesn't work when drupalPostAJAX() is // invoked multiple times for a page, so use XPath instead. This also // sets us up for adding support for $command['selector'], though it // will require transforming a jQuery selector to XPath. $xpath = new DOMXPath($dom); $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0); if ($wrapperNode) { // ajax.js adds an enclosing DIV to work around a Safari bug. $newDom = new DOMDocument(); $newDom->loadHTML('<div>' . $command['data'] . '</div>'); $newNode = $dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE); $method = isset($command['method']) ? $command['method'] : $ajax_settings['method']; // The "method" is a jQuery DOM manipulation function. Emulate each // one using PHP's DOMNode API. switch ($method) { case 'replaceWith': $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode); break; case 'append': $wrapperNode->appendChild($newNode); break; case 'prepend': // If no firstChild, insertBefore() falls back to appendChild(). $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild); break; case 'before': $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode); break; case 'after': // If no nextSibling, insertBefore() falls back to appendChild(). $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling); break; case 'html': foreach ($wrapperNode->childNodes as $childNode) { $wrapperNode->removeChild($childNode); } $wrapperNode->appendChild($newNode); break; } } } } $this->drupalSetContent($dom->saveHTML()); } return $return; }
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) $elements_pr_page = 8;
public function doGet($parameters, $addDownload = true) { //drupal_http_build_query($parameters); $options['headers']['Content-Type'] = 'application/json'; $options['headers']['Accept-Encoding'] = 'gzip, deflate'; $options['method'] = 'get'; //'post'; //$options['data'] = drupal_http_build_query($parameters);//json_encode($send); $options['timeout'] = 3000000000.0; global $DEBUG; if ($DEBUG) { $f = fopen("/tmp/proxyPost.log", "a"); fwrite($f, "CALL: GET='" . var_export($options, TRUE) . "'\n"); } $postServer = $this->server; if ($addDownload) { $postServer .= '/download'; } //Hack to test if get works like this. $postServer .= "?" . drupal_http_build_query($parameters); $result = _bim_http_request($postServer, $options); //bimserverJsonConnector::_bim_http_request($postServer, $options); if ($result->headers['Content-Encoding'] == 'gzip' || $result->headers['content-encoding'] == 'gzip') { $result->data2 = substr($result->data, 10); $result->data3 = gzinflate(substr($result->data, 10)); $result->data = drupal_json_decode(gzinflate(substr($result->data, 10))); if (isset($result->headers['Content-Encoding'])) { unset($result->headers['Content-Encoding']); $result->headers['Content-Encoding'] = "text/plain"; } if (isset($result->headers['content-encoding'])) { unset($result->headers['content-encoding']); $result->headers['content-encoding'] = "text/plain"; } //$result->headers['Content-Encoding'] = "text/plain"; } if ($DEBUG) { fwrite($f, "AWNS: \t'" . var_export($result, TRUE) . "'\n"); fclose($f); } //dsm($result); /* if ($shorten) { if (empty($result->data)) { $result = $result; //->data; } else { $result = drupal_json_decode($result->data); } } else { if (!empty($result->data)) { $result->data = drupal_json_decode($result->data); } }*/ return $result; }