/**
  * Copy a file onto itself.
  */
 function testOverwriteSelf()
 {
     // Create a file for testing
     $uri = $this->createUri();
     // Copy the file onto itself with renaming works.
     $new_filepath = file_unmanaged_copy($uri, $uri, FILE_EXISTS_RENAME);
     $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
     $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
     $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
     $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
     $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
     // Copy the file onto itself without renaming fails.
     $new_filepath = file_unmanaged_copy($uri, $uri, FILE_EXISTS_ERROR);
     $this->assertFalse($new_filepath, 'Copying onto itself without renaming fails.');
     $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');
     // Copy the file into same directory without renaming fails.
     $new_filepath = file_unmanaged_copy($uri, drupal_dirname($uri), FILE_EXISTS_ERROR);
     $this->assertFalse($new_filepath, 'Copying onto itself fails.');
     $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');
     // Copy the file into same directory with renaming works.
     $new_filepath = file_unmanaged_copy($uri, drupal_dirname($uri), FILE_EXISTS_RENAME);
     $this->assertTrue($new_filepath, 'Copying into same directory works.');
     $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
     $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
     $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
     $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
 }
 /**
  * {@inheritdoc}
  */
 public function import(Row $row, array $old_destination_id_values = array())
 {
     $source = $this->configuration['source_base_path'] . $row->getSourceProperty($this->configuration['source_path_property']);
     $destination = $row->getDestinationProperty($this->configuration['destination_path_property']);
     $replace = FILE_EXISTS_REPLACE;
     if (!empty($this->configuration['rename'])) {
         $entity_id = $row->getDestinationProperty($this->getKey('id'));
         if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) {
             $replace = FILE_EXISTS_RENAME;
         }
     }
     $dirname = drupal_dirname($destination);
     if (!file_prepare_directory($dirname, FILE_CREATE_DIRECTORY)) {
         throw new MigrateException(t('Could not create directory %dirname', array('%dirname' => $dirname)));
     }
     if ($this->configuration['move']) {
         $copied = file_unmanaged_move($source, $destination, $replace);
     } else {
         // Determine whether we can perform this operation based on overwrite rules.
         $original_destination = $destination;
         $destination = file_destination($destination, $replace);
         if ($destination === FALSE) {
             throw new MigrateException(t('File %file could not be copied because a file by that name already exists in the destination directory (%destination)', array('%file' => $source, '%destination' => $original_destination)));
         }
         $source = $this->urlencode($source);
         $copied = copy($source, $destination);
     }
     if ($copied) {
         return parent::import($row, $old_destination_id_values);
     } else {
         throw new MigrateException(t('File %source could not be copied to %destination.', array('%source' => $source, '%destination' => $destination)));
     }
 }
 /**
  * Creates a file, then tests the tokens generated from it.
  */
 function testFileTokenReplacement()
 {
     $node_storage = $this->container->get('entity.manager')->getStorage('node');
     $token_service = \Drupal::token();
     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
     // Create file field.
     $type_name = 'article';
     $field_name = 'field_' . strtolower($this->randomMachineName());
     $this->createFileField($field_name, 'node', $type_name);
     $test_file = $this->getTestFile('text');
     // Coping a file to test uploads with non-latin filenames.
     $filename = drupal_dirname($test_file->getFileUri()) . '/текстовый файл.txt';
     $test_file = file_copy($test_file, $filename);
     // Create a new node with the uploaded file.
     $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
     // Load the node and the file.
     $node_storage->resetCache(array($nid));
     $node = $node_storage->load($nid);
     $file = file_load($node->{$field_name}->target_id);
     // Generate and test sanitized tokens.
     $tests = array();
     $tests['[file:fid]'] = $file->id();
     $tests['[file:name]'] = String::checkPlain($file->getFilename());
     $tests['[file:path]'] = String::checkPlain($file->getFileUri());
     $tests['[file:mime]'] = String::checkPlain($file->getMimeType());
     $tests['[file:size]'] = format_size($file->getSize());
     $tests['[file:url]'] = String::checkPlain(file_create_url($file->getFileUri()));
     $tests['[file:created]'] = format_date($file->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[file:created:short]'] = format_date($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[file:changed]'] = format_date($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[file:changed:short]'] = format_date($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[file:owner]'] = String::checkPlain(user_format_name($this->adminUser));
     $tests['[file:owner:uid]'] = $file->getOwnerId();
     // 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 = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId()));
         $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
     }
     // Generate and test unsanitized tokens.
     $tests['[file:name]'] = $file->getFilename();
     $tests['[file:path]'] = $file->getFileUri();
     $tests['[file:mime]'] = $file->getMimeType();
     $tests['[file:size]'] = format_size($file->getSize());
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE));
         $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
     }
 }
Exemple #4
0
 /**
  * {@inheritdoc}
  */
 public function import(Row $row, array $old_destination_id_values = array())
 {
     $source = $this->configuration['source_base_path'] . $row->getSourceProperty($this->configuration['source_path_property']);
     $destination = $row->getDestinationProperty($this->configuration['destination_path_property']);
     $replace = FILE_EXISTS_REPLACE;
     if (!empty($this->configuration['rename'])) {
         $entity_id = $row->getDestinationProperty($this->getKey('id'));
         if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) {
             $replace = FILE_EXISTS_RENAME;
         }
     }
     $dirname = drupal_dirname($destination);
     file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);
     if ($this->configuration['move']) {
         file_unmanaged_move($source, $destination, $replace);
     } else {
         file_unmanaged_copy($source, $destination, $replace);
     }
     return parent::import($row, $old_destination_id_values);
 }
