diff --git a/cck.install b/cck.install index 49a2f9b..4a6ab3e 100644 --- a/cck.install +++ b/cck.install @@ -93,3 +93,66 @@ function cck_update_7000() { db_add_field('cck_field_settings', 'language', $field); } } + +function cck_update_7001(&$sandbox = array()) { + $ret = array(); + + // Query the existing D6 files table for possible duplicate URIs in D7. + if (db_table_exists('files')) { + if (!isset($sandbox['progress'])) { + $sandbox['progress'] = 0; + $sandbox['current_file'] = ''; + $sandbox['max'] = db_query("SELECT COUNT(f1.fid) FROM {files} f1 WHERE (SELECT count(f2.filepath) FROM {files} f2 WHERE f2.filepath = f1.filepath) > 1 ORDER BY f1.filename")->fetchField(); + } + + // Update 50 files at a time. + $batch_size = 50; + $query = "SELECT f1.fid, f1.filename, f1.filepath FROM {files} f1 WHERE (SELECT count(f2.filepath) FROM {files} f2 WHERE f2.filepath = f1.filepath) > 1 ORDER BY f1.filename"; + $result = db_query_range($query, $sandbox['current_file'], $batch_size); + $last_file = ''; + + foreach ($result as $record) { + if ($record->filepath == $last_file) { + // Log an error if the file copy destination is not writable. + $directory = str_replace('/' . $old_file, '', $record->filepath); + if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) { + watchdog('cck', 'The directory %directory could not be created or is not accessible.', array('%directory' => $directory)); + } + else { + // Log an error if the destination does not contain a valid stream. + $destination = variable_get('file_default_scheme', 'public') . '://'; + $destination_scheme = file_uri_scheme($destination); + if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) { + watchdog('cck', 'The file could not be copied, because the destination %destination is invalid.', array('%destination' => $destination), 'error'); + } + else { + // Duplicate file via copy. + $new_path = str_replace("public://", "", file_destination($destination . $record->filepath, FILE_EXISTS_RENAME)); + $saved_filepath = file_unmanaged_copy($record->filepath, $new_path, FILE_EXISTS_RENAME); + + // Update the database to use the new filename. + if ($saved_filepath) { + $saved_filepath_base = basename($saved_filepath); + $num_updated = db_update('files') + ->fields(array( + 'filename' => $saved_filepath_base, + 'filepath' => $saved_filepath, + )) + ->condition('fid', $record->fid, '=') + ->execute(); + drupal_set_message("Updated file: fid: $record->fid, $record->filename to $saved_filepath_base"); + } + } + } + } + $last_file = strtolower($record->filepath); + + $sandbox['current_file'] = $record->filepath; + } + + $sandbox['progress']++; + $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']); + } + + return $ret; +}