Пример #1
0
 /**
  * Do the actual file save. This function is called to save the data file AND
  * the metadata sidecar file.
  * @param \BackupMigrate\Core\File\BackupFileReadableInterface $file
  * @throws \BackupMigrate\Core\Exception\BackupMigrateException
  */
 function _saveFile(BackupFileReadableInterface $file)
 {
     // Check if the directory exists.
     $this->checkDirectory();
     // @TODO Decide what the appropriate file_exists strategy should be.
     file_unmanaged_move($file->realpath(), $this->confGet('directory') . $file->getFullName(), FILE_EXISTS_REPLACE);
 }
Пример #2
0
 /**
  * Private function for creating a random image.
  *
  * This function only works with the GD toolkit. ImageMagick is not supported.
  */
 protected function generateImage($extension = 'png', $min_resolution, $max_resolution)
 {
     if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) {
         $destination = $tmp_file . '.' . $extension;
         file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
         $min = explode('x', $min_resolution);
         $max = explode('x', $max_resolution);
         $width = rand((int) $min[0], (int) $max[0]);
         $height = rand((int) $min[1], (int) $max[1]);
         // Make an image split into 4 sections with random colors.
         $im = imagecreate($width, $height);
         for ($n = 0; $n < 4; $n++) {
             $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
             $x = $width / 2 * ($n % 2);
             $y = $height / 2 * (int) ($n >= 2);
             imagefilledrectangle($im, $x, $y, $x + $width / 2, $y + $height / 2, $color);
         }
         // Make a perfect circle in the image middle.
         $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
         $smaller_dimension = min($width, $height);
         $smaller_dimension = $smaller_dimension % 2 ? $smaller_dimension : $smaller_dimension;
         imageellipse($im, $width / 2, $height / 2, $smaller_dimension, $smaller_dimension, $color);
         $save_function = 'image' . ($extension == 'jpg' ? 'jpeg' : $extension);
         $save_function($im, drupal_realpath($destination));
         return $destination;
     }
 }
Пример #3
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);
     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)));
     }
 }
 /**
  * Helper function that moves an uploaded file.
  *
  * @param string $filename
  *   The path of the file to move.
  * @param string $uri
  *   The path where to move the file.
  *
  * @return bool
  *   TRUE if the file was moved. FALSE otherwise.
  */
 protected static function moveUploadedFile($filename, $uri)
 {
     if (drupal_move_uploaded_file($filename, $uri)) {
         return TRUE;
     }
     return variable_get('restful_insecure_uploaded_flag', FALSE) && (bool) file_unmanaged_move($filename, $uri);
 }
