Exemple #1
0
/**
 * Callback to the module that defined the field to prepare items comparison.
 *
 * This allows the module to alter all items prior to rendering the comparative
 * values. It is mainly used to bulk load entities to reduce overheads
 * associated with loading entities individually.
 *
 * @param array $old_items
 *   An array of field items from the older revision.
 * @param array $new_items
 *   An array of field items from the newer revision.
 * @param array $context
 *   An associative array containing:
 *   - entity_type: The entity type; e.g., 'node' or 'user'.
 *   - bundle: The bundle name.
 *   - field: The field that the items belong to.
 *   - instance: The instance that the items belong to.
 *   - language: The language associated with $items.
 *   - old_entity: The older entity.
 *   - new_entity: The newer entity.
 *
 * @see MODULE_field_diff_view()
 */
function MODULE_field_diff_view_prepare(&$old_items, &$new_items, $context)
{
    $fids = array();
    foreach (array_merge_recursive($old_items, $new_items) as $info) {
        $fids[$info['fid']] = $info['fid'];
    }
    // A single load is much faster than individual loads.
    $files = file_load_multiple($fids);
    // For ease of processing, store a reference of the entity on the item array.
    foreach ($old_items as $delta => $info) {
        $old_items[$delta]['file'] = isset($files[$info['fid']]) ? $files[$info['fid']] : NULL;
    }
    foreach ($new_items as $delta => $info) {
        $new_items[$delta]['file'] = isset($files[$info['fid']]) ? $files[$info['fid']] : NULL;
    }
}
Exemple #2
0
 /**
  * This will test loading file data from the database.
  */
 function testMultiple()
 {
     // Create a new file entity.
     $file = $this->createFile('druplicon.txt', NULL, 'public');
     // Load by path.
     file_test_reset();
     $by_path_files = entity_load_multiple_by_properties('file', array('uri' => $file->getFileUri()));
     $this->assertFileHookCalled('load');
     $this->assertEqual(1, count($by_path_files), 'file_load_multiple() returned an array of the correct size.');
     $by_path_file = reset($by_path_files);
     $this->assertTrue($by_path_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
     $this->assertEqual($by_path_file->id(), $file->id(), 'Loading by filepath got the correct fid.', 'File');
     // Load by fid.
     file_test_reset();
     $by_fid_files = file_load_multiple(array($file->id()));
     $this->assertFileHooksCalled(array());
     $this->assertEqual(1, count($by_fid_files), 'file_load_multiple() returned an array of the correct size.');
     $by_fid_file = reset($by_fid_files);
     $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
     $this->assertEqual($by_fid_file->getFileUri(), $file->getFileUri(), 'Loading by fid got the correct filepath.', 'File');
 }
Exemple #3
0
function unl_reset_site_submit($form, &$form_state)
{
    $nids = db_select('node', 'n')->fields('n', array('nid'))->execute()->fetchCol();
    node_delete_multiple($nids);
    variable_set('site_frontpage', 'node');
    $mlids = db_select('menu_links', 'm')->fields('m', array('mlid'))->condition('m.menu_name', 'main-menu')->execute()->fetchCol();
    foreach ($mlids as $mlid) {
        menu_link_delete($mlid);
    }
    $home_link = array('link_path' => '<front>', 'link_title' => 'Home', 'menu_name' => 'main-menu', 'module' => 'menu');
    menu_link_save($home_link);
    $fids = db_select('file_managed', 'f')->fields('f', array('fid'))->execute()->fetchCol();
    $files = file_load_multiple($fids);
    foreach ($files as $file) {
        file_delete($file);
    }
    $files_dir = DRUPAL_ROOT . '/' . conf_path() . '/files/';
    $cmd = 'rm -rf ' . $files_dir . '*';
    echo shell_exec($cmd);
    drupal_mkdir('public://styles/');
    variable_set('site_name', 'Site Name');
}
 /**
  * Cleanup files created during download().
  *
  * It is expected that $files is returned from download(). Also, be aware that
  * each parent directory in the hierarchy may be removed if there are no more
  * files left in that directory.
  *
  * @param [] $files
  *   Array of files as returned from download() method.
  */
 public static function cleanup(array $files)
 {
     foreach ($files as $file_path => $file_name) {
         // Handle managed files.
         if (count(file_load_multiple([], ['uri' => $file_path])) > 0) {
             $file_obj = new \stdClass();
             $file_obj->uri = $file_path;
             file_delete($file_obj);
         } else {
             file_unmanaged_delete($file_path);
         }
         // Remove all directories in the tree if the file was the last one in this
         // directory.
         $file_dir = dirname($file_path);
         while (count(file_scan_directory($file_dir, '/.*/')) === 0) {
             if (!is_dir($file_dir)) {
                 break;
             }
             drupal_rmdir($file_dir);
             $file_dir = dirname($file_dir);
         }
     }
 }
Exemple #5
0
 /**
  * Test the file_save_upload() function.
  */
 function testNormal()
 {
     $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
     $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
     $file1 = file_load($max_fid_after);
     $this->assertTrue($file1, 'Loaded the file.');
     // MIME type of the uploaded image may be either image/jpeg or image/png.
     $this->assertEqual(substr($file1->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
     // Reset the hook counters to get rid of the 'load' we just called.
     file_test_reset();
     // Upload a second file.
     $image2 = current($this->drupalGetTestFiles('image'));
     $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
     $this->assertResponse(200, 'Received a 200 response for posted test file.');
     $this->assertRaw(t('You WIN!'));
     $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
     // Check that the correct hooks were called.
     $this->assertFileHooksCalled(array('validate', 'insert'));
     $file2 = file_load($max_fid_after);
     $this->assertTrue($file2, 'Loaded the file');
     // MIME type of the uploaded image may be either image/jpeg or image/png.
     $this->assertEqual(substr($file2->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
     // Load both files using file_load_multiple().
     $files = file_load_multiple(array($file1->id(), $file2->id()));
     $this->assertTrue(isset($files[$file1->id()]), 'File was loaded successfully');
     $this->assertTrue(isset($files[$file2->id()]), 'File was loaded successfully');
     // Upload a third file to a subdirectory.
     $image3 = current($this->drupalGetTestFiles('image'));
     $image3_realpath = drupal_realpath($image3->uri);
     $dir = $this->randomName();
     $edit = array('files[file_test_upload]' => $image3_realpath, 'file_subdir' => $dir);
     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
     $this->assertResponse(200, 'Received a 200 response for posted test file.');
     $this->assertRaw(t('You WIN!'));
     $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
 }
 /**
  * {@inheritdoc}
  */
 public function prepareView(array $entities_items)
 {
     // Remove files specified to not be displayed.
     $fids = array();
     foreach ($entities_items as $items) {
         foreach ($items as $item) {
             if ($item->isDisplayed() && !empty($item->target_id)) {
                 // Load the files from the files table.
                 $fids[] = $item->target_id;
             }
         }
     }
     if ($fids) {
         $files = file_load_multiple($fids);
         foreach ($entities_items as $items) {
             foreach ($items as $item) {
                 // If the file does not exist, mark the entire item as empty.
                 if (!empty($item->target_id)) {
                     $item->entity = isset($files[$item->target_id]) ? $files[$item->target_id] : NULL;
                 }
             }
         }
     }
 }
Exemple #7
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;
 }
  /**
   * An adaptation of file_save_upload() that includes more verbose errors.
   *
   * @param string $source
   *   A string specifying the filepath or URI of the uploaded file to save.
   *
   * @return stdClass
   *   The saved file object.
   *
   * @throws \RestfulBadRequestException
   * @throws \RestfulServiceUnavailable
   *
   * @see file_save_upload()
   */
  protected function fileSaveUpload($source) {
    static $upload_cache;

    $account = $this->getAccount();
    $options = $this->getPluginKey('options');

    $validators = $options['validators'];
    $destination = $options['scheme'] . "://";
    $replace = $options['replace'];

    // Return cached objects without processing since the file will have
    // already been processed and the paths in _FILES will be invalid.
    if (isset($upload_cache[$source])) {
      return $upload_cache[$source];
    }

    // Make sure there's an upload to process.
    if (empty($_FILES['files']['name'][$source])) {
      return NULL;
    }

    // Check for file upload errors and return FALSE if a lower level system
    // error occurred. For a complete list of errors:
    // See http://php.net/manual/features.file-upload.errors.php.
    switch ($_FILES['files']['error'][$source]) {
      case UPLOAD_ERR_INI_SIZE:
      case UPLOAD_ERR_FORM_SIZE:
        $message = format_string('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $_FILES['files']['name'][$source], '%maxsize' => format_size(file_upload_max_size())));
        throw new \RestfulBadRequestException($message);

      case UPLOAD_ERR_PARTIAL:
      case UPLOAD_ERR_NO_FILE:
        $message = format_string('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$source]));
        throw new \RestfulBadRequestException($message);

      case UPLOAD_ERR_OK:
        // Final check that this is a valid upload, if it isn't, use the
        // default error handler.
        if (is_uploaded_file($_FILES['files']['tmp_name'][$source])) {
          break;
        }

      // Unknown error
      default:
        $message = format_string('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$source]));
        throw new \RestfulServiceUnavailable($message);
    }

    // Begin building file object.
    $file = new stdClass();
    $file->uid      = $account->uid;
    $file->status   = 0;
    $file->filename = trim(drupal_basename($_FILES['files']['name'][$source]), '.');
    $file->uri      = $_FILES['files']['tmp_name'][$source];
    $file->filemime = file_get_mimetype($file->filename);
    $file->filesize = $_FILES['files']['size'][$source];

    $extensions = '';
    if (isset($validators['file_validate_extensions'])) {
      if (isset($validators['file_validate_extensions'][0])) {
        // Build the list of non-munged extensions if the caller provided them.
        $extensions = $validators['file_validate_extensions'][0];
      }
      else {
        // If 'file_validate_extensions' is set and the list is empty then the
        // caller wants to allow any extension. In this case we have to remove the
        // validator or else it will reject all extensions.
        unset($validators['file_validate_extensions']);
      }
    }
    else {
      // No validator was provided, so add one using the default list.
      // Build a default non-munged safe list for file_munge_filename().
      $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
      $validators['file_validate_extensions'] = array();
      $validators['file_validate_extensions'][0] = $extensions;
    }

    if (!empty($extensions)) {
      // Munge the filename to protect against possible malicious extension hiding
      // within an unknown file type (ie: filename.html.foo).
      $file->filename = file_munge_filename($file->filename, $extensions);
    }

    // Rename potentially executable files, to help prevent exploits (i.e. will
    // rename filename.php.foo and filename.php to filename.php.foo.txt and
    // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
    // evaluates to TRUE.
    if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
      $file->filemime = 'text/plain';
      $file->uri .= '.txt';
      $file->filename .= '.txt';
      // 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 (!empty($extensions)) {
        $validators['file_validate_extensions'][0] .= ' txt';

        // Unlike file_save_upload() we don't need to let the user know that
        // for security reasons, your upload has been renamed, since RESTful
        // will return the file name in the response.
      }
    }

    // If the destination is not provided, use the temporary directory.
    if (empty($destination)) {
      $destination = 'temporary://';
    }

    // Assert that the destination contains a valid stream.
    $destination_scheme = file_uri_scheme($destination);
    if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) {
      $message = format_string('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination));
      throw new \RestfulServiceUnavailable($message);
    }

    $file->source = $source;
    // A URI may already have a trailing slash or look like "public://".
    if (substr($destination, -1) != '/') {
      $destination .= '/';
    }
    $file->destination = file_destination($destination . $file->filename, $replace);
    // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
    // there's an existing file so we need to bail.
    if ($file->destination === FALSE) {
      $message = format_string('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $source, '%directory' => $destination));
      throw new \RestfulServiceUnavailable($message);
    }

    // Add in our check of the the file name length.
    $validators['file_validate_name_length'] = array();

    // Call the validation functions specified by this function's caller.
    $errors = file_validate($file, $validators);

    // Check for errors.
    if (!empty($errors)) {
      $message = format_string('The specified file %name could not be uploaded.', array('%name' => $file->filename));
      if (count($errors) > 1) {
        $message .= theme('item_list', array('items' => $errors));
      }
      else {
        $message .= ' ' . array_pop($errors);
      }

      throw new \RestfulServiceUnavailable($message);
    }

    // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
    // directory. This overcomes open_basedir restrictions for future file
    // operations.
    $file->uri = $file->destination;
    if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) {
      watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
      $message = 'File upload error. Could not move uploaded file.';
      throw new \RestfulServiceUnavailable($message);
    }

    // Set the permissions on the new file.
    drupal_chmod($file->uri);

    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('uri' => $file->uri));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing->fid;
      }
    }

    // If we made it this far it's safe to record this file in the database.
    if ($file = file_save($file)) {
      // Add file to the cache.
      $upload_cache[$source] = $file;
      return $file;
    }

    // Something went wrong, so throw a general exception.
    throw new \RestfulServiceUnavailable('Unknown error has occurred.');
  }
 /**
  * Retrieve managed file object using specified URI.
  *
  * @param string $uri
  *   File URI.
  *
  * @return bool|object
  *   Managed file object or FALSE if file was not found.
  */
 public function getManagedFileByUri($uri)
 {
     $files = file_load_multiple([], ['uri' => $uri]);
     if (count($files)) {
         return reset($files);
     }
     return FALSE;
 }
Exemple #10
0
 /**
  * Helper method for fetching all translation request files.
  *
  * @return array
  *    An array with objects or an empty one if there is no results.
  */
 public static function getAllRequestTranslationFiles()
 {
     $result = db_select('file_managed', 'fm')->fields('fm', ['fid'])->condition('filemime', 'application/xml', '=')->condition('uri', db_like(TMGMT_POETRY_MOCK_REQUESTS_PATH) . '%', 'LIKE')->orderBy('timestamp', 'DESC')->execute()->fetchAllAssoc('fid');
     if ($result) {
         return file_load_multiple(array_keys($result));
     }
     return [];
 }