protected function urlToFileEntity($url) { $url = urldecode(DRUPAL_ROOT . EntityPathHelper::normalizeUrl($url)); if (file_exists($url)) { // Get the filename. $filename = pathinfo($url, PATHINFO_FILENAME) . '.' . pathinfo($url, PATHINFO_EXTENSION); $filesize = filesize($url); $files = db_select('file_managed', 'f')->fields('f', array('fid', 'uri', 'filesize'))->condition('filename', $filename)->condition('filesize', $filesize)->execute(); $found_fid = -1; while ($row = $files->fetch()) { $result_uri = drupal_realpath($row->uri); if ($result_uri == drupal_realpath($url)) { $found_fid = $row->fid; break; } } if ($found_fid !== -1) { return Entity::load($found_fid, 'file'); } else { // Create the file entity. if ($contents = file_get_contents($url)) { $public_files_directory = DRUPAL_ROOT . '/' . variable_get('file_public_path', conf_path() . '/files') . '/'; $schema_url = 'public://' . str_replace($public_files_directory, '', $url); // This will basically re-create the same file with the same filename, so we don't // need to check to see if the file already exists because we don't care to replace // the file with itself. $file = file_save_data($contents, $schema_url, FILE_EXISTS_REPLACE); return Entity::load($file->fid, 'file'); } } } return false; }