Пример #5
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     $object_field = array();
     static $available_images = array();
     if (empty($available_images)) {
         $available_images = $this->getImages();
     }
     if (empty($available_images)) {
         $args = func_get_args();
         return call_user_func_array('_image_devel_generate', $args);
     }
     $extension = array_rand(array('jpg' => 'jpg', 'png' => 'png'));
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     if (FALSE === ($tmp_file = drupal_tempnam('temporary://', 'imagefield_'))) {
         return FALSE;
     }
     $destination = $tmp_file . '.' . $extension;
     file_unmanaged_move($tmp_file, $destination, FILE_EXISTS_REPLACE);
     $rand_file = array_rand($available_images);
     if (!empty($instance['settings']['file_directory'])) {
         $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
     }
     $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
     file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
     if ($this->settings['devel_image_no_alter']) {
         $file = $available_images[$rand_file];
         $file = file_copy($file, $destination_dir);
     } else {
         $image = image_load($rand_file);
         $min = explode('x', $min_resolution);
         $max = explode('x', $max_resolution);
         $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
         $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
         $width = rand((int) $min[0], (int) $max[0]);
         $height = rand((int) $min[1], (int) $max[1]);
         if (!image_scale_and_crop($image, $width, $height)) {
             return FALSE;
         }
         // Use destination image type.
         $image->info['extension'] = $extension;
         if (!image_save($image, $destination)) {
             return FALSE;
         }
         $source = new stdClass();
         $source->uri = $destination;
         $source->uid = 1;
         // TODO: randomize? Use case specific.
         $source->filemime = $image->info['mime_type'];
         $source->filename = drupal_basename($image->source);
         $destination = $destination_dir . basename($destination);
         $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
Пример #6
0
 /**
  * Private function for generating a random text file.
  */
 private function generateTextFile($filesize = 1024)
 {
     if ($tmp_file = drupal_tempnam('temporary://', 'filefield_')) {
         $destination = $tmp_file . '.txt';
         file_unmanaged_move($tmp_file, $destination);
         $fp = fopen($destination, 'w');
         fwrite($fp, str_repeat('01', $filesize / 2));
         fclose($fp);
         return $destination;
     }
 }
Пример #7
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     static $images = array();
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     $extension = 'jpg';
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) {
         if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) {
             $destination = $tmp_file . '.' . $extension;
             file_unmanaged_move($tmp_file, $destination, FILE_EXISTS_REPLACE);
             $min = explode('x', $min_resolution);
             $max = explode('x', $max_resolution);
             $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
             $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
             $width = rand((int) $min[0], (int) $max[0]);
             $height = rand((int) $min[1], (int) $max[1]);
             $gray = isset($this->settings['devel_image_provider_gray']) ? $this->settings['devel_image_provider_gray'] : NULL;
             $tags = isset($this->settings['devel_image_provider_tags']) ? $this->settings['devel_image_provider_tags'] : NULL;
             $url = "{$this->provider_base_url}/{$width}/{$height}";
             if (!empty($tags)) {
                 $url .= '/' . $tags;
             }
             $url = $gray ? $url . '/bw' : $url;
             // Generate seed value.
             $seed = isset($this->settings['devel_image_provider_seed']) ? $this->settings['devel_image_provider_seed'] : NULL;
             $rand_value = rand(0, $seed);
             $url .= '/' . $rand_value;
             $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents';
             $path = devel_image_provider_get_file($url, $destination, $method);
             $source = new stdClass();
             $source->uri = $path;
             $source->uid = 1;
             // TODO: randomize? Use case specific.
             $source->filemime = 'image/jpg';
             if (!empty($instance['settings']['file_directory'])) {
                 $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
             }
             $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . basename($path);
             $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
         } else {
             return FALSE;
         }
     } else {
         // Select one of the images we've already generated for this field.
         $file = new stdClass();
         $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
 /**
  * Try to move a file onto itself.
  */
 function testOverwriteSelf()
 {
     // Create a file for testing.
     $uri = $this->createUri();
     // Move the file onto itself without renaming shouldn't make changes.
     $new_filepath = file_unmanaged_move($uri, $uri, FILE_EXISTS_REPLACE);
     $this->assertFalse($new_filepath, 'Moving onto itself without renaming fails.');
     $this->assertTrue(file_exists($uri), 'File exists after moving onto itself.');
     // Move the file onto itself with renaming will result in a new filename.
     $new_filepath = file_unmanaged_move($uri, $uri, FILE_EXISTS_RENAME);
     $this->assertTrue($new_filepath, 'Moving onto itself with renaming works.');
     $this->assertFalse(file_exists($uri), 'Original file has been removed.');
     $this->assertTrue(file_exists($new_filepath), 'File exists after moving onto itself.');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Create target directory if necessary
     $destination = \Drupal::config('system.file')->get('default_scheme') . '://plupload-test';
     file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
     $saved_files = array();
     foreach ($form_state->getValue('plupload') as $uploaded_file) {
         $file_uri = file_stream_wrapper_uri_normalize($destination . '/' . $uploaded_file['name']);
         // Move file without creating a new 'file' entity.
         file_unmanaged_move($uploaded_file['tmppath'], $file_uri);
         // @todo: When https://www.drupal.org/node/2245927 is resolved,
         // use a helper to save file to file_managed table
         $saved_files[] = $file_uri;
     }
     if (!empty($saved_files)) {
         drupal_set_message('Files uploaded correctly: ' . implode(', ', $saved_files) . '.', 'status');
     }
 }
Пример #10
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);
 }
Пример #11
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)));
     }
 }
Пример #12
0
 /**
  * Tries to move or copy a file.
  *
  * @param string $source
  *   The source path or URI.
  * @param string $destination
  *   The destination path or URI.
  * @param int $replace
  *   (optional) FILE_EXISTS_REPLACE (default) or FILE_EXISTS_RENAME.
  *
  * @return string|bool
  *   File destination on success, FALSE on failure.
  */
 protected function writeFile($source, $destination, $replace = FILE_EXISTS_REPLACE)
 {
     if ($this->configuration['move']) {
         return file_unmanaged_move($source, $destination, $replace);
     }
     // Check if there is a destination available for copying. If there isn't,
     // it already exists at the destination and the replace flag tells us to not
     // replace it. In that case, return the original destination.
     if (!($final_destination = file_destination($destination, $replace))) {
         return $destination;
     }
     // We can't use file_unmanaged_copy because it will break with remote Urls.
     if (@copy($source, $final_destination)) {
         return $final_destination;
     }
     return FALSE;
 }
