Esempio n. 1
1
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Validate video URL.
     if (!UrlHelper::isValid($form_state->getValue('video'), TRUE)) {
         $form_state->setErrorByName('video', $this->t("The video url '%url' is invalid.", array('%url' => $form_state->getValue('video'))));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (isset($value)) {
         $url_is_valid = TRUE;
         /** @var $link_item \Drupal\link\LinkItemInterface */
         $link_item = $value;
         $link_type = $link_item->getFieldDefinition()->getSetting('link_type');
         $url_string = $link_item->url;
         // Validate the url property.
         if ($url_string !== '') {
             try {
                 // @todo This shouldn't be needed, but massageFormValues() may not
                 //   run.
                 $parsed_url = UrlHelper::parse($url_string);
                 $url = Url::createFromPath($parsed_url['path']);
                 if ($url->isExternal() && !UrlHelper::isValid($url_string, TRUE)) {
                     $url_is_valid = FALSE;
                 } elseif ($url->isExternal() && !($link_type & LinkItemInterface::LINK_EXTERNAL)) {
                     $url_is_valid = FALSE;
                 }
             } catch (NotFoundHttpException $e) {
                 $url_is_valid = FALSE;
             } catch (MatchingRouteNotFoundException $e) {
                 $url_is_valid = FALSE;
             } catch (ParamNotConvertedException $e) {
                 $url_is_valid = FALSE;
             }
         }
         if (!$url_is_valid) {
             $this->context->addViolation($this->message, array('%url' => $url_string));
         }
     }
 }
Esempio n. 3
0
File: Link.php Progetto: Tawreh/mtg
 /**
  * {@inheritdoc}
  */
 protected function prepareValue($delta, array &$values)
 {
     $values['uri'] = trim($values['uri']);
     if (!UrlHelper::isValid($values['uri'], TRUE)) {
         $values['uri'] = '';
     }
 }
 /**
  * {@inheritdoc}
  */
 public function blockValidate($form, FormStateInterface $form_state)
 {
     // Instantiate UrlHelper object to validate the URL's.
     $url_helper = new UrlHelper();
     // Build an array of the links that need validating. If more fields are
     // added later, add another entry to the links array.
     $links = [];
     $links['pantheon_url'] = $form_state->getValue('pantheon_url');
     // Create an error variable to prevent setting the error message repeatedly.
     $error_set = FALSE;
     // Validate and set errors where appropriate.
     foreach ($links as $key => $link) {
         if ($link == '') {
             break;
         }
         $validity = $url_helper->isValid($link, TRUE);
         if ($validity != TRUE) {
             $form_state->setErrorByName($key, "The value must be a full URL similar to http://www.example.com.");
             // Using drupal_set_message because of a bug with setError that is
             // causing the form to not submit correctly, but isn't displaying
             // messages.
             if ($error_set == FALSE) {
                 drupal_set_message('All values must be full URLs of format: http://www.example.com.', 'error');
                 // Prevent the error from outputting multiple times.
                 $error_set = TRUE;
             }
         }
     }
 }
Esempio n. 5
0
 /**
  * Form element validation handler for #type 'url'.
  *
  * Note that #maxlength and #required is validated by _form_validate() already.
  */
 public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $value = trim($element['#value']);
     $form_state->setValueForElement($element, $value);
     if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
         $form_state->setError($element, t('The URL %url is not valid.', array('%url' => $value)));
     }
 }
Esempio n. 6
0
 /**
  * {@inheritdoc}
  */
 public static function validateValue(array &$element, FormStateInterface $form_state, array $form)
 {
     if (!empty($element['#value'])) {
         if (!UrlHelper::isValid($element['#value'], TRUE)) {
             $form_state->setError($element, t('The entered Tumblr URI is not valid.'));
         }
     }
 }
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (strlen($form_state->getValue('title')) < 3) {
         $form_state->setErrorByName('title', $this->t('Your name is too short.'));
     }
     if (!UrlHelper::isValid($form_state->getValue('video'), TRUE)) {
         $form_state->setErrorByName('video', $this->t("The video url '%url' is invalid.", array('%url' => $form_state->getValue('video'))));
     }
 }
 /**
  * Response for the xmlsitemap_engines_test.ping route.
  *
  * @throws NotFoundHttpException
  *   Throw a NotFoundHttpException if query url is not valid.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   A response with 200 code if the url query is valid.
  */
 public function render()
 {
     $query = \Drupal::request()->query->get('sitemap');
     if (empty($query) || !UrlHelper::isValid($query)) {
         watchdog('xmlsitemap', 'No valid sitemap parameter provided.', array(), WATCHDOG_WARNING);
         // @todo Remove this? Causes an extra watchdog error to be handled.
         throw new NotFoundHttpException();
     } else {
         watchdog('xmlsitemap', 'Recieved ping for @sitemap.', array('@sitemap' => $query));
     }
     return new Response('', 200);
 }
