/** * Creates a node, then tests the statistics tokens generated from it. */ function testStatisticsTokenReplacement() { $language_interface = \Drupal::languageManager()->getCurrentLanguage(); // Create user and node. $user = $this->drupalCreateUser(array('create page content')); $this->drupalLogin($user); $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $user->id())); // Hit the node. $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::httpClient(); $client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10)); $client->post($stats_path, array('headers' => $headers, 'body' => $post)); $statistics = statistics_get($node->id()); // Generate and test tokens. $tests = array(); $tests['[node:total-count]'] = 1; $tests['[node:day-count]'] = 1; $tests['[node:last-view]'] = format_date($statistics['timestamp']); $tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short'); // Test to make sure that we generated something for each token. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.'); foreach ($tests as $input => $expected) { $output = \Drupal::token()->replace($input, array('node' => $node), array('langcode' => $language_interface->getId())); $this->assertEqual($output, $expected, format_string('Statistics token %token replaced.', array('%token' => $input))); } }
public function request($path, $query_array = array(), $options = array()) { $parse_url = parse_url($path); if (isset($parse_url['scheme']) && !empty($parse_url['scheme'])) { $validate_url = $path; } else { $validate_url = API_DOMAIN . $path; } $method = isset($options['method']) ? strtolower($options['method']) : 'get'; $post_data = isset($options['post_data']) ? $options['post_data'] : array(); $content_type = isset($options['content_type']) ? $options['content_type'] : 'form_params'; $ssl_verify = isset($options['ssl_verify']) ? $options['ssl_verify'] : FALSE; $httpclient_options['verify'] = $ssl_verify; if ($method == 'post') { $httpclient_options[$content_type] = $post_data; } if ($query_array !== FALSE) { $validate_url .= '?' . LoginRadius::queryBuild(LoginRadius::authentication($query_array)); } try { $response = \Drupal::httpClient()->{$method}($validate_url, $httpclient_options); $data = (string) $response->getBody(); return $data; } catch (RequestException $e) { throw new LoginRadiusException($e->getMessage(), $e); } catch (ClientException $e) { throw new LoginRadiusException($e->getMessage(), $e); } catch (Exception $e) { throw new LoginRadiusException($e->getMessage(), $e); } }
/** * 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->blocking_user->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::httpClient(); $client->setDefaultOption('config/curl', array(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.'); $this->assertRaw(l($node->label(), 'node/' . $node->id()), 'Found link to visited node.'); }
/** * Returns the content of the enclosre as a string. * * @return string|false * The content of the referenced resource, or false if the file could not be * read. This should be checked with an ===, since an empty string could be * returned. * * @throws \RuntimeException * Thrown if the download failed. * * @todo Better error handling. */ public function getContent() { $response = \Drupal::httpClient()->get($this->uri)->send(); if ($response->getStatusCode() != 200) { $args = ['%url' => $this->uri, '@code' => $response->getStatusCode()]; throw new \RuntimeException(SafeMarkup::format('Download of %url failed with code @code.', $args)); } return $response->getBody(TRUE); }
/** * Submit the POST request with the specified parameters. * * @param RequestParameters $params * Request parameters * * @return string * Body of the reCAPTCHA response */ public function submit(RequestParameters $params) { try { $options = ['headers' => ['Content-type' => 'application/x-www-form-urlencoded'], 'body' => $params->toQueryString()]; $response = \Drupal::httpClient()->post(self::SITE_VERIFY_URL, $options); } catch (RequestException $exception) { \Drupal::logger('reCAPTCHA web service')->error($exception); } return (string) $response->getBody(); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installEntitySchema('file'); $entity_manager = \Drupal::entityManager(); $link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default'), \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack')), new RelationLinkManager(new MemoryBackend('default'), $entity_manager, \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack'))); // Set up the mock serializer. $normalizers = array(new FieldItemNormalizer(), new FileEntityNormalizer($entity_manager, \Drupal::httpClient(), $link_manager, \Drupal::moduleHandler())); $encoders = array(new JsonEncoder()); $this->serializer = new Serializer($normalizers, $encoders); }
/** * Starts a background job using a new process. * * @param \Drupal\feeds\FeedInterface $feed * The feed to start the job for. * @param string $method * Method to execute on importer; one of 'import' or 'clear'. * * @throws Exception $e * * @todo Inject these dependencies. */ protected function startBackgroundJob(FeedInterface $feed, $method) { $cid = 'feeds_feed:' . $feed->id(); $token = Crypt::randomStringHashed(55); \Drupal::state()->set($cid, array('token' => $token, 'method' => $method)); $client = \Drupal::httpClient(); // Do not wait for a response. $client->addSubscriber(new AsyncPlugin()); $url = $this->url('feeds.execute', array('feeds_feed' => $feed->id()), array('absolute' => TRUE)); $request = $client->post($url)->addPostFields(array('token' => $token)); $request->send(); }
protected function setUp() { parent::setUp(); // Create Basic page node type. if ($this->profile != 'standard') { $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); } $this->privilegedUser = $this->drupalCreateUser(array('administer statistics', 'view post access counter', 'create page content')); $this->drupalLogin($this->privilegedUser); $this->testNode = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->privilegedUser->id())); $this->client = \Drupal::httpClient(); $this->client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10)); }
/** * Generates an example page. */ public function content() { // Get module configuration. $module_config = \Drupal::config('weather.settings'); $this->key = $module_config->get('key'); // Create a HTTP client. $client = \Drupal::httpClient(); // Set default options. $client->setDefaultOption('timeout', self::WEATHER_TIMEOUT); // Create a request GET object. $request = $client->createRequest('GET', self::WEATHER_API_URL); // Filter on Key. if ($this->key != '') { $filter = "SecureGuid eq '" . $this->key . "'"; } else { drupal_set_message('Set up you IBP Catalog key', 'status', TRUE); return FALSE; } // Add a few query strings. $query = $request->getQuery(); $query->set('$filter', $filter); try { $response = $client->send($request); } catch (RequestException $e) { drupal_set_message('Bad request', 'error', TRUE); return FALSE; } catch (\Exception $e) { drupal_set_message('Bad request', 'error', TRUE); return FALSE; } // If success. if ($response->getStatusCode() == 200) { // We are expecting XML content. $xml = $response->xml(); $compt = 0; foreach ($xml->xpath('//m:properties') as $properties) { $d = $properties->children('http://schemas.microsoft.com/ado/2007/08/dataservices'); $rows[$compt]['url'] = String::checkPlain($d->CalculatedUrl); $rows[$compt]['language'] = String::checkPlain($d->Language); $rows[$compt]['subcategoryfr'] = String::checkPlain($d->SubCategoryFR); $rows[$compt]['friendlysizekey'] = String::checkPlain($d->FriendlySizeKey); $rows[$compt]['productdomaincodedescriptionfr'] = String::checkPlain($d->ProductDomainCodeDescriptionFR); $rows[$compt++]['companyname'] = String::checkPlain($d->CompanyName); } } $header = array('URL', 'Language', 'Category Description', 'FriendlySizeKey', 'Product', 'Company'); $table = array('#type' => 'table', '#header' => $header, '#rows' => $rows, '#attributes' => array('id' => 'book-outline'), '#empty' => t('No item available.')); return drupal_render($table); }
/** * Generates an example page. */ public function response($date, $location, $hourly_interval) { /** * Weather API URL. */ $WEATHER_API_URL = 'http://api.worldweatheronline.com/free/v2/weather.ashx?q=' . $location . '&date=' . $date . '&tp=' . $hourly_interval . '&key=ade5f8b9d77a3eb016b7515df6464&format=json'; // Create a HTTP client. $client = \Drupal::httpClient(); // Create a request GET object. $response = $client->get($WEATHER_API_URL); #$request = $client->createRequest('GET', self::WEATHER_API_URL, []); if ($response->getStatusCode() == 200) { return json_decode($response->getBody(), TRUE); } }
public function decode($url) { // Clients will only throw exceptions that are a subclass of GuzzleHttp\Exception\RequestException. try { // Create a HTTP client. $response = \Drupal::httpClient()->get($url)->getBody(TRUE); } catch (RequestException $e) { // Do some stuff in case of the error. } // If successful HTTP query. if ($response) { $data = $response->getContents(); return Json::decode($data); } else { return NULL; } }
protected function setUp() { parent::setUp(); // Create Basic page node type. if ($this->profile != 'standard') { $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); } $this->authUser = $this->drupalCreateUser(array('access content', 'create page content', 'edit own page content')); // Ensure we have a node page to access. $this->node = $this->drupalCreateNode(array('title' => $this->randomMachineName(255), 'uid' => $this->authUser->id())); // Enable access logging. $this->config('statistics.settings')->set('count_content_views', 1)->save(); // Clear the logs. db_truncate('node_counter'); $this->client = \Drupal::httpClient(); $this->client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10)); }
/** * Generates a new ZOHO Auth Token and stores in db. * * @param string $username * User name of the Zoho crm account * @param string $pass * Password for Zoho crm account * * @returns array * Returns an array with authtoken if success and error otherwise. */ function zoho_generate_authtoken($username, $pass) { $url = ZOHO_TICKET_URL . "apiauthtoken/nb/create?SCOPE=ZohoCRM/crmapi&EMAIL_ID=" . $username . "&PASSWORD="******"\n", $result); $authtoken = explode("=", $anarray['2']); $cmp = strcmp($authtoken['0'], "AUTHTOKEN"); if ($cmp == 0) { return array('authtoken' => $authtoken['1']); } else { return array('error' => $authtoken['1']); } } catch (RequestException $ex) { watchdog_exception('zoho', $ex); return array('error' => $ex); } }
/** * {@inheritdoc} */ public function build() { $config = $this->getConfiguration(); if (!empty($config['unibuc_weather_api_key'])) { $url = 'http://api.openweathermap.org/data/2.5/forecast/city?id=683506&APPID=' . $config['unibuc_weather_api_key']; $data = (string) \Drupal::httpClient()->get($url)->getBody(); $data = json_decode($data); $temp = $data->list[0]->main->temp; $degree = $config['unibuc_weather_api_display']; if ($config['unibuc_weather_api_display'] == 'c') { $temp = $temp - 273; } else { $temp = $temp * 9 / 5 - 460; } return array('#markup' => $this->t('The temperature in @city is @temp @degree', array('@city' => 'Bucharest', '@temp' => $temp, '@degree' => strtoupper($degree)))); } else { return array('#markup' => $this->t("Please set your API Key from <a target='_blank' href='http://openweathermap.org/'>openweathermap.org</a>")); } }
/** * Tests the integration of the {node_counter} table in views. */ public function testNodeCounterIntegration() { $this->drupalGet('node/' . $this->node->id()); // Manually calling statistics.php, simulating ajax behavior. // @see \Drupal\statistics\Tests\StatisticsLoggingTest::testLogging(). global $base_url; $stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php'; $client = \Drupal::httpClient(); $client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10)); $client->post($stats_path, array('body' => array('nid' => $this->node->id()))); $this->drupalGet('test_statistics_integration'); $expected = statistics_get($this->node->id()); // Convert the timestamp to year, to match the expected output of the date // handler. $expected['timestamp'] = date('Y', $expected['timestamp']); foreach ($expected as $field => $value) { $xpath = "//div[contains(@class, views-field-{$field})]/span[@class = 'field-content']"; $this->assertFieldByXpath($xpath, $value, "The {$field} output matches the expected."); } }
/** * Tests access to routes protected by CSRF request header requirements. * * This checks one route that uses _csrf_request_header_token and one that * uses the deprecated _access_rest_csrf. */ public function testRouteAccess() { $client = \Drupal::httpClient(); $csrf_token_paths = ['deprecated/session/token', 'session/token']; // Test using the both the current path and a test path that returns // a token using the deprecated 'rest' value. // Checking /deprecated/session/token can be removed in 8.3. // @see \Drupal\Core\Access\CsrfRequestHeaderAccessCheck::access() foreach ($csrf_token_paths as $csrf_token_path) { // Check both test routes. $route_names = ['csrf_test.protected', 'csrf_test.deprecated.protected']; foreach ($route_names as $route_name) { $user = $this->drupalCreateUser(); $this->drupalLogin($user); $csrf_token = $this->drupalGet($csrf_token_path); $url = Url::fromRoute($route_name)->setAbsolute(TRUE)->toString(); $domain = parse_url($url, PHP_URL_HOST); $session_id = $this->getSession()->getCookie($this->getSessionName()); /** @var \GuzzleHttp\Cookie\CookieJar $cookies */ $cookies = CookieJar::fromArray([$this->getSessionName() => $session_id], $domain); $post_options = ['headers' => ['Accept' => 'text/plain'], 'http_errors' => FALSE]; // Test that access is allowed for anonymous user with no token in header. $result = $client->post($url, $post_options); $this->assertEquals(200, $result->getStatusCode()); // Add cookies to POST options so that all other requests are for the // authenticated user. $post_options['cookies'] = $cookies; // Test that access is denied with no token in header. $result = $client->post($url, $post_options); $this->assertEquals(403, $result->getStatusCode()); // Test that access is allowed with correct token in header. $post_options['headers']['X-CSRF-Token'] = $csrf_token; $result = $client->post($url, $post_options); $this->assertEquals(200, $result->getStatusCode()); // Test that access is denied with incorrect token in header. $post_options['headers']['X-CSRF-Token'] = 'this-is-not-the-token-you-are-looking-for'; $result = $client->post($url, $post_options); $this->assertEquals(403, $result->getStatusCode()); } } }
/** * Checks that the auth options restricts access to a REST views display. */ public function testRestViewsAuthentication() { // Assume the view is hidden behind a permission. $this->drupalGetWithFormat('test/serialize/auth_with_perm', 'json'); $this->assertResponse(401); // Not even logging in would make it possible to see the view, because then // we are denied based on authentication method (cookie). $this->drupalLogin($this->adminUser); $this->drupalGetWithFormat('test/serialize/auth_with_perm', 'json'); $this->assertResponse(403); $this->drupalLogout(); // But if we use the basic auth authentication strategy, we should be able // to see the page. $url = $this->buildUrl('test/serialize/auth_with_perm'); $response = \Drupal::httpClient()->get($url, ['auth' => [$this->adminUser->getUsername(), $this->adminUser->pass_raw]]); // Ensure that any changes to variables in the other thread are picked up. $this->refreshVariables(); $headers = $response->getHeaders(); $this->verbose('GET request to: ' . $url . '<hr />Code: ' . curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE) . '<hr />Response headers: ' . nl2br(print_r($headers, TRUE)) . '<hr />Response body: ' . (string) $response->getBody()); $this->assertResponse(200); }
public function getCollection(\DateTime $date, $location) { $weather_collection = NULL; $WEATHER_API_URL = 'http://api.worldweatheronline.com/free/v2/weather.ashx?q=' . $location . '&date=' . $date->format('Y-m-d') . '&key=ade5f8b9d77a3eb016b7515df6464&format=json'; // Create a HTTP client. $client = \Drupal::httpClient(); // Create a request GET object. $response = $client->get($WEATHER_API_URL); if ($response->getStatusCode() == 200) { $raw = json_decode($response->getBody(), TRUE); foreach ($raw as $data => $interval) { //$date = $interval['weather'][0]['date']; $day_date = new \DateTime(); if ($interval['weather']) { $collections = $this->setIntervals($date, $interval); $this->collections = $collections; return $collections; } else { throw new Exception("Sorry we don't have hourly data for this time right now."); } } } }
/** * Initializes Mink sessions. */ protected function initMink() { $driver = $this->getDefaultDriverInstance(); if ($driver instanceof GoutteDriver) { $driver->getClient()->setClient(\Drupal::httpClient()); } $session = new Session($driver); $this->mink = new Mink(); $this->mink->registerSession('default', $session); $this->mink->setDefaultSessionName('default'); $this->registerSessions(); // According to the W3C WebDriver specification a cookie can only be set if // the cookie domain is equal to the domain of the active document. When the // browser starts up the active document is not our domain but 'about:blank' // or similar. To be able to set our User-Agent and Xdebug cookies at the // start of the test we now do a request to the front page so the active // document matches the domain. // @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie // @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975 $session = $this->getSession(); $session->visit($this->baseUrl); return $session; }
/** * {@inheritdoc} */ public function processDefinition(array &$definition, $plugin_id) { $provider_path = ProviderManager::FILE_PATH; file_prepare_directory($provider_path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS); // Process API data. if ($api = $this->getApi()) { // Use manually imported API data, if it exists. if (file_exists("{$provider_path}/{$plugin_id}.json") && ($imported_data = file_get_contents("{$provider_path}/{$plugin_id}.json"))) { $definition['imported'] = TRUE; $response = new Response(200, [], $imported_data); } else { $client = \Drupal::httpClient(); $request = new Request('GET', $api); try { $response = $client->send($request); } catch (RequestException $e) { $response = new Response(400); } } $contents = $response->getBody(TRUE)->getContents(); $json = Json::decode($contents) ?: []; $this->processApi($json, $definition); } }
/** * Constructs a DomainNegotiator object. * * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. */ public function __construct(ModuleHandlerInterface $module_handler) { $this->moduleHandler = $module_handler; // @TODO: Move to a proper service? $this->httpClient = \Drupal::httpClient(); }
/** * Performs GET requests for internal pages. * @param $url * @return \Psr\Http\Message\ResponseInterface */ protected function getInternal($url) { $client = \Drupal::httpClient(); try { $response = $client->get($url); } catch (RequestException $e) { watchdog_exception('feeds_youtube', $e->getMessage()); } return $response; }
/** * Performs a GET request. * * @param string $url * The URL to GET. * * @return \Guzzle\Http\Message\Response * A Guzzle response. */ protected function get($url, $cache = TRUE) { $url = strtr($url, array('feed://' => 'http://', 'webcal://' => 'http://')); $client = \Drupal::httpClient(); // Add our handy dandy cache plugin. It's magic. if ($cache) { $client->addSubscriber(new CachePlugin(\Drupal::cache())); } $request = $client->get($url); // Stream to a file to provide the best scenario for intellegent parsers. $tempname = drupal_tempnam('temporary://', 'feeds_download_cache_'); $request->setResponseBody($tempname); try { $response = $request->send(); } catch (BadResponseException $e) { $response = $e->getResponse(); $args = array('%url' => $url, '%error' => $response->getStatusCode() . ' ' . $response->getReasonPhrase()); watchdog('feeds', 'The feed %url seems to be broken due to "%error".', $args, WATCHDOG_WARNING); drupal_set_message($this->t('The feed %url seems to be broken because of error "%error".', $args, 'warning')); return FALSE; } catch (RequestException $e) { $args = array('%url' => $url, '%error' => $e->getMessage()); watchdog('feeds', 'The feed %url seems to be broken due to "%error".', $args, WATCHDOG_WARNING); drupal_set_message($this->t('The feed %url seems to be broken because of error "%error".', $args), 'warning'); return FALSE; } return $response; }
/** * Processes Instant Payment Notifications from PayPal. * * @param array $ipn * The IPN data. */ protected function processIpn($ipn) { $amount = $ipn['mc_gross']; $email = !empty($ipn['business']) ? $ipn['business'] : $ipn['receiver_email']; $txn_id = $ipn['txn_id']; if (!isset($ipn['invoice'])) { \Drupal::logger('uc_paypal')->error('IPN attempted with invalid order ID.'); return; } // Extract order and cart IDs. $order_id = $ipn['invoice']; if (strpos($order_id, '-') > 0) { list($order_id, $cart_id) = explode('-', $order_id); \Drupal::service('session')->set('uc_cart_id', $cart_id); } $order = Order::load($order_id); if (!$order) { \Drupal::logger('uc_paypal')->error('IPN attempted for non-existent order @order_id.', ['@order_id' => $order_id]); return; } // @todo Send method name and order ID in the IPN URL? $config = \Drupal::service('plugin.manager.uc_payment.method')->createFromOrder($order)->getConfiguration(); // Optionally log IPN details. if (!empty($config['wps_debug_ipn'])) { \Drupal::logger('uc_paypal')->notice('Receiving IPN at URL for order @order_id. <pre>@debug</pre>', ['@order_id' => $order_id, '@debug' => print_r($ipn, TRUE)]); } // Express Checkout IPNs may not have the WPS email stored. But if it is, // make sure that the right account is being paid. if (!empty($config['wps_email']) && Unicode::strtolower($email) != Unicode::strtolower($config['wps_email'])) { \Drupal::logger('uc_paypal')->error('IPN for a different PayPal account attempted.'); return; } // Determine server. if (empty($data['test_ipn'])) { $host = 'https://www.paypal.com/cgi-bin/webscr'; } else { $host = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } // POST IPN data back to PayPal to validate. try { $response = \Drupal::httpClient()->request('POST', $host, ['form_params' => ['cmd' => '_notify-validate'] + $ipn]); } catch (TransferException $e) { \Drupal::logger('uc_paypal')->error('IPN validation failed with HTTP error %error.', ['%error' => $e->getMessage()]); return; } // Check IPN validation response to determine if the IPN was valid.. if ($response->getBody() != 'VERIFIED') { \Drupal::logger('uc_paypal')->error('IPN transaction failed verification.'); uc_order_comment_save($order_id, 0, $this->t('An IPN transaction failed verification for this order.'), 'admin'); return; } // Check for a duplicate transaction ID. $duplicate = (bool) db_query_range('SELECT 1 FROM {uc_payment_paypal_ipn} WHERE txn_id = :id AND status <> :status', 0, 1, [':id' => $txn_id, ':status' => 'Pending'])->fetchField(); if ($duplicate) { if ($order->getPaymentMethodId() != 'credit') { \Drupal::logger('uc_paypal')->notice('IPN transaction ID has been processed before.'); } return; } db_insert('uc_payment_paypal_ipn')->fields(array('order_id' => $order_id, 'txn_id' => $txn_id, 'txn_type' => $ipn['txn_type'], 'mc_gross' => $amount, 'status' => $ipn['payment_status'], 'receiver_email' => $email, 'payer_email' => $ipn['payer_email'], 'received' => REQUEST_TIME))->execute(); switch ($ipn['payment_status']) { case 'Canceled_Reversal': uc_order_comment_save($order_id, 0, $this->t('PayPal has canceled the reversal and returned @amount @currency to your account.', ['@amount' => uc_currency_format($amount, FALSE), '@currency' => $ipn['mc_currency']]), 'admin'); break; case 'Completed': if (abs($amount - $order->getTotal()) > 0.01) { \Drupal::logger('uc_paypal')->warning('Payment @txn_id for order @order_id did not equal the order total.', ['@txn_id' => $txn_id, '@order_id' => $order->id(), 'link' => Link::createFromRoute($this->t('view'), 'entity.uc_order.canonical', ['uc_order' => $order->id()])->toString()]); } $comment = $this->t('PayPal transaction ID: @txn_id', ['@txn_id' => $txn_id]); uc_payment_enter($order_id, 'paypal_wps', $amount, $order->getOwnerId(), NULL, $comment); uc_order_comment_save($order_id, 0, $this->t('PayPal IPN reported a payment of @amount @currency.', ['@amount' => uc_currency_format($amount, FALSE), '@currency' => $ipn['mc_currency']])); break; case 'Denied': uc_order_comment_save($order_id, 0, $this->t("You have denied the customer's payment."), 'admin'); break; case 'Expired': uc_order_comment_save($order_id, 0, $this->t('The authorization has failed and cannot be captured.'), 'admin'); break; case 'Failed': uc_order_comment_save($order_id, 0, $this->t("The customer's attempted payment from a bank account failed."), 'admin'); break; case 'Pending': $order->setStatusId('paypal_pending')->save(); uc_order_comment_save($order_id, 0, $this->t('Payment is pending at PayPal: @reason', ['@reason' => $this->pendingMessage($ipn['pending_reason'])]), 'admin'); break; // You, the merchant, refunded the payment. // You, the merchant, refunded the payment. case 'Refunded': $comment = $this->t('PayPal transaction ID: @txn_id', ['@txn_id' => $txn_id]); uc_payment_enter($order_id, 'paypal_wps', $amount, $order->getOwnerId(), NULL, $comment); break; case 'Reversed': \Drupal::logger('uc_paypal')->error('PayPal has reversed a payment!'); uc_order_comment_save($order_id, 0, $this->t('Payment has been reversed by PayPal: @reason', ['@reason' => $this->reversalMessage($ipn['reason_code'])]), 'admin'); break; case 'Processed': uc_order_comment_save($order_id, 0, $this->t('A payment has been accepted.'), 'admin'); break; case 'Voided': uc_order_comment_save($order_id, 0, $this->t('The authorization has been voided.'), 'admin'); break; } }
/** * {@inheritdoc} */ public function __construct(array $configuration, $plugin_id, $plugin_definition) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->httpClient = \Drupal::httpClient(); }
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { parent::validateForm($form, $form_state); // Custom variables validation. foreach ($form_state->getValue(['piwik_custom_var', 'slots']) as $custom_var) { $form_state->setValue(['piwik_custom_var', 'slots', $custom_var['slot'], 'name'], trim($custom_var['name'])); $form_state->setValue(['piwik_custom_var', 'slots', $custom_var['slot'], 'value'], trim($custom_var['value'])); // Validate empty names/values. if (empty($custom_var['name']) && !empty($custom_var['value'])) { $form_state->setErrorByName("piwik_custom_var][slots][" . $custom_var['slot'] . "][name", t('The custom variable @slot-number requires a <em>Name</em> if a <em>Value</em> has been provided.', ['@slot-number' => $custom_var['slot']])); } elseif (!empty($custom_var['name']) && empty($custom_var['value'])) { $form_state->setErrorByName("piwik_custom_var][slots][" . $custom_var['slot'] . "][value", t('The custom variable @slot-number requires a <em>Value</em> if a <em>Name</em> has been provided.', ['@slot-number' => $custom_var['slot']])); } } $form_state->setValue('piwik_custom_var', $form_state->getValue(['piwik_custom_var', 'slots'])); // Trim some text area values. $form_state->setValue('piwik_site_id', trim($form_state->getValue('piwik_site_id'))); $form_state->setValue('piwik_visibility_request_path_pages', trim($form_state->getValue('piwik_visibility_request_path_pages'))); $form_state->setValue('piwik_codesnippet_before', trim($form_state->getValue('piwik_codesnippet_before'))); $form_state->setValue('piwik_codesnippet_after', trim($form_state->getValue('piwik_codesnippet_after'))); $form_state->setValue('piwik_visibility_user_role_roles', array_filter($form_state->getValue('piwik_visibility_user_role_roles'))); $form_state->setValue('piwik_trackmessages', array_filter($form_state->getValue('piwik_trackmessages'))); if (!preg_match('/^\\d{1,}$/', $form_state->getValue('piwik_site_id'))) { $form_state->setErrorByName('piwik_site_id', t('A valid Piwik site ID is an integer only.')); } $url = $form_state->getValue('piwik_url_http') . 'piwik.php'; try { $result = \Drupal::httpClient()->get($url); if ($result->getStatusCode() != 200 && $form_state->getValue('piwik_url_skiperror') == FALSE) { $form_state->setErrorByName('piwik_url_http', t('The validation of "@url" failed with error "@error" (HTTP code @code).', ['@url' => UrlHelper::filterBadProtocol($url), '@error' => $result->getReasonPhrase(), '@code' => $result->getStatusCode()])); } } catch (RequestException $exception) { $form_state->setErrorByName('piwik_url_http', t('The validation of "@url" failed with an exception "@error" (HTTP code @code).', ['@url' => UrlHelper::filterBadProtocol($url), '@error' => $exception->getMessage(), '@code' => $exception->getCode()])); } $piwik_url_https = $form_state->getValue('piwik_url_https'); if (!empty($piwik_url_https)) { $url = $piwik_url_https . 'piwik.php'; try { $result = \Drupal::httpClient()->get($url); if ($result->getStatusCode() != 200 && $form_state->getValue('piwik_url_skiperror') == FALSE) { $form_state->setErrorByName('piwik_url_https', t('The validation of "@url" failed with error "@error" (HTTP code @code).', ['@url' => UrlHelper::filterBadProtocol($url), '@error' => $result->getReasonPhrase(), '@code' => $result->getStatusCode()])); } } catch (RequestException $exception) { $form_state->setErrorByName('piwik_url_https', t('The validation of "@url" failed with an exception "@error" (HTTP code @code).', ['@url' => UrlHelper::filterBadProtocol($url), '@error' => $exception->getMessage(), '@code' => $exception->getCode()])); } } // Verify that every path is prefixed with a slash, but don't check PHP // code snippets. if ($form_state->getValue('piwik_visibility_request_path_mode') != 2) { $pages = preg_split('/(\\r\\n?|\\n)/', $form_state->getValue('piwik_visibility_request_path_pages')); foreach ($pages as $page) { if (strpos($page, '/') !== 0 && $page !== '<front>') { $form_state->setErrorByName('piwik_visibility_request_path_pages', t('Path "@page" not prefixed with slash.', ['@page' => $page])); // Drupal forms show one error only. break; } } } // Clear obsolete local cache if cache has been disabled. if ($form_state->isValueEmpty('piwik_cache') && $form['advanced']['piwik_cache']['#default_value']) { piwik_clear_js_cache(); } // This is for the Newbie's who cannot read a text area description. if (preg_match('/(.*)<\\/?script(.*)>(.*)/i', $form_state->getValue('piwik_codesnippet_before'))) { $form_state->setErrorByName('piwik_codesnippet_before', t('Do not include the <script> tags in the javascript code snippets.')); } if (preg_match('/(.*)<\\/?script(.*)>(.*)/i', $form_state->getValue('piwik_codesnippet_after'))) { $form_state->setErrorByName('piwik_codesnippet_after', t('Do not include the <script> tags in the javascript code snippets.')); } }
/** * Load CDN version optios. */ function _bootstrap_library_cdn_versions() { static $uri = 'http://netdna.bootstrapcdn.com/data/bootstrapcdn.json'; $json_response = NULL; try { $client = \Drupal::httpClient(); $response = $client->get($uri, array('headers' => array('Accept' => 'text/plain'))); $data = (string) $response->getBody(); if (empty($data)) { return FALSE; } } catch (RequestException $e) { watchdog_exception('bootstrap_library', $e->getMessage()); return FALSE; } return $data; }
/** * Tests import and export for the XLIFF format. */ function testXLIFF() { $translator = Translator::load('file'); $translator->setSetting('export_format', 'xlf')->save(); // Set multiple data items for the source. \Drupal::state()->set('tmgmt.test_source_data', array('dummy' => array('deep_nesting' => array('#text' => 'Text of deep nested item @id.', '#label' => 'Label of deep nested item @id')), 'another_item' => array('#text' => 'Text of another item @id.', '#label' => 'Label of another item @id.'))); $job = $this->createJob(); $job->translator = $translator->id(); $first_item = $job->addItem('test_source', 'test', '1'); // Keep the first item data for later use. $first_item_data = \Drupal::service('tmgmt.data')->flatten($first_item->getData()); $job->addItem('test_source', 'test', '2'); $job->requestTranslation(); $messages = $job->getMessages(); $message = reset($messages); $variables = $message->variables; $download_url = $variables->{'@link'}; $this->assertFalse((bool) strpos('< a', $download_url)); $xliff = file_get_contents($download_url); $dom = new \DOMDocument(); $dom->loadXML($xliff); $this->assertTrue($dom->schemaValidate(drupal_get_path('module', 'tmgmt_file') . '/xliff-core-1.2-strict.xsd')); // "Translate" items. $xml = simplexml_import_dom($dom); $translated_text = array(); foreach ($xml->file->body->children() as $group) { foreach ($group->children() as $transunit) { if ($transunit->getName() == 'trans-unit') { // The target should be empty. $this->assertEqual($transunit->target, ''); $transunit->target = $xml->file['target-language'] . '_' . (string) $transunit->source; // Store the text to allow assertions later on. $translated_text[(string) $group['id']][(string) $transunit['id']] = (string) $transunit->target; } } } // Change the job id to a non-existing one and try to import it. $wrong_xml = clone $xml; $wrong_xml->file->header->{'phase-group'}->phase['job-id'] = 500; $wrong_file = 'public://tmgmt_file/wrong_file.xlf'; $wrong_xml->asXML($wrong_file); $edit = array('files[file]' => $wrong_file); $this->drupalPostForm($job->urlInfo(), $edit, t('Import')); $this->assertText(t('Failed to validate file, import aborted.')); // Change the job id to a wrong one and try to import it. $wrong_xml = clone $xml; $second_job = $this->createJob(); $second_job->translator = $translator->id(); // We need to add the elements count value into settings, otherwise the // validation will fail on integrity check. $xliff_validation = array(1 => 0, 2 => 0); $second_job->settings->xliff_validation = $xliff_validation; $second_job->save(); $wrong_xml->file->header->{'phase-group'}->phase['job-id'] = $second_job->id(); $wrong_file = 'public://tmgmt_file/wrong_file.xlf'; $wrong_xml->asXML($wrong_file); $edit = array('files[file]' => $wrong_file); $this->drupalPostForm($job->urlInfo(), $edit, t('Import')); $this->assertRaw(t('The imported file job id @file_id does not match the job id @job_id.', array('@file_id' => $second_job->id(), '@job_id' => $job->id()))); $translated_file = 'public://tmgmt_file/translated file.xlf'; $xml->asXML($translated_file); // Import the file and accept translation for the "dummy" item. $edit = array('files[file]' => $translated_file); $this->drupalPostForm($job->urlInfo(), $edit, t('Import')); $this->assertText(t('The translation of @job_item to German is finished and can now be reviewed.', ['@job_item' => $first_item->label()])); $this->clickLink(t('Review')); $this->drupalPostAjaxForm(NULL, NULL, array('reviewed-dummy|deep_nesting' => '✓')); // Update the translation for "another" item and import. $xml->file->body->group[0]->{'trans-unit'}[1]->target = $xml->file->body->group[0]->{'trans-unit'}[1]->target . ' updated'; $xml->asXML($translated_file); $edit = array('files[file]' => $translated_file); $this->drupalPostForm($job->urlInfo(), $edit, t('Import')); // At this point we must have the "dummy" item accepted and intact. The // "another" item must have updated translation. $this->clickLink(t('Review')); $this->assertFieldByName('dummy|deep_nesting[translation]', 'de_' . $first_item_data['dummy][deep_nesting']['#text']); $this->assertFieldByName('another_item[translation]', 'de_' . $first_item_data['another_item']['#text'] . ' updated'); // Now finish the import/save as completed process doing another extra // import. The extra import will test that a duplicate import of the same // file does not break the process. $this->importFile($translated_file, $translated_text, $job); $this->assertNoText(t('Import translated file')); // Create a job, assign to the file translator and delete before attaching // a file. $other_job = $this->createJob(); $other_job->translator = $translator->id(); $other_job->save(); $other_job->delete(); // Make sure the file of the other job still exists. $response = \Drupal::httpClient()->get($download_url); $this->assertEqual(200, $response->getStatusCode()); // Delete the job and then make sure that the file has been deleted. $job->delete(); try { $response = \Drupal::httpClient()->get($download_url); $this->fail('Expected exception not thrown.'); } catch (RequestException $e) { $this->assertEqual(404, $e->getResponse()->getStatusCode()); } }
/** * Tests the httpClient() method. * * @covers ::httpClient */ public function testHttpClient() { $this->setMockContainerService('http_client'); $this->assertNotNull(\Drupal::httpClient()); }
/** * @return bool TRUE if test HTPPS connection returns 200, FALSE otherwise. */ public function securePagesTestHttpsConnection() { global $base_url; //Makes a request for the test HTTPS Connection route. $client = \Drupal::httpClient(); try { //Ignores SSL certificate validation. //@TODO Find a better way to handle that. Full discussion at: https://github.com/d8-contrib-modules/securepages/issues/6 $options = array('verify' => FALSE); $testHttpsConnectionUrl = Url::fromRoute($this::SECURE_PAGES_TEST_HTTPS_CONNECTION_ROUTE, array(), array('absolute' => TRUE))->toString(); $request = $client->request('GET', $this->securePagesGenerateUrl($base_url, $testHttpsConnectionUrl, TRUE), $options); } catch (RequestException $e) { return FALSE; } return method_exists($request, 'getStatusCode') && $request->getStatusCode() == 200; }