Пример #13
0
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user = \Drupal::currentUser();
    $validators = array(
      'file_validate_is_image' => array()
    );
    $count = 0;
    $files_uploaded = array();
    $nid = $form_state->getValue('nid');
    $album_uid = db_query("SELECT uid FROM {node_field_data} WHERE nid = :nid", array(':nid' => $nid))->fetchField();
    // If photos_access is enabled check viewid.
    $scheme = 'default';
    $album_viewid = 0;
    if (\Drupal::moduleHandler()->moduleExists('photos_access')) {
      $node = \Drupal\node\Entity\Node::load($nid);
      if (isset($node->privacy) && isset($node->privacy['viewid'])) {
        $album_viewid = $node->privacy['viewid'];
        if ($album_viewid > 0) {
          // Check for private file path.
          if (PrivateStream::basePath()) {
            $scheme = 'private';
          }
          else {
            // Set warning message.
            drupal_set_message(t('Warning: image files can still be accessed by visiting the direct URL.
              For better security, ask your website admin to setup a private file path.'), 'warning');
          }
        }
      }
    }
    if (empty($album_uid)) {
      $album_uid = $user->id();
    }
    // \Drupal\user\Entity\User::load($album_uid);
    $account = \Drupal::entityManager()->getStorage('user')->load($album_uid);
    // Check if plupload is enabled.
    // @todo check for plupload library?
    if (\Drupal::config('photos.settings')->get('photos_plupload_status')) {
      $plupload_files = $form_state->getValue('plupload');
      foreach ($plupload_files as $uploaded_file) {
        if ($uploaded_file['status'] == 'done') {
          // Check for zip files.
          $ext = \Drupal\Component\Utility\Unicode::substr($uploaded_file['name'], -3);
          if ($ext <> 'zip' && $ext <> 'ZIP') {
            // Prepare directory.
            $photos_path = photos_check_path($scheme, '', $account);
            $photos_name = _photos_rename($uploaded_file['name']);
            $file_uri = file_destination($photos_path . '/' . $photos_name, FILE_EXISTS_RENAME);
            if (file_unmanaged_move($uploaded_file['tmppath'], $file_uri)) {
              $path_parts = pathinfo($file_uri);
              $image = \Drupal::service('image.factory')->get($file_uri);
              if ($path_parts['extension'] && $image->getWidth()) {
                // Create a file entity.
                $file = entity_create('file', array(
                  'uri' => $file_uri,
                  'uid' => $user->id(),
                  'status' => FILE_STATUS_PERMANENT,
                  'pid' => $form_state->getValue('pid'),
                  'nid' => $form_state->getValue('nid'),
                  'filename' => $photos_name,
                  'filesize' => $image->getFileSize(),
                  'filemime' => $image->getMimeType()
                ));

                if ($file_fid = _photos_save_data($file)) {
                  $files_uploaded[] = photos_image_date($file);
                }
                $count++;
              }
              else {
                file_delete($file_uri);
                \Drupal::logger('photos')->notice('Wrong file type');
              }
            }
            else {
              \Drupal::logger('photos')->notice('Upload error. Could not move temp file.');
            }
          }
          else {
            if (!\Drupal::config('photos.settings')->get('photos_upzip')) {
              drupal_set_message(t('Please set Album photos to open zip uploads.'), 'error');
            }
            $directory = photos_check_path();
            file_prepare_directory($directory);
            $zip = file_destination($directory . '/' . $uploaded_file['name'], FILE_EXISTS_RENAME);
            if (file_unmanaged_move($uploaded_file['tmppath'], $zip)) {
              $value = new \StdClass();
              $value->pid = $form_state->getValue('pid');
              $value->nid = $form_state->getValue('nid');
              $value->title = $uploaded_file['name'];
              $value->des = '';
              // Unzip it.
              if (!$file_count = _photos_unzip($zip, $value, $scheme, $account)) {
                drupal_set_message(t('Zip upload failed.'), 'error');
              }
              else {
                // Update image upload count.
                $count = $count+$file_count;
              }
            }
          }
        }
        else {
          drupal_set_message(t('Error uploading some photos.'), 'error');
        }
      }
    }
    else {
      // Manual upload form.
      $pid = $form_state->getValue('pid');
      $photos_num = \Drupal::config('photos.settings')->get('photos_num');
      for ($i = 0; $i < $photos_num; ++$i) {
        if ($_FILES['files']['name']['images_' . $i]) {
          $ext = \Drupal\Component\Utility\Unicode::substr($_FILES['files']['name']['images_' . $i], -3);
          if ($ext <> 'zip' && $ext <> 'ZIP') {
            // Prepare directory.
            $photos_path = photos_check_path($scheme, '', $account);
            if ($file = file_save_upload('images_' . $i, $validators, $photos_path, 0)) {
              // Save file to album. Include title and description.
              $file->pid = $pid;
              $file->nid = $form_state->getValue('nid');
              $file->des = $form_state->getValue('des_' . $i);
              $file->title = $form_state->getValue('title_' . $i);
              $files_uploaded[] = photos_image_date($file);
              $count++;
            }
          }
          else {
            // Zip upload from manual upload form.
            if (!\Drupal::config('photos.settings')->get('photos_upzip')) {
              return form_set_error('error', t('Please update settings to allow zip uploads.'));
            }
            $directory = photos_check_path();
            file_prepare_directory($directory);
            $zip = file_destination($directory . '/' . trim(basename($_FILES['files']['name']['images_' . $i])), FILE_EXISTS_RENAME);
            if (file_unmanaged_move($_FILES['files']['tmp_name']['images_' . $i], $zip)) {
              $value = new \stdClass();
              $value->pid = $pid;
              $value->nid = $form_state->getValue('nid') ? $form_state->getValue('nid') : $form_state->getValue('pid');
              $value->des = $form_state->getValue('des_' . $i);
              $value->title = $form_state->getValue('title_' . $i);
              if (!$file_count = _photos_unzip($zip, $value, $scheme, $account)) {
                $msg = t('Upload failed.');
              }
              else {
                $count = $count+$file_count;
              }
            }
          }
        }
      }
    }
    // Clear node and album page cache.
    Cache::invalidateTags(array('node:' . $nid, 'photos:album:' . $nid));
    $message = \Drupal::translation()->formatPlural($count, '1 image uploaded.', '@count images uploaded.');
    drupal_set_message($message);
  }
Пример #14
0
 /**
  * Tries to move or copy a file.
  *
  * @param string $source
  *  The source path or URI.
  * @param string $destination
  *  The destination path or URI.
  * @param integer $replace
  *  FILE_EXISTS_REPLACE (default) or FILE_EXISTS_RENAME.
  *
  * @return boolean
  *  TRUE on success, FALSE on failure.
  */
 protected function writeFile($source, $destination, $replace = FILE_EXISTS_REPLACE)
 {
     if ($this->configuration['move']) {
         return (bool) file_unmanaged_move($source, $destination, $replace);
     } else {
         $destination = file_destination($destination, $replace);
         $source = $this->urlencode($source);
         return @copy($source, $destination);
     }
 }
Пример #15
0
 /**
  * {@inheritdoc}
  */
 public static function valueCallback(&$element, $input, FormStateInterface $form_state)
 {
     $file_names = [];
     $return['uploaded_files'] = NULL;
     if ($input !== FALSE) {
         $user_input = NestedArray::getValue($form_state->getUserInput(), $element['#parents'] + ['uploaded_files']);
         if (!empty($user_input['uploaded_files'])) {
             $file_names = array_filter(explode(';', $user_input['uploaded_files']));
             $tmp_override = \Drupal::config('dropzonejs.settings')->get('tmp_dir');
             $temp_path = $tmp_override ? $tmp_override : \Drupal::config('system.file')->get('path.temporary');
             foreach ($file_names as $name) {
                 // The upload handler appended the txt extension to the file for
                 // security reasons. We will remove it in this callback.
                 $old_filepath = "{$temp_path}/{$name}";
                 // The upload handler appended the txt extension to the file for
                 // security reasons. Because here we know the acceptable extensions
                 // we can remove that extension and sanitize the filename.
                 $name = self::fixTmpFilename($name);
                 $name = file_munge_filename($name, self::getValidExtensions($element));
                 // Finaly rename the file and add it to results.
                 $new_filepath = "{$temp_path}/{$name}";
                 $move_result = file_unmanaged_move($old_filepath, $new_filepath);
                 if ($move_result) {
                     $return['uploaded_files'][] = ['path' => $move_result, 'filename' => $name];
                 } else {
                     drupal_set_message(t('There was a problem while processing the file named @name', ['@name' => $name]), 'error');
                 }
             }
         }
         $form_state->setValueForElement($element, $return);
         return $return;
     }
 }
Пример #16
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     static $images = array();
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     $extension = 'jpg';
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) {
         if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) {
             $destination = $tmp_file . '.' . $extension;
             file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
             $min = explode('x', $min_resolution);
             $max = explode('x', $max_resolution);
             $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
             $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
             $width = rand((int) $min[0], (int) $max[0]);
             $height = rand((int) $min[1], (int) $max[1]);
             $gray = isset($this->settings['devel_image_provider_gray']) ? $this->settings['devel_image_provider_gray'] : NULL;
             $gray_part = $gray ? '/g' : '';
             $url = "{$this->provider_base_url}" . $gray_part . "/{$width}/{$height}";
             $categories = isset($this->settings['devel_image_provider_categories']) ? $this->settings['devel_image_provider_categories'] : array();
             $category = array_rand($categories);
             if (!empty($category) && $category != 'any') {
                 $url .= '/' . $category;
             }
             $include_text = isset($this->settings['devel_image_provider_include_text']) ? $this->settings['devel_image_provider_include_text'] : FALSE;
             switch ($include_text) {
                 case 'custom':
                     $custom_text = isset($this->settings['devel_image_provider_custom_text']) ? $this->settings['devel_image_provider_custom_text'] : '';
                     break;
                 case 'random':
                     $custom_text = trim(substr(devel_create_greeking(mt_rand(1, 4)), 0, 16));
                     break;
                 case 'default':
                 default:
                     $custom_text = '';
                     break;
             }
             if (!empty($custom_text)) {
                 // Replace the spaces with - as per lorempixum specifications.
                 $custom_text = str_replace(' ', '-', check_plain($custom_text));
                 $url .= '/' . $custom_text;
             }
             $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents';
             $path = devel_image_provider_get_file($url, $destination, $method);
             $source = new stdClass();
             $source->uri = $path;
             $source->uid = 1;
             // TODO: randomize? Use case specific.
             $source->filemime = 'image/jpg';
             if (!empty($instance['settings']['file_directory'])) {
                 $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
             }
             $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . basename($path);
             $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
         } else {
             return FALSE;
         }
     } else {
         // Select one of the images we've already generated for this field.
         $file = new stdClass();
         $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user_value = $form_state->getValue('user');
    if ($user_value) {
      $form_state->setRebuild();
    }
    else {
      // @todo check if file is already in use before moving?
      // - If in use copy?
      $album = $form_state->getValue('album');
      $directory = $form_state->getValue('directory');
      $user = \Drupal::currentUser();
      $validators = array(
        'file_validate_is_image' => array()
      );
      $count = 0;
      $files_uploaded = array();
      $nid = $album;
      $album_uid = $form_state->getValue('uid');
      // If photos_access is enabled check viewid.
      $scheme = 'default';
      $album_viewid = 0;
      if (\Drupal::moduleHandler()->moduleExists('photos_access')) {
        $node = \Drupal\node\Entity\Node::load($nid);
        if (isset($node->privacy) && isset($node->privacy['viewid'])) {
          $album_viewid = $node->privacy['viewid'];
          if ($album_viewid > 0) {
            // Check for private file path.
            if (PrivateStream::basePath()) {
              $scheme = 'private';
            }
            else {
              // Set warning message.
              drupal_set_message(t('Warning: image files can still be accessed by visiting the direct URL.
                For better security, ask your website admin to setup a private file path.'), 'warning');
            }
          }
        }
      }
      $account = \Drupal::entityManager()->getStorage('user')->load($album_uid);
      // Check if zip is included.
      $allow_zip = \Drupal::config('photos.settings')->get('photos_upzip') ? '|zip|ZIP' : '';
      $file_extensions = 'png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF' . $allow_zip;
      $files = file_scan_directory($directory, '/^.*\.(' . $file_extensions . ')$/');
      foreach ($files as $dir_file) {
        $ext = \Drupal\Component\Utility\Unicode::substr($dir_file->uri, -3);
        if ($ext <> 'zip' && $ext <> 'ZIP') {
          // Prepare directory.
          $photos_path = photos_check_path($scheme, '', $account);
          $photos_name = _photos_rename($dir_file->filename);
          $file_uri = file_destination($photos_path . '/' . $photos_name, FILE_EXISTS_RENAME);
          if (file_unmanaged_move($dir_file->uri, $file_uri)) {
            // Save file to album. Include title and description.
            $image = \Drupal::service('image.factory')->get($file_uri);
            if ($image->getWidth()) {
              // Create a file entity.
              $file = entity_create('file', array(
                'uri' => $file_uri,
                'uid' => $user->id(),
                'status' => FILE_STATUS_PERMANENT,
                'pid' => $nid,
                'nid' => $nid,
                'filename' => $photos_name,
                'filesize' => $image->getFileSize(),
                'filemime' => $image->getMimeType()
              ));

              if ($file_fid = _photos_save_data($file)) {
                $files_uploaded[] = photos_image_date($file);
              }
              $count++;
            }
          }
        }
        else {
          // Zip upload from manual upload form.
          if (!\Drupal::config('photos.settings')->get('photos_upzip')) {
            return form_set_error('error', t('Please update settings to allow zip uploads.'));
          }
          $directory = photos_check_path();
          file_prepare_directory($directory);
          $zip = file_destination($directory . '/' . trim(basename($dir_file->uri)), FILE_EXISTS_RENAME);
          if (file_unmanaged_move($dir_file->uri, $zip)) {
            $value = new \stdClass();
            $value->pid = $nid;
            $value->nid = $nid;
            $value->des = '';
            $value->title = $dir_file->filename;
            if (!$file_count = _photos_unzip($zip, $value, $scheme, $account)) {
            $msg = t('Upload failed.');
            }
            else {
              $count = $count+$file_count;
            }
          }
        }
      }
      // Clear node and album page cache.
      Cache::invalidateTags(array('node:' . $nid, 'photos:album:' . $nid));
      $message = \Drupal::translation()->formatPlural($count, '1 image moved to selected album.', '@count images moved to selected album.');
      drupal_set_message($message);
    }
  }
Пример #18
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     static $images = array();
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     $extension = 'jpg';
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) {
         if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) {
             $destination = $tmp_file . '.' . $extension;
             file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
             $min = explode('x', $min_resolution);
             $max = explode('x', $max_resolution);
             $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
             $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
             $width = rand((int) $min[0], (int) $max[0]);
             $height = rand((int) $min[1], (int) $max[1]);
             $background_color = isset($this->settings['devel_image_provider_background_color']) ? $this->settings['devel_image_provider_background_color'] : FALSE;
             if ($background_color) {
                 if (preg_match('/^#[a-f0-9]{6}$/i', $background_color)) {
                     // Check for valid hex number
                     $background_color = "/" . str_replace('#', '', check_plain($background_color));
                     // Strip out #
                 } else {
                     $background_color = '';
                 }
             } else {
                 $background_color = '';
             }
             $text_color = isset($this->settings['devel_image_provider_text_color']) ? $this->settings['devel_image_provider_text_color'] : FALSE;
             if ($text_color) {
                 // Check for valid hex number.
                 if (preg_match('/^#[a-f0-9]{6}$/i', $text_color)) {
                     // Strip out # character.
                     $text_color = "/" . str_replace('#', '', check_plain($text_color));
                 } else {
                     $text_color = '';
                 }
             } else {
                 $text_color = '';
             }
             $include_text = isset($this->settings['devel_image_provider_include_text']) ? $this->settings['devel_image_provider_include_text'] : FALSE;
             switch ($include_text) {
                 case 'custom':
                     $custom_text = isset($this->settings['devel_image_provider_custom_text']) ? $this->settings['devel_image_provider_custom_text'] : '';
                     break;
                 case 'random':
                     // Small random text as text size is depending on the image size.
                     $custom_text = trim(substr(devel_create_greeking(mt_rand(1, 3)), 0, 8));
                     break;
                 case 'default':
                 default:
                     $custom_text = '';
                     break;
             }
             if (!empty($custom_text)) {
                 //Replace the spaces with + as per provider specifications
                 $custom_text = "&text=" . str_replace(' ', '+', check_plain($custom_text));
             }
             $url = "{$this->provider_base_url}/" . $width . "x" . $height . '/' . $background_color . '/' . $text_color . '&text=' . $custom_text;
             $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents';
             $path = devel_image_provider_get_file($url, $destination, $method);
             $source = new stdClass();
             $source->uri = $path;
             $source->uid = 1;
             // TODO: randomize? Use case specific.
             $source->filemime = 'image/jpg';
             if (!empty($instance['settings']['file_directory'])) {
                 $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
             }
             $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . basename($path);
             $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
         } else {
             return FALSE;
         }
     } else {
         // Select one of the images we've already generated for this field.
         $file = new stdClass();
         $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
Пример #19
0
 /**
  * {@inheritdoc}
  */
 public function save($destination)
 {
     $scheme = file_uri_scheme($destination);
     // Work around lack of stream wrapper support in imagejpeg() and imagepng().
     if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
         // If destination is not local, save image to temporary local file.
         $local_wrappers = $this->streamWrapperManager->getWrappers(StreamWrapperInterface::LOCAL);
         if (!isset($local_wrappers[$scheme])) {
             $permanent_destination = $destination;
             $destination = drupal_tempnam('temporary://', 'gd_');
         }
         // Convert stream wrapper URI to normal path.
         $destination = drupal_realpath($destination);
     }
     $function = 'image' . image_type_to_extension($this->getType(), FALSE);
     if (!function_exists($function)) {
         return FALSE;
     }
     if ($this->getType() == IMAGETYPE_JPEG) {
         $success = $function($this->getResource(), $destination, $this->configFactory->get('system.image.gd')->get('jpeg_quality'));
     } else {
         // Always save PNG images with full transparency.
         if ($this->getType() == IMAGETYPE_PNG) {
             imagealphablending($this->getResource(), FALSE);
             imagesavealpha($this->getResource(), TRUE);
         }
         $success = $function($this->getResource(), $destination);
     }
     // Move temporary local file to remote destination.
     if (isset($permanent_destination) && $success) {
         return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE);
     }
     return $success;
 }