Esempio n. 9
0
 /**
  * Implements \Drupal\Core\Form\FormInterface::validateForm().
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $routing_path = $form_state->getValue('routing_path');
     if ($routing_path) {
         $form_state->setValueForElement($form['routing']['routing_path'], $routing_path);
     } else {
         $form_state->setValueForElement($form['routing']['routing_path'], '/headless');
     }
     if ($routing_path[0] == '/') {
         $form_state->setErrorByName('routing_path', $this->t("The path '%path' cannot start with a slash.", array('%path' => $routing_path)));
     }
     if (!UrlHelper::isValid($routing_path)) {
         $form_state->setErrorByName('routing_path', $this->t("The path '%path' is invalid or you do not have access to it.", array('%path' => $routing_path)));
     }
 }
Esempio n. 10
0
 /**
  * Tests invalid relative URLs.
  *
  * @dataProvider providerTestInvalidRelativeData
  * @covers ::isValid
  *
  * @param string $url
  *   The url to test.
  * @param string $prefix
  *   The prefix to test.
  */
 public function testInvalidRelative($url, $prefix)
 {
     $test_url = $prefix . $url;
     $valid_url = UrlHelper::isValid($test_url);
     $this->assertFalse($valid_url, SafeMarkup::format('@url is NOT a valid URL.', array('@url' => $test_url)));
 }
