update hook_file implementation to reflect modt recent core hook_file path with callb...
[project/filefield.git] / field_file.inc
1 <?php
2 // $Id$
3 /**
4 * @file
5 * Common functionality for file handling CCK field modules.
6 */
7
8 /**
9 * Load a file object from the database.
10 *
11 * @param $fid
12 * A numeric file id or string containing the file path.
13 *
14 * @param $reset
15 * Whether to reset the internal file_load cache.
16 */
17 function field_file_load($fid, $reset = NULL) {
18 // Reset internal cache.
19 if (isset($reset)) {
20 _field_file_cache(NULL, TRUE);
21 }
22
23 if (empty($fid)) {
24 return array();
25 }
26 $files = _field_file_cache();
27
28 // Serve file from internal cache if available.
29 if (empty($files[$fid])) {
30 if (is_numeric($fid)) {
31 $file = db_fetch_object(db_query('SELECT f.* FROM {files} f WHERE f.fid = %d', $fid));
32 }
33 else {
34 $file = db_fetch_object(db_query("SELECT f.* FROM {files} f WHERE f.filepath = '%s'", $fid));
35 }
36
37 if (!$file) {
38 return array();
39 }
40
41 foreach (module_implements('file_load') as $module) {
42 $function = $module .'_file_load';
43 $function($file);
44 }
45
46 // Cache the fully loaded file for later reusability.
47 $files = _field_file_cache($file);
48 }
49
50 // Cast to array for field. hook_file() expects objects as well as
51 // core file functions.
52 return (array)$files[$fid];
53 }
54
55 /**
56 * Save a file upload to a new location. The source file is validated as a
57 * proper upload and handled as such. By implementing hook_file($op = 'insert'),
58 * modules are able to act on the file upload and to add their own properties
59 * to the file.
60 *
61 * The file will be added to the files table as a temporary file. Temporary files
62 * are periodically cleaned. To make the file permanent file call
63 * file_set_status() to change its status.
64 *
65 * @param $source
66 * A string specifying the name of the upload field to save.
67 * @param $validators
68 * An optional, associative array of callback functions used to validate the
69 * file. The keys are function names and the values arrays of callback
70 * parameters which will be passed in after the user and file objects. The
71 * functions should return an array of error messages, an empty array
72 * indicates that the file passed validation. The functions will be called in
73 * the order specified.
74 * @param $dest
75 * A string containing the directory $source should be copied to. If this is
76 * not provided or is not writable, the temporary directory will be used.
77 * @param $replace
78 * A boolean indicating whether an existing file of the same name in the
79 * destination directory should overwritten. A false value will generate a
80 * new, unique filename in the destination directory.
81 * @return
82 * An array containing the file information, or 0 in the event of an error.
83 */
84 function field_file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME) {
85 if (!$file = file_save_upload($source, $validators, $dest, $replace)) {
86 return 0;
87 }
88 // Let modules add additional properties to the yet barebone file object.
89 foreach (module_implements('file_insert') as $module) {
90 $function = $module .'_file_insert';
91 $function($file);
92 }
93 _field_file_cache($file); // cache the file in order to minimize load queries
94 return (array)$file;
95 }
96
97 /**
98 * Update an field item file. Delete marked items if neccessary and set new items as permamant.
99 *
100 * @param $node
101 * Node object this file is be associated with.
102 * @param $file
103 * File to be inserted, passed by reference since fid should be attached.
104 * @return array
105 */
106 function field_file_save($node, &$file) {
107 // If this item is marked for deletion.
108 if (!empty($file['delete'])) {
109 // If we're creating a new revision, return an empty array so CCK will
110 // remove the item.
111 if (!empty($node->old_vid)) {
112 return array();
113 }
114 // Otherwise delete the file and return an empty array.
115 if (field_file_delete($file)) {
116 return array();
117 }
118 }
119
120 // Cast to object since core functions use objects.
121 $file = (object)$file;
122
123 // Set permanent status on files if unset.
124 if (empty($file->status)) {
125 file_set_status($file, FILE_STATUS_PERMANENT);
126 }
127
128 // Let modules update their additional file properties too.
129 foreach (module_implements('file_update') as $module) {
130 $function = $module .'_file_update';
131 $function($file);
132 }
133 _field_file_cache($file); // update the cache, in case the file has changed
134
135 $file = (array)$file;
136 return $file;
137 }
138
139 /**
140 * Delete a field file and its database record.
141 *
142 * @param $path
143 * A file object.
144 * @param $force
145 * Force File Deletion ignoring reference counting.
146 * @return mixed
147 * TRUE for success, Array for reference count block, or FALSE in the event of an error.
148 */
149 function field_file_delete($file, $force = FALSE) {
150 $file = (object)$file;
151 // If any module returns a value from the reference hook, the
152 // file will not be deleted from Drupal, but file_delete will
153 // return a populated array that tests as TRUE.
154 if (!$force && $references = module_invoke_all('file_references', $file)) {
155 $references = array_filter($references); // only keep positive values
156 if (!empty($references)) {
157 return $references;
158 }
159 }
160
161 // Let other modules clean up on delete.
162 module_invoke_all('file_delete', $file);
163
164 // Make sure the file is deleted before removing its row from the
165 // database, so UIs can still find the file in the database.
166 if (file_delete($file->filepath)) {
167 db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
168 _field_file_cache(NULL, $file); // delete the file from the cache
169 return TRUE;
170 }
171 return FALSE;
172 }
173
174 /**
175 * Internal cache, in order to minimize database queries for loading files.
176 */
177 function _field_file_cache($file = NULL, $reset = FALSE) {
178 static $files = array();
179
180 // Reset internal cache.
181 if (is_object($reset)) { // file object, uncache just that one
182 unset($files[$reset->fid]);
183 unset($files[$reset->filepath]);
184 }
185 else if ($reset) { // TRUE, delete the whole cache
186 $files = array();
187 }
188
189 // Cache the file by both fid and filepath.
190 // Use non-copying objects to save memory.
191 if (isset($file)) {
192 $files[$file->fid] = $file;
193 $files[$file->filepath] = $file;
194 }
195 return $files;
196 }
197
198 /**
199 * A silent version of file.inc:file_check_directory it's only talkative
200 * on errors.
201 *
202 * Check that the directory exists and is writable. Directories need to
203 * have execute permissions to be considered a directory by FTP servers, etc.
204 *
205 * @param $directory A string containing the name of a directory path.
206 * @param $mode A Boolean value to indicate if the directory should be created
207 * if it does not exist or made writable if it is read-only.
208 * @param $form_item An optional string containing the name of a form item that
209 * any errors will be attached to. This is useful for settings forms that
210 * require the user to specify a writable directory. If it can't be made to
211 * work, a form error will be set preventing them from saving the settings.
212 * @return FALSE when directory not found, or TRUE when directory exists.
213 */
214 function field_file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
215 $directory = rtrim($directory, '/\\');
216
217 // Check if the directory exists.
218 if (!is_dir($directory)) {
219 if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory)) {
220 @chmod($directory, 0775); // Necessary for non-webserver users.
221 }
222 else {
223 if ($form_item) {
224 form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
225 }
226 watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
227 return FALSE;
228 }
229 }
230
231 // Check to see if the directory is writable.
232 if (!is_writable($directory)) {
233 if (($mode & FILE_MODIFY_PERMISSIONS) && !@chmod($directory, 0775)) {
234 if ($form_item) {
235 form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
236 }
237 watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
238 return FALSE;
239 }
240 }
241
242 if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
243 $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
244 if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
245 fclose($fp);
246 chmod($directory .'/.htaccess', 0664);
247 }
248 else {
249 $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>";
250 $repl = array('%directory' => $directory, '!htaccess' => '<br />'. nl2br(check_plain($htaccess_lines)));
251 form_set_error($form_item, t($message, $repl));
252 watchdog('security', $message, $repl, WATCHDOG_ERROR);
253 }
254 }
255
256 return TRUE;
257 }
258
259 /**
260 * Remove a possible leading file directory path from the given path.
261 */
262 function field_file_strip_path($path) {
263 $dirpath = file_directory_path();
264 $dirlen = drupal_strlen($dirpath);
265 if (drupal_substr($path, 0, $dirlen + 1) == $dirpath .'/') {
266 $path = drupal_substr($path, $dirlen + 1);
267 }
268 return $path;
269 }
270
271
272 /**
273 * return references to a file by a single field.
274 */
275
276 function field_file_references($file, $field) {
277 $db_info = content_database_info($field);
278 $references += db_result(db_query(
279 'SELECT count('. $db_info['columns']['fid']['column'] .')
280 FROM {'. $db_info['table'] .'}
281 WHERE '. $db_info['columns']['fid']['column'] .' = %d', $file->fid
282 ));
283 if (isset($file->field_name) && $field['field_name'] == $file->field_name) {
284 --$references; // doesn't count as it's being deleted
285 }
286 return $references;
287 }