Пример #20
0
 /**
  * {@inheritdoc}
  *
  * @todo Make parsers be able to handle streams. Maybe exclusively.
  * @todo Clean download cache directory.
  */
 public function fetch(FeedInterface $feed)
 {
     $feed_config = $feed->getConfigurationFor($this);
     $response = $this->get($feed_config['source']);
     // 304, nothing to see here.
     if ($response->getStatusCode() == 304) {
         drupal_set_message($this->t('The feed has not been updated.'));
         return;
     }
     // If there was a redirect, the url will be updated automagically.
     if ($url = $response->getParams()->get('feeds.redirect')) {
         $feed_config['source'] = $url;
         $feed->setConfigFor($this, $feed_config);
     }
     $tempname = $response->getBody()->getUri();
     $response->getBody()->close();
     $download_file = $this->prepareDirectory($feed_config['source']);
     file_unmanaged_move($tempname, $download_file, FILE_EXISTS_REPLACE);
     return new FetcherResult($download_file);
 }
Пример #21
0
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $random = new Random();
     $settings = $field_definition->getSettings();
     static $images = array();
     $min_resolution = empty($settings['min_resolution']) ? '100x100' : $settings['min_resolution'];
     $max_resolution = empty($settings['max_resolution']) ? '600x600' : $settings['max_resolution'];
     $extensions = array_intersect(explode(' ', $settings['file_extensions']), array('png', 'gif', 'jpg', 'jpeg'));
     $extension = array_rand(array_combine($extensions, $extensions));
     // Generate a max of 5 different images.
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= 5) {
         $tmp_file = drupal_tempnam('temporary://', 'generateImage_');
         $destination = $tmp_file . '.' . $extension;
         file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
         if ($path = $random->image(drupal_realpath($destination), $min_resolution, $max_resolution)) {
             $image = File::create();
             $image->setFileUri($path);
             $image->setOwnerId(\Drupal::currentUser()->id());
             $image->setMimeType(\Drupal::service('file.mime_type.guesser')->guess($path));
             $image->setFileName(drupal_basename($path));
             $destination_dir = static::doGetUploadLocation($settings);
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . '/' . basename($path);
             $file = file_move($image, $destination, FILE_CREATE_DIRECTORY);
             $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file;
         } else {
             return array();
         }
     } else {
         // Select one of the images we've already generated for this field.
         $image_index = array_rand($images[$extension][$min_resolution][$max_resolution]);
         $file = $images[$extension][$min_resolution][$max_resolution][$image_index];
     }
     list($width, $height) = getimagesize($file->getFileUri());
     $values = array('target_id' => $file->id(), 'alt' => $random->sentences(4), 'title' => $random->sentences(4), 'width' => $width, 'height' => $height);
     return $values;
 }
