establish a default value for files as a files array with all empty or 0 valued elements.
[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('fid' => 0, 'filepath' => '', 'filename' => '', 'filemime' => '', 'filesize' => 0);
25 }
26
27 $files = _field_file_cache();
28
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));
33 }
34 else {
35 $file = db_fetch_object(db_query("SELECT f.* FROM {files} f WHERE f.filepath = '%s'", $fid));
36 }
37
38 if (!$file) {
39 $file = array('fid' => 0, 'filepath' => '', 'filename' => '', 'filemime' => '', 'filesize' => 0);
40 }
41
42 foreach (module_implements('file_load') as $module) {
43 $function = $module .'_file_load';
44 $function($file);
45 }
46
47 // Cache the fully loaded file for later reusability.
48 $files = _field_file_cache($file);
49 }
50
51 // Cast to array for field. hook_file() expects objects as well as
52 // core file functions.
53 return (array)$files[$fid];
54 }
55
56 /**
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
60 * to the file.
61 *
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.
65 *
66 * @param $source
67 * A string specifying the name of the upload field to save.
68 * @param $validators
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.
75 * @param $dest
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.
78 * @param $replace
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.
82 * @return
83 * An array containing the file information, or 0 in the event of an error.
84 */
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)) {
87 return 0;
88 }
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';
92 $function($file);
93 }
94 _field_file_cache($file); // cache the file in order to minimize load queries
95 return (array)$file;
96 }
97
98 /**
99 * Update an field item file. Delete marked items if neccessary and set new items as permamant.
100 *
101 * @param $node
102 * Node object this file is be associated with.
103 * @param $file
104 * File to be inserted, passed by reference since fid should be attached.
105 * @return array
106 */
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
111 // remove the item.
112 if (!empty($node->old_vid)) {
113 return array();
114 }
115 // Otherwise delete the file and return an empty array.
116 if (field_file_delete($file)) {
117 return array();
118 }
119 }
120
121 // Cast to object since core functions use objects.
122 $file = (object)$file;
123
124 // Set permanent status on files if unset.
125 if (empty($file->status)) {
126 file_set_status($file, FILE_STATUS_PERMANENT);
127 }
128
129 // Let modules update their additional file properties too.
130 foreach (module_implements('file_update') as $module) {
131 $function = $module .'_file_update';
132 $function($file);
133 }
134 _field_file_cache($file); // update the cache, in case the file has changed
135
136 $file = (array)$file;
137 return $file;
138 }
139
140 /**
141 * Delete a field file and its database record.
142 *
143 * @param $path
144 * A file object.
145 * @param $force
146 * Force File Deletion ignoring reference counting.
147 * @return mixed
148 * TRUE for success, Array for reference count block, or FALSE in the event of an error.
149 */
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)) {
158 return $references;
159 }
160 }
161
162 // Let other modules clean up on delete.
163 module_invoke_all('file_delete', $file);
164
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
170 return TRUE;
171 }
172 return FALSE;
173 }
174
175 /**
176 * Internal cache, in order to minimize database queries for loading files.
177 */
178 function _field_file_cache($file = NULL, $reset = FALSE) {
179 static $files = array();
180
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]);
185 }
186 else if ($reset) { // TRUE, delete the whole cache
187 $files = array();
188 }
189
190 // Cache the file by both fid and filepath.
191 // Use non-copying objects to save memory.
192 if (isset($file)) {
193 $files[$file->fid] = $file;
194 $files[$file->filepath] = $file;
195 }
196 return $files;
197 }
198
199 /**
200 * A silent version of file.inc:file_check_directory it's only talkative
201 * on errors.
202 *
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.
205 *
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.
214 */
215 function field_file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
216 $directory = rtrim($directory, '/\\');
217
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.
222 }
223 else {
224 if ($form_item) {
225 form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
226 }
227 watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
228 return FALSE;
229 }
230 }
231
232 // Check to see if the directory is writable.
233 if (!is_writable($directory)) {
234 if (($mode & FILE_MODIFY_PERMISSIONS) && !@chmod($directory, 0775)) {
235 if ($form_item) {
236 form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
237 }
238 watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
239 return FALSE;
240 }
241 }
242
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)) {
246 fclose($fp);
247 chmod($directory .'/.htaccess', 0664);
248 }
249 else {
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);
254 }
255 }
256
257 return TRUE;
258 }
259
260 /**
261 * Remove a possible leading file directory path from the given path.
262 */
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);
268 }
269 return $path;
270 }
271
272
273 /**
274 * return references to a file by a single field.
275 */
276
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
283 ));
284 if (isset($file->field_name) && $field['field_name'] == $file->field_name) {
285 --$references; // doesn't count as it's being deleted
286 }
287 return $references;
288 }