Пример #1
0
 /**
  * Create a file with the specified data.
  *
  * @param $data
  *   Twodimensional array.
  *
  * @param $file_options
  *   Array with record separator, etc.
  *
  * @return
  *   String. Path to file (in temporary directory).
  */
 public function nodeImportCreateFile($data, $file_options = array())
 {
     module_load_include('inc', 'node_import');
     $path = file_create_filename($this->randomName() . '.csv', file_directory_temp());
     $fp = fopen($path, 'w');
     foreach ($data as $row) {
         $s = node_import_write_to_string($row, $file_options);
         fputs($fp, $s);
     }
     fclose($fp);
     return $path;
 }
Пример #2
0
 /**
  * Resizes a list of imce items and returns succeeded ones.
  */
 public function resizeItems(ImceFM $fm, array $items, $width, $height, $copy = FALSE)
 {
     $factory = \Drupal::service('image.factory');
     $fs = \Drupal::service('file_system');
     $success = array();
     foreach ($items as $item) {
         $uri = $item->getUri();
         $image = $factory->get($uri);
         // Check vallidity
         if (!$image->isValid()) {
             continue;
         }
         // Check if resizing is needed.
         $resize = $image->getWidth() != $width || $image->getHeight() != $height;
         if (!$resize && !$copy) {
             continue;
         }
         if ($resize && !$image->resize($width, $height)) {
             continue;
         }
         // Save
         $destination = $copy ? file_create_filename($fs->basename($uri), $fs->dirname($uri)) : $uri;
         if (!$image->save($destination)) {
             continue;
         }
         // Create a new file record.
         if ($copy) {
             $filename = $fs->basename($destination);
             $values = array('uid' => $fm->user->id(), 'status' => 1, 'filename' => $filename, 'uri' => $destination, 'filesize' => $image->getFileSize(), 'filemime' => $image->getMimeType());
             $file = \Drupal::entityTypeManager()->getStorage('file')->create($values);
             // Check quota
             if ($errors = file_validate_size($file, 0, $fm->getConf('quota'))) {
                 file_unmanaged_delete($destination);
                 $fm->setMessage($errors[0]);
             } else {
                 $file->save();
                 // Add imce item
                 $item->parent->addFile($filename)->addToJs();
             }
         } else {
             if ($file = Imce::getFileEntity($uri)) {
                 $file->setSize($image->getFileSize());
                 $file->save();
             }
             // Add to js
             $item->addToJs();
         }
         $success[] = $item;
     }
     return $success;
 }
Пример #3
0
 /**
  * {@inheritdoc}
  */
 public static function value(array &$element, &$input, FormStateInterface $form_state)
 {
     if (isset($input['filefield_clipboard']['contents']) && strlen($input['filefield_clipboard']['contents']) > 0) {
         // 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)) {
             $url = $input['filefield_clipboard']['filename'];
             \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;
         }
         // Split the file information in mimetype and base64 encoded binary.
         $base64_data = $input['filefield_clipboard']['contents'];
         $comma_position = strpos($base64_data, ',');
         $semicolon_position = strpos($base64_data, ';');
         $file_contents = base64_decode(substr($base64_data, $comma_position + 1));
         $mimetype = substr($base64_data, 5, $semicolon_position - 5);
         $extension = \Drupal::service('file.mime_type.guesser.extension')->convertMimeTypeToExtension($mimetype);
         $filename = trim($input['filefield_clipboard']['filename']);
         $filename = preg_replace('/\\.[a-z0-9]{3,4}$/', '', $filename);
         $filename = (empty($filename) ? 'paste_' . REQUEST_TIME : $filename) . '.' . $extension;
         $filepath = file_create_filename($filename, $temporary_directory);
         $copy_success = FALSE;
         if ($fp = @fopen($filepath, 'w')) {
             fwrite($fp, $file_contents);
             fclose($fp);
             $copy_success = TRUE;
         }
         if ($copy_success && ($file = filefield_sources_save_file($filepath, $element['#upload_validators'], $element['#upload_location']))) {
             if (!in_array($file->id(), $input['fids'])) {
                 $input['fids'][] = $file->id();
             }
         }
         // Remove the temporary file generated from paste.
         @unlink($filepath);
     }
 }