Пример #22
0
                				  }
                				  $i++;
                				}
                
                				file_put_contents($valid_file, $valid_data);
                				fclose($fp_exceptionfile);*/
                $info = pathinfo($file);
                $filename = $info["filename"];
                $basename = $info["basename"];
                $extension = $info["extension"];
                $dirname = $info["dirname"];
                if ($extension == 'dat' || $extension == 'DAT') {
                    $newbasename = "users_list_vendor.dat";
                    $current_path = $dirname . '/' . $basename;
                    $new_path = $destination . '/' . $newbasename;
                    file_unmanaged_move($current_path, $new_path, FILE_EXISTS_REPLACE);
                    $num++;
                } else {
                    //invalid file type, continue
                    continue;
                }
            }
        }
        closedir($handle);
    } else {
        echo "{$source} could not be opened.\n";
    }
}
// Execute the import.
if (is_file($destination . '/users_list_vendor.dat')) {
    smv_sitecron_source_config_path($importer_id);
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user = \Drupal::currentUser();
    $validators = array(
      'file_validate_is_image' => array()
    );
    $files_uploaded = array();
    if (\Drupal::config('photos.settings')->get('photos_plupload_status')) {
      $nid = $form_state->getValue('nid');
      $album_uid = db_query("SELECT uid FROM {node_field_data} WHERE nid = :nid", array(':nid' => $nid))->fetchField();
      if (empty($album_uid)) {
        $album_uid = $user->id();
      }
      // \Drupal\user\Entity\User::load($album_uid);
      $account = \Drupal::entityManager()->getStorage('user')->load($album_uid);
      $plupload_files = $form_state->getValue('plupload');
      foreach ($plupload_files as $uploaded_file) {
        if ($uploaded_file['status'] == 'done') {
          // Check for zip files.
          $ext = \Drupal\Component\Utility\Unicode::substr($uploaded_file['name'], -3);
          if ($ext <> 'zip' && $ext <> 'ZIP') {
            $photos_path = photos_check_path('default', '', $account);
            $photos_name = _photos_rename($uploaded_file['name']);
            $file_uri = file_destination($photos_path . '/' . $photos_name, FILE_EXISTS_RENAME);
            if (file_unmanaged_move($uploaded_file['tmppath'], $file_uri)) {
              $path_parts = pathinfo($file_uri);
              $image = \Drupal::service('image.factory')->get($file_uri);
              if ($path_parts['extension'] && $image->getWidth()) {
                // Create a file entity.
                $file = entity_create('file', array(
                  'uri' => $file_uri,
                  'uid' => $user->id(),
                  'status' => FILE_STATUS_PERMANENT,
                  'pid' => $form_state->getValue('pid'),
                  'nid' => $form_state->getValue('nid'),
                  'filename' => $photos_name,
                  'filesize' => $image->getFileSize(),
                  'filemime' => $image->getMimeType()
                ));

                if ($file_fid = _photos_save_data($file)) {
                  $files_uploaded[] = photos_image_date($file);
                }
              }
              else {
                file_delete($file_uri);
                \Drupal::logger('photos')->notice('Wrong file type', []);
              }
            }
            else {
              \Drupal::logger('photos')->notice('Upload error. Could not move temp file.', []);
            }
          }
          else {
            if (!\Drupal::config('photos.settings')->get('photos_upzip')) {
              drupal_set_message(t('Please set Album photos to open zip uploads.'), 'error');
            }
            $directory = photos_check_path();
            file_prepare_directory($directory);
            $zip = file_destination($directory . '/' . $uploaded_file['name'], FILE_EXISTS_RENAME);
            if (file_unmanaged_move($uploaded_file['tmppath'], $zip)) {
              $value = new stdClass();
              $value->pid = $form_state->getValue('pid');
              $value->nid = $form_state->getValue('nid');
              $value->title = $uploaded_file['name'];
              $value->des = '';
              if (!$msg = _photos_unzip($zip, $value)) {
                drupal_set_message(t('Zip upload failed.'), 'error');
              }
            }
          }
        }
        else {
          drupal_set_message(t('Error uploading some photos.'), 'error');
        }
      }
    }
  }