Esempio n. 11
0
 /**
  * Tests UrlHelper::parse().
  */
 function testDrupalParseUrl()
 {
     // Relative, absolute, and external URLs, without/with explicit script path,
     // without/with Drupal path.
     foreach (array('', '/', 'http://drupal.org/') as $absolute) {
         foreach (array('', 'index.php/') as $script) {
             foreach (array('', 'foo/bar') as $path) {
                 $url = $absolute . $script . $path . '?foo=bar&bar=baz&baz#foo';
                 $expected = array('path' => $absolute . $script . $path, 'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''), 'fragment' => 'foo');
                 $this->assertEqual(UrlHelper::parse($url), $expected, 'URL parsed correctly.');
             }
         }
     }
     // Relative URL that is known to confuse parse_url().
     $url = 'foo/bar:1';
     $result = array('path' => 'foo/bar:1', 'query' => array(), 'fragment' => '');
     $this->assertEqual(UrlHelper::parse($url), $result, 'Relative URL parsed correctly.');
     // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
     $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
     $this->assertTrue(UrlHelper::isExternal($url), 'Correctly identified an external URL.');
     // Test that UrlHelper::parse() does not allow spoofing a URL to force a malicious redirect.
     $parts = UrlHelper::parse('forged:http://cwe.mitre.org/data/definitions/601.html');
     $this->assertFalse(UrlHelper::isValid($parts['path'], TRUE), '\\Drupal\\Component\\Utility\\UrlHelper::isValid() correctly parsed a forged URL.');
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $validators = array('file_validate_extensions' => array('opml xml'));
     if ($file = file_save_upload('upload', $validators, FALSE, 0)) {
         $data = file_get_contents($file->getFileUri());
     } else {
         // @todo Move this to a fetcher implementation.
         try {
             $response = $this->httpClient->get($form_state->getValue('remote'));
             $data = (string) $response->getBody();
         } catch (RequestException $e) {
             $this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', array('%error' => $e->getMessage()));
             drupal_set_message($this->t('Failed to download OPML file due to "%error".', array('%error' => $e->getMessage())));
             return;
         }
     }
     $feeds = $this->parseOpml($data);
     if (empty($feeds)) {
         drupal_set_message($this->t('No new feed has been added.'));
         return;
     }
     // @todo Move this functionality to a processor.
     foreach ($feeds as $feed) {
         // Ensure URL is valid.
         if (!UrlHelper::isValid($feed['url'], TRUE)) {
             drupal_set_message($this->t('The URL %url is invalid.', array('%url' => $feed['url'])), 'warning');
             continue;
         }
         // Check for duplicate titles or URLs.
         $query = $this->feedStorage->getQuery();
         $condition = $query->orConditionGroup()->condition('title', $feed['title'])->condition('url', $feed['url']);
         $ids = $query->condition($condition)->execute();
         $result = $this->feedStorage->loadMultiple($ids);
         foreach ($result as $old) {
             if (strcasecmp($old->label(), $feed['title']) == 0) {
                 drupal_set_message($this->t('A feed named %title already exists.', array('%title' => $old->label())), 'warning');
                 continue 2;
             }
             if (strcasecmp($old->getUrl(), $feed['url']) == 0) {
                 drupal_set_message($this->t('A feed with the URL %url already exists.', array('%url' => $old->getUrl())), 'warning');
                 continue 2;
             }
         }
         $new_feed = $this->feedStorage->create(array('title' => $feed['title'], 'url' => $feed['url'], 'refresh' => $form_state->getValue('refresh')));
         $new_feed->save();
     }
     $form_state->setRedirect('aggregator.admin_overview');
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Check that the chunk size will not create more than 1000 chunks.
     $chunk_size = $form_state->getValue('chunk_size');
     if ($chunk_size != 'auto' && $chunk_size != 50000 && xmlsitemap_get_link_count() / $chunk_size > 1000) {
         $form_state->setErrorByName('chunk_size', t('The sitemap page link count of @size will create more than 1,000 sitemap pages. Please increase the link count.', array('@size' => $chunk_size)));
     }
     $base_url = $form_state->getValue('xmlsitemap_base_url');
     $base_url = rtrim($base_url, '/');
     $form_state->setValue('xmlsitemap_base_url', $base_url);
     if ($base_url != '' && !UrlHelper::isValid($base_url, TRUE)) {
         $form_state->setErrorByName('xmlsitemap_base_url', t('Invalid base URL.'));
     }
     parent::validateForm($form, $form_state);
 }
Esempio n. 14
0
 /**
  * Helper for getUrlIfValid() and getUrlIfValidWithoutAccessCheck().
  */
 protected function getUrl($path, $access_check)
 {
     $path = ltrim($path, '/');
     $parsed_url = UrlHelper::parse($path);
     $options = [];
     if (!empty($parsed_url['query'])) {
         $options['query'] = $parsed_url['query'];
     }
     if (!empty($parsed_url['fragment'])) {
         $options['fragment'] = $parsed_url['fragment'];
     }
     if ($parsed_url['path'] == '<front>') {
         return new Url('<front>', [], $options);
     } elseif ($parsed_url['path'] == '<none>') {
         return new Url('<none>', [], $options);
     } elseif (UrlHelper::isExternal($path) && UrlHelper::isValid($path)) {
         if (empty($parsed_url['path'])) {
             return FALSE;
         }
         return Url::fromUri($path);
     }
     $request = Request::create('/' . $path);
     $attributes = $this->getPathAttributes($path, $request, $access_check);
     if (!$attributes) {
         return FALSE;
     }
     $route_name = $attributes[RouteObjectInterface::ROUTE_NAME];
     $route_parameters = $attributes['_raw_variables']->all();
     return new Url($route_name, $route_parameters, $options + ['query' => $request->query->all()]);
 }
Esempio n. 15
0
 /**
  * Tests invalid relative URLs.
  *
  * @dataProvider providerTestInvalidRelativeData
  * @covers ::isValid
  *
  * @param string $url
  *   The url to test.
  * @param string $prefix
  *   The prefix to test.
  */
 public function testInvalidRelative($url, $prefix)
 {
     $test_url = $prefix . $url;
     $valid_url = UrlHelper::isValid($test_url);
     $this->assertFalse($valid_url, $test_url . ' is NOT a valid URL.');
 }
Esempio n. 16
0
 /**
  * Process inline images..
  *
  * @param Swift_Message $m
  *   The message which inline images are to be added to.
  * @param array $images
  *   The images which are to be added as inline images to the provided
  *   message.
  */
 private function embed(Swift_Message $m, array $images)
 {
     // Iterate through each array element.
     foreach ($images as $image) {
         if ($image instanceof \stdClass) {
             // Validate required fields.
             if (empty($image->uri) || empty($image->filename) || empty($image->filemime) || empty($image->cid)) {
                 continue;
             }
             // Keep track of the 'cid' assigned to the embedded image.
             $cid = NULL;
             // Get image data.
             if (UrlHelper::isValid($image->uri, TRUE)) {
                 $content = file_get_contents($image->uri);
             } else {
                 $content = file_get_contents(\Drupal::service('file_system')->realpath($image->uri));
             }
             $filename = $image->filename;
             $filemime = $image->filemime;
             // Embed image.
             $cid = $m->embed(Swift_Image::newInstance($content, $filename, $filemime));
             // The provided 'cid' needs to be replaced with the 'cid' returned
             // by the Swift Mailer library.
             $body = $m->getBody();
             $body = preg_replace('/cid.*' . $image->cid . '/', $cid, $body);
             $m->setBody($body);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $custom_urls = $form_state->getValue('custom_urls');
     $custom_urls = preg_split('/[\\r\\n]+/', $custom_urls, -1, PREG_SPLIT_NO_EMPTY);
     foreach ($custom_urls as $custom_url) {
         $url = xmlsitemap_engines_prepare_url($custom_url, '');
         if (!UrlHelper::isValid($url, TRUE)) {
             $form_state->setErrorByName($custom_url, t('Invalid URL %url.', array('%url' => $custom_url)));
         }
     }
     $custom_urls = implode("\n", $custom_urls);
     $form_state->setValue('custom_urls', $custom_ruls);
     parent::validateForm($form, $form_state);
 }
Esempio n. 18
0
 /**
  * {@inheritdoc}
  */
 public function condition($property, $value = NULL, $operator = '=', $langcode = NULL)
 {
     $key = $property . '-' . $operator;
     $field_storage_definitions = \Drupal::service('entity.manager')->getFieldStorageDefinitions($this->entityTypeId);
     /*
      * Ok, so what is all this:
      * We need to convert our conditions into some sparql compatible conditions.
      */
     $bundle = $this->entityType->getKey('bundle');
     $id = $this->entityType->getKey('id');
     $label = $this->entityType->getKey('label');
     switch ($key) {
         // @todo Limit the graphs here to the set bundles.
         case $bundle . '-IN':
             $rdf_bundles = $this->mappingHandler->getBundleUriList($this->entityType->getBundleEntityType(), $value);
             if ($rdf_bundles) {
                 $this->condition->condition('?entity', '?bundlepredicate', '?type');
                 $this->filterAdded = TRUE;
                 $predicates = "(<" . implode(">, <", $this->entityStorage->bundlePredicate()) . ">)";
                 $this->filter->filter('?bundlepredicate IN ' . $predicates);
                 $this->filter->filter('?type IN ' . $rdf_bundles);
             }
             return $this;
         case $bundle . '-=':
             $mapping = $this->mappingHandler->getRdfBundleMappedUri($this->entityType->getBundleEntityType(), $value);
             $bundle = $mapping[$value];
             if ($bundle) {
                 $this->condition->condition('?entity', '?bundlepredicate', SparqlArg::uri($bundle));
                 $predicates = "(<" . implode(">, <", $this->entityStorage->bundlePredicate()) . ">)";
                 $this->filter->filter('?bundlepredicate IN ' . $predicates);
                 $this->filterAdded = TRUE;
             }
             return $this;
         case $id . '-IN':
             if ($value) {
                 $ids_list = "(<" . implode(">, <", $value) . ">)";
                 if (!$this->filterAdded) {
                     $this->condition->condition('?entity', '?bundlepredicate', '?type');
                     $predicates = "(<" . implode(">, <", $this->entityStorage->bundlePredicate()) . ">)";
                     $this->filter->filter('?bundlepredicate IN ' . $predicates);
                     $this->filterAdded = TRUE;
                 }
                 $this->filter->filter('?entity IN ' . $ids_list);
             }
             return $this;
         case $id . '-NOT IN':
         case $id . '-<>':
             if ($value) {
                 if (is_array($value)) {
                     $ids_list = "(<" . implode(">, <", $value) . ">)";
                 } else {
                     $ids_list = "(<" . $value . ">)";
                 }
                 if (!$this->filterAdded) {
                     $this->condition->condition('?entity', '?bundlepredicate', '?type');
                     $predicates = "(<" . implode(">, <", $this->entityStorage->bundlePredicate()) . ">)";
                     $this->filter->filter('?bundlepredicate IN ' . $predicates);
                     $this->filterAdded = TRUE;
                 }
                 $this->filter->filter('!(?entity IN ' . $ids_list . ')');
             }
             return $this;
         case $id . '-=':
             if (!$value) {
                 return $this;
             }
             $id = '<' . $value . '>';
             if (!$this->filterAdded) {
                 $this->condition->condition('?entity', '?bundlepredicate', '?type');
                 $predicates = "(<" . implode(">, <", $this->entityStorage->bundlePredicate()) . ">)";
                 $this->filter->filter('?bundlepredicate IN ' . $predicates);
                 $this->filterAdded = TRUE;
             }
             $this->filter->filter('?entity IN ' . SparqlArg::literal($id));
             break;
         case $label . '-=':
             preg_match('/\\((.*?)\\)/', $value, $matches);
             $matching = array_pop($matches);
             if ($matching) {
                 $ids = "(<{$matching}>)";
                 $this->filter->filter('?entity IN ' . $ids);
             } else {
                 if (file_valid_uri($value)) {
                     $ids = "(<{$value}>)";
                     $this->filter->filter('?entity IN ' . $ids);
                 } else {
                     $mapping = $this->mappingHandler->getEntityTypeLabelPredicates($this->entityTypeId);
                     $label_list = "(<" . implode(">, <", array_unique(array_keys($mapping))) . ">)";
                     $this->condition->condition('?entity', '?label_type', '?label');
                     $this->filter->filter('?label_type IN ' . $label_list);
                     $this->filter->filter('str(?label) = "' . $value . '"');
                 }
             }
             return $this;
         case $label . '-CONTAINS':
             $mapping = $this->mappingHandler->getEntityTypeLabelPredicates($this->entityTypeId);
             $label_list = "(<" . implode(">, <", array_unique(array_keys($mapping))) . ">)";
             $this->condition->condition('?entity', '?label_type', '?label');
             $this->filter->filter('?label_type IN ' . $label_list);
             if ($value) {
                 $this->filter->filter('regex(?label, "' . $value . '", "i")');
                 $this->filter->filter('(lang(?label) = "" || langMatches(lang(?label), "EN"))');
             }
             return $this;
         case '_field_exists-EXISTS':
         case '_field_exists-NOT EXISTS':
             $field_rdf_name = $this->getFieldRdfPropertyName($value, $field_storage_definitions);
             if (!UrlHelper::isValid($field_rdf_name, TRUE) === FALSE) {
                 $field_rdf_name = SparqlArg::uri($field_rdf_name);
             }
             if ($field_rdf_name) {
                 $this->filter('?entity ' . $field_rdf_name . ' ?c', 'FILTER ' . $operator);
             }
             return $this;
     }
     if ($operator == '=') {
         if (!$value) {
             return $this;
         }
         // @todo this code will be handled in ISAICP-2631
         if (strpos($property, '.') !== FALSE) {
             list($field_name, $column) = explode('.', $property);
         } else {
             $field_name = $property;
         }
         $field_rdf_name = $this->getFieldRdfPropertyName($field_name, $field_storage_definitions);
         if (!UrlHelper::isValid($value, TRUE) === FALSE) {
             $value = SparqlArg::uri($value);
         } else {
             $value = SparqlArg::literal($value);
         }
         $this->condition->condition('?entity', SparqlArg::uri($field_rdf_name), $value);
     }
     return $this;
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public static function value(array &$element, &$input, FormStateInterface $form_state)
 {
     if (isset($input['filefield_remote']['url']) && strlen($input['filefield_remote']['url']) > 0 && UrlHelper::isValid($input['filefield_remote']['url']) && $input['filefield_remote']['url'] != FILEFIELD_SOURCE_REMOTE_HINT_TEXT) {
         $field = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $element['#field_name']);
         $url = $input['filefield_remote']['url'];
         // Check that the destination is writable.
         $temporary_directory = 'temporary://';
         if (!file_prepare_directory($temporary_directory, FILE_MODIFY_PERMISSIONS)) {
             \Drupal::logger('filefield_sources')->log(E_NOTICE, 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => drupal_realpath($temporary_directory)));
             drupal_set_message(t('The file could not be transferred because the temporary directory is not writable.'), 'error');
             return;
         }
         // Check that the destination is writable.
         $directory = $element['#upload_location'];
         $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY);
         // This first chmod check is for other systems such as S3, which don't
         // work with file_prepare_directory().
         if (!drupal_chmod($directory, $mode) && !file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
             \Drupal::logger('filefield_sources')->log(E_NOTICE, 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $url, '%destination' => drupal_realpath($directory)));
             drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $url)), 'error');
             return;
         }
         // Check the headers to make sure it exists and is within the allowed
         // size.
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_HEADER, TRUE);
         curl_setopt($ch, CURLOPT_NOBODY, TRUE);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
         curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(get_called_class(), 'parseHeader'));
         // Causes a warning if PHP safe mode is on.
         @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
         curl_exec($ch);
         $info = curl_getinfo($ch);
         if ($info['http_code'] != 200) {
             curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
             $file_contents = curl_exec($ch);
             $info = curl_getinfo($ch);
         }
         curl_close($ch);
         if ($info['http_code'] != 200) {
             switch ($info['http_code']) {
                 case 403:
                     $form_state->setError($element, t('The remote file could not be transferred because access to the file was denied.'));
                     break;
                 case 404:
                     $form_state->setError($element, t('The remote file could not be transferred because it was not found.'));
                     break;
                 default:
                     $form_state->setError($element, t('The remote file could not be transferred due to an HTTP error (@code).', array('@code' => $info['http_code'])));
             }
             return;
         }
         // Update the $url variable to reflect any redirects.
         $url = $info['url'];
         $url_info = parse_url($url);
         // Determine the proper filename by reading the filename given in the
         // Content-Disposition header. If the server fails to send this header,
         // fall back on the basename of the URL.
         //
         // We prefer to use the Content-Disposition header, because we can then
         // use URLs like http://example.com/get_file/23 which would otherwise be
         // rejected because the URL basename lacks an extension.
         $filename = static::filename();
         if (empty($filename)) {
             $filename = rawurldecode(basename($url_info['path']));
         }
         $pathinfo = pathinfo($filename);
         // Create the file extension from the MIME header if all else has failed.
         if (empty($pathinfo['extension']) && ($extension = static::mimeExtension())) {
             $filename = $filename . '.' . $extension;
             $pathinfo = pathinfo($filename);
         }
         $filename = filefield_sources_clean_filename($filename, $field->getSetting('file_extensions'));
         $filepath = file_create_filename($filename, $temporary_directory);
         if (empty($pathinfo['extension'])) {
             $form_state->setError($element, t('The remote URL must be a file and have an extension.'));
             return;
         }
         // Perform basic extension check on the file before trying to transfer.
         $extensions = $field->getSetting('file_extensions');
         $regex = '/\\.(' . preg_replace('/[ +]/', '|', preg_quote($extensions)) . ')$/i';
         if (!empty($extensions) && !preg_match($regex, $filename)) {
             $form_state->setError($element, t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions)));
             return;
         }
         // Check file size based off of header information.
         if (!empty($element['#upload_validators']['file_validate_size'][0])) {
             $max_size = $element['#upload_validators']['file_validate_size'][0];
             $file_size = $info['download_content_length'];
             if ($file_size > $max_size) {
                 $form_state->setError($element, t('The remote file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file_size), '%maxsize' => format_size($max_size))));
                 return;
             }
         }
         // Set progress bar information.
         $options = array('key' => $element['#entity_type'] . '_' . $element['#bundle'] . '_' . $element['#field_name'] . '_' . $element['#delta'], 'filepath' => $filepath);
         static::setTransferOptions($options);
         $transfer_success = FALSE;
         // If we've already downloaded the entire file because the
         // header-retrieval failed, just ave the contents we have.
         if (isset($file_contents)) {
             if ($fp = @fopen($filepath, 'w')) {
                 fwrite($fp, $file_contents);
                 fclose($fp);
                 $transfer_success = TRUE;
             }
         } else {
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $url);
             curl_setopt($ch, CURLOPT_HEADER, FALSE);
             curl_setopt($ch, CURLOPT_WRITEFUNCTION, array(get_called_class(), 'curlWrite'));
             // Causes a warning if PHP safe mode is on.
             @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
             $transfer_success = curl_exec($ch);
             curl_close($ch);
         }
         if ($transfer_success && ($file = filefield_sources_save_file($filepath, $element['#upload_validators'], $element['#upload_location']))) {
             if (!in_array($file->id(), $input['fids'])) {
                 $input['fids'][] = $file->id();
             }
         }
         // Delete the temporary file.
         @unlink($filepath);
     }
 }
Esempio n. 20
0
 /**
  * {@inheritdoc}.
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (!$form_state->getValue('base_url')) {
         $form_state->setValue('base_url', NULL);
     } elseif (!UrlHelper::isValid($form_state->getValue('base_url'), TRUE)) {
         $form_state->setErrorByName('base_url', $this->t('The secure base URL must be a valid URL.'));
     } elseif (strtolower(parse_url($form_state->getValue('base_url'), PHP_URL_SCHEME)) !== 'https') {
         $form_state->setErrorByName('base_url', $this->t('The secure base URL must start with <em>https://</em>.'));
     }
     parent::validateForm($form, $form_state);
 }