Exemple #5
0
 /**
  * {@inheritdoc}
  */
 public function import(Row $row, array $old_destination_id_values = array())
 {
     $file = $row->getSourceProperty($this->configuration['source_path_property']);
     $destination = $row->getDestinationProperty($this->configuration['destination_path_property']);
     // We check the destination to see if this is a temporary file. If it is
     // then we do not prepend the source_base_path because temporary files are
     // already absolute.
     $source = $this->isTempFile($destination) ? $file : $this->configuration['source_base_path'] . $file;
     $dirname = drupal_dirname($destination);
     if (!file_prepare_directory($dirname, FILE_CREATE_DIRECTORY)) {
         throw new MigrateException(t('Could not create directory %dirname', array('%dirname' => $dirname)));
     }
     // If the start and end file is exactly the same, there is nothing to do.
     if (drupal_realpath($source) === drupal_realpath($destination)) {
         return parent::import($row, $old_destination_id_values);
     }
     $replace = FILE_EXISTS_REPLACE;
     if (!empty($this->configuration['rename'])) {
         $entity_id = $row->getDestinationProperty($this->getKey('id'));
         if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) {
             $replace = FILE_EXISTS_RENAME;
         }
     }
     if ($this->configuration['move']) {
         $copied = file_unmanaged_move($source, $destination, $replace);
     } else {
         // Determine whether we can perform this operation based on overwrite rules.
         $original_destination = $destination;
         $destination = file_destination($destination, $replace);
         if ($destination === FALSE) {
             throw new MigrateException(t('File %file could not be copied because a file by that name already exists in the destination directory (%destination)', array('%file' => $source, '%destination' => $original_destination)));
         }
         $source = $this->urlencode($source);
         $copied = @copy($source, $destination);
     }
     if ($copied) {
         return parent::import($row, $old_destination_id_values);
     } else {
         throw new MigrateException(t('File %source could not be copied to %destination.', array('%source' => $source, '%destination' => $destination)));
     }
 }
Exemple #6
0
 /**
  * Returns a Drupal file object of the enclosed resource.
  *
  * @param string $destination
  *   The path or uri specifying the target directory in which the file is
  *   expected. Don't use trailing slashes unless it's a streamwrapper scheme.
  * @param int $replace
  *   (optional) Replace behavior when the destination file already exists:
  *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  *       the destination name exists then its database entry will be updated.
  *       If no database entry is found then a new one will be created.
  *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename
  *       is unique.
  *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  *   Defaults to FILE_EXISTS_RENAME.
  *
  * @return \Drupal\file\Entity\FileInterface
  *   A Drupal temporary file object of the enclosed resource.
  *
  * @throws \RuntimeException
  *   If file object could not be created.
  *
  * @todo Refactor this
  */
 public function getFile($destination, $replace = FILE_EXISTS_RENAME)
 {
     $file = FALSE;
     if (!$this->uri) {
         return $file;
     }
     // Prepare destination directory.
     file_prepare_directory($destination, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY);
     // Copy or save file depending on whether it is remote or local.
     if (drupal_realpath($this->uri)) {
         $file = entity_create('file', ['uid' => 0, 'uri' => $this->uri, 'filemime' => $this->mimeType, 'filename' => basename($this->uri)]);
         if (drupal_dirname($file->getFileUri()) != $destination) {
             $file = file_copy($file, $destination, $replace);
         } else {
             // If file is not to be copied, check whether file already exists,
             // as file_save() won't do that for us (compare file_copy() and
             // file_save())
             $existing_files = file_load_multiple([], ['uri' => $file->getFileUri()]);
             if ($existing_files) {
                 return reset($existing_files);
             }
             $file->save();
         }
     } else {
         $filename = drupal_basename($this->uri);
         if (\Drupal::moduleHandler()->moduleExists('transliteration')) {
             require_once drupal_get_path('module', 'transliteration') . '/transliteration.inc';
             $filename = transliteration_clean_filename($filename);
         }
         if (file_uri_target($destination)) {
             $destination = trim($destination, '/') . '/';
         }
         try {
             $file = file_save_data($this->getContent(), $destination . $filename, $replace);
         } catch (\Exception $e) {
             watchdog_exception('Feeds', $e, nl2br(SafeMarkup::checkPlain($e)));
         }
     }
     // We couldn't make sense of this enclosure, throw an exception.
     if (!$file) {
         throw new \RuntimeException(SafeMarkup::format('Invalid enclosure %enclosure', ['%enclosure' => $this->uri]));
     }
     return $file;
 }
 /**
  * {@inheritdoc}
  */
 public function createDerivative($original_uri, $derivative_uri)
 {
     // Get the folder for the final location of this style.
     $directory = drupal_dirname($derivative_uri);
     // Build the destination folder tree if it doesn't already exist.
     if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
         \Drupal::logger('image')->error('Failed to create style directory: %directory', array('%directory' => $directory));
         return FALSE;
     }
     $image = \Drupal::service('image.factory')->get($original_uri);
     if (!$image->isValid()) {
         return FALSE;
     }
     foreach ($this->getEffects() as $effect) {
         $effect->applyEffect($image);
     }
     if (!$image->save($derivative_uri)) {
         if (file_exists($derivative_uri)) {
             \Drupal::logger('image')->error('Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $derivative_uri));
         }
         return FALSE;
     }
     return TRUE;
 }