Пример #24
0
 /**
  * {@inheritdoc}
  */
 public function saveFile($uri, $destination, $extensions, AccountProxyInterface $user, $validators = [])
 {
     // Create the file entity.
     $file = $this->fileEntityFromUri($uri, $user);
     // Handle potentialy dangerous extensions.
     $renamed = $this->renameExecutableExtensions($file);
     // The .txt extension may not be in the allowed list of extensions. We have
     // to add it here or else the file upload will fail.
     if ($renamed && !empty($extensions)) {
         $extensions .= ' txt';
         drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->getFilename()]));
     }
     // Validate the file.
     $errors = $this->validateFile($file, $extensions, $validators);
     if (!empty($errors)) {
         $message = ['error' => ['#markup' => t('The specified file %name could not be uploaded.', ['%name' => $file->getFilename()])], 'item_list' => ['#theme' => 'item_list', '#items' => $errors]];
         drupal_set_message($this->renderer->renderPlain($message), 'error');
         return FALSE;
     }
     // Prepare destination.
     if (!$this->prepareDestination($file, $destination)) {
         drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]), 'error');
         return FALSE;
     }
     // Move uploaded files from PHP's upload_tmp_dir to destination.
     $move_result = file_unmanaged_move($uri, $file->getFileUri());
     if (!$move_result) {
         drupal_set_message(t('File upload error. Could not move uploaded file.'), 'error');
         $this->logger->notice('Upload error. Could not move uploaded file %file to destination %destination.', ['%file' => $file->getFilename(), '%destination' => $file->getFileUri()]);
         return FALSE;
     }
     // Set the permissions on the new file.
     $this->fileSystem->chmod($file->getFileUri());
     // If we made it this far it's safe to record this file in the database.
     $file->save();
     return $file;
 }