5 * Common functionality for file handling CCK field modules.
9 * Load a file object from the database.
12 * A numeric file id or string containing the file path.
15 * Whether to reset the internal file_load cache.
17 function field_file_load($fid, $reset = NULL
) {
18 // Reset internal cache.
20 _field_file_cache(NULL
, TRUE
);
24 return array('fid' => 0, 'filepath' => '', 'filename' => '', 'filemime' => '', 'filesize' => 0);
27 $files = _field_file_cache();
29 // Serve file from internal cache if available.
30 if (empty($files[$fid])) {
31 if (is_numeric($fid)) {
32 $file = db_fetch_object(db_query('SELECT f.* FROM {files} f WHERE f.fid = %d', $fid));
35 $file = db_fetch_object(db_query("SELECT f.* FROM {files} f WHERE f.filepath = '%s'", $fid));
39 $file = array('fid' => 0, 'filepath' => '', 'filename' => '', 'filemime' => '', 'filesize' => 0);
42 foreach (module_implements('file_load') as
$module) {
43 $function = $module .
'_file_load';
47 // Cache the fully loaded file for later reusability.
48 $files = _field_file_cache($file);
51 // Cast to array for field. hook_file() expects objects as well as
52 // core file functions.
53 return (array)$files[$fid];
57 * Save a file upload to a new location. The source file is validated as a
58 * proper upload and handled as such. By implementing hook_file($op = 'insert'),
59 * modules are able to act on the file upload and to add their own properties
62 * The file will be added to the files table as a temporary file. Temporary files
63 * are periodically cleaned. To make the file permanent file call
64 * file_set_status() to change its status.
67 * A string specifying the name of the upload field to save.
69 * An optional, associative array of callback functions used to validate the
70 * file. The keys are function names and the values arrays of callback
71 * parameters which will be passed in after the user and file objects. The
72 * functions should return an array of error messages, an empty array
73 * indicates that the file passed validation. The functions will be called in
74 * the order specified.
76 * A string containing the directory $source should be copied to. If this is
77 * not provided or is not writable, the temporary directory will be used.
79 * A boolean indicating whether an existing file of the same name in the
80 * destination directory should overwritten. A false value will generate a
81 * new, unique filename in the destination directory.
83 * An array containing the file information, or 0 in the event of an error.
85 function field_file_save_upload($source, $validators = array(), $dest = FALSE
, $replace = FILE_EXISTS_RENAME
) {
86 if (!$file = file_save_upload($source, $validators, $dest, $replace)) {
89 // Let modules add additional properties to the yet barebone file object.
90 foreach (module_implements('file_insert') as
$module) {
91 $function = $module .
'_file_insert';
94 _field_file_cache($file); // cache the file in order to minimize load queries
99 * Update an field item file. Delete marked items if neccessary and set new items as permamant.
102 * Node object this file is be associated with.
104 * File to be inserted, passed by reference since fid should be attached.
107 function field_file_save($node, &$file) {
108 // If this item is marked for deletion.
109 if (!empty($file['delete'])) {
110 // If we're creating a new revision, return an empty array so CCK will
112 if (!empty($node->old_vid
)) {
115 // Otherwise delete the file and return an empty array.
116 if (field_file_delete($file)) {
121 // Cast to object since core functions use objects.
122 $file = (object)$file;
124 // Set permanent status on files if unset.
125 if (empty($file->status
)) {
126 file_set_status($file, FILE_STATUS_PERMANENT
);
129 // Let modules update their additional file properties too.
130 foreach (module_implements('file_update') as
$module) {
131 $function = $module .
'_file_update';
134 _field_file_cache($file); // update the cache, in case the file has changed
136 $file = (array)$file;
141 * Delete a field file and its database record.
146 * Force File Deletion ignoring reference counting.
148 * TRUE for success, Array for reference count block, or FALSE in the event of an error.
150 function field_file_delete($file, $force = FALSE
) {
151 $file = (object)$file;
152 // If any module returns a value from the reference hook, the
153 // file will not be deleted from Drupal, but file_delete will
154 // return a populated array that tests as TRUE.
155 if (!$force && $references = module_invoke_all('file_references', $file)) {
156 $references = array_filter($references); // only keep positive values
157 if (!empty($references)) {
162 // Let other modules clean up on delete.
163 module_invoke_all('file_delete', $file);
165 // Make sure the file is deleted before removing its row from the
166 // database, so UIs can still find the file in the database.
167 if (file_delete($file->filepath
)) {
168 db_query('DELETE FROM {files} WHERE fid = %d', $file->fid
);
169 _field_file_cache(NULL
, $file); // delete the file from the cache
176 * Internal cache, in order to minimize database queries for loading files.
178 function _field_file_cache($file = NULL
, $reset = FALSE
) {
179 static
$files = array();
181 // Reset internal cache.
182 if (is_object($reset)) { // file object, uncache just that one
183 unset($files[$reset->fid
]);
184 unset($files[$reset->filepath
]);
186 else if ($reset) { // TRUE, delete the whole cache
190 // Cache the file by both fid and filepath.
191 // Use non-copying objects to save memory.
193 $files[$file->fid
] = $file;
194 $files[$file->filepath
] = $file;
200 * A silent version of file.inc:file_check_directory it's only talkative
203 * Check that the directory exists and is writable. Directories need to
204 * have execute permissions to be considered a directory by FTP servers, etc.
206 * @param $directory A string containing the name of a directory path.
207 * @param $mode A Boolean value to indicate if the directory should be created
208 * if it does not exist or made writable if it is read-only.
209 * @param $form_item An optional string containing the name of a form item that
210 * any errors will be attached to. This is useful for settings forms that
211 * require the user to specify a writable directory. If it can't be made to
212 * work, a form error will be set preventing them from saving the settings.
213 * @return FALSE when directory not found, or TRUE when directory exists.
215 function field_file_check_directory(&$directory, $mode = 0, $form_item = NULL
) {
216 $directory = rtrim($directory, '/\\');
218 // Check if the directory exists.
219 if (!is_dir($directory)) {
220 if (($mode & FILE_CREATE_DIRECTORY
) && @
mkdir($directory)) {
221 @
chmod($directory, 0775); // Necessary for non-webserver users.
225 form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
227 watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR
);
232 // Check to see if the directory is writable.
233 if (!is_writable($directory)) {
234 if (($mode & FILE_MODIFY_PERMISSIONS
) && !@
chmod($directory, 0775)) {
236 form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
238 watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR
);
243 if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
244 $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
245 if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
247 chmod($directory .
'/.htaccess', 0664);
250 $message = "Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <code>!htaccess</code>";
251 $repl = array('%directory' => $directory, '!htaccess' => '<br />'.
nl2br(check_plain($htaccess_lines)));
252 form_set_error($form_item, t($message, $repl));
253 watchdog('security', $message, $repl, WATCHDOG_ERROR
);
261 * Remove a possible leading file directory path from the given path.
263 function field_file_strip_path($path) {
264 $dirpath = file_directory_path();
265 $dirlen = drupal_strlen($dirpath);
266 if (drupal_substr($path, 0, $dirlen + 1) == $dirpath .
'/') {
267 $path = drupal_substr($path, $dirlen + 1);
274 * return references to a file by a single field.
277 function field_file_references($file, $field) {
278 $db_info = content_database_info($field);
279 $references += db_result(db_query(
280 'SELECT count('.
$db_info['columns']['fid']['column'] .
')
281 FROM {'.
$db_info['table'] .
'}
282 WHERE '.
$db_info['columns']['fid']['column'] .
' = %d', $file->fid
284 if (isset($file->field_name
) && $field['field_name'] == $file->field_name
) {
285 --$references; // doesn't count as it's being deleted