Пример #4
0
 /**
  * Download a file from the URL generated by file_create_url().
  *
  * Create a file with the specified scheme, directory and filename; check that
  * the URL generated by file_create_url() for the specified file equals the
  * specified URL; fetch the URL and then compare the contents to the file.
  *
  * @param string $scheme
  *   A scheme, e.g. "public".
  * @param string $directory
  *   A directory, possibly "".
  * @param string $filename
  *   A filename.
  * @param string $expected_url
  *   The expected URL.
  */
 private function checkUrl($scheme, $directory, $filename, $expected_url)
 {
     // Convert $filename to a valid filename, i.e. strip characters not
     // supported by the filesystem, and create the file in the specified
     // directory.
     $filepath = file_create_filename($filename, $directory);
     $directory_uri = $scheme . '://' . dirname($filepath);
     file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
     $file = $this->createFile($filepath, NULL, $scheme);
     $url = file_create_url($file->getFileUri());
     $this->assertEqual($url, $expected_url);
     if ($scheme == 'private') {
         // Tell the implementation of hook_file_download() in file_test.module
         // that this file may be downloaded.
         file_test_set_return('download', array('x-foo' => 'Bar'));
     }
     $this->drupalGet($url);
     if ($this->assertResponse(200) == 'pass') {
         $this->assertRaw(file_get_contents($file->getFileUri()), 'Contents of the file are correct.');
     }
     $file->delete();
 }
?>
    
 
<div class="ppy" id="ppy1">
            <ul class="ppy-imglist">

			<?php 
$files = upload_load(node_load($nid));
$rows = array();
foreach ($files as $file) {
    if ($file->list) {
        $mime = explode('/', file_get_mimetype($file->filename));
        $type = $mime[0];
        switch ($type) {
            case 'image':
                $href = $file->fid ? file_create_url($file->filepath) : url(file_create_filename($file->filename, file_create_path()));
                ?>
 
                        <li>
                        <a href="<?php 
                print $href;
                ?>
">
                            <img src="<?php 
                print $href;
                ?>
" alt="<?php 
                print $file->description;
                ?>
" />
                        </a>
Пример #6
0
 /**
  * This will take a directory and path, and find a valid filepath that is not
  * taken by another file.
  */
 function testFileCreateNewFilepath()
 {
     // First we test against an imaginary file that does not exist in a
     // directory.
     $basename = 'xyz.txt';
     $directory = 'core/misc';
     $original = $directory . '/' . $basename;
     $path = file_create_filename($basename, $directory);
     $this->assertEqual($path, $original, format_string('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
     // Then we test against a file that already exists within that directory.
     $basename = 'druplicon.png';
     $original = $directory . '/' . $basename;
     $expected = $directory . '/druplicon_0.png';
     $path = file_create_filename($basename, $directory);
     $this->assertEqual($path, $expected, format_string('Creating a new filepath from %original equals %new (expected %expected).', array('%new' => $path, '%original' => $original, '%expected' => $expected)), 'File');
     // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.
 }
Пример #7
0
/**
 * Determines the destination path for a file depending on how replacement of
 * existing files should be handled.
 *
 * @param $destination A string specifying the desired path.
 * @param $replace Replace behavior when the destination file already exists.
 *   - FILE_EXISTS_REPLACE - Replace the existing file
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
 *     unique
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
 * @return The destination file path or FALSE if the file already exists and
 *   FILE_EXISTS_ERROR was specified.
 */
function file_destination($destination, $replace)
{
    if (file_exists($destination)) {
        switch ($replace) {
            case FILE_EXISTS_RENAME:
                $basename = basename($destination);
                $directory = dirname($destination);
                $destination = file_create_filename($basename, $directory);
                break;
            case FILE_EXISTS_ERROR:
                drupal_set_message(t('The selected file %file could not be copied, because a file by that name already exists in the destination.', array('%file' => $destination)), 'error');
                return FALSE;
        }
    }
    return $destination;
}
Пример #8
0
/**
* Displays file attachments as list items instead of in table
*/
function phptemplate_upload_attachments($files)
{
    $rows = array();
    foreach ($files as $file) {
        if ($file->list) {
            $href = $file->fid ? file_create_url($file->filepath) : url(file_create_filename($file->filename, file_create_path()));
            $text = $file->description ? $file->description : $file->filename;
            $rows[] = array(l($text, $href), format_size($file->filesize));
        }
    }
    foreach ($rows as $row) {
        $listfiles .= '<li>' . $row[0] . ' <em>(' . $row[1] . ')</em>' . '</li>';
    }
    return '<ul>' . $listfiles . '</ul>';
}
Пример #9
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);
     }
 }
Пример #10
0
 /**
  * Creates export file type and real path from URI.
  */
 protected function exportFileRealPath()
 {
     $path = $this->exportFilePath();
     $extension = $this->exportFileType();
     $this->file_uri = file_create_filename($this->filename . '_' . time() . $extension, $path);
     $this->file_location = \Drupal::service('file_system')->realpath($this->file_uri);
 }