#857908: Corrected file name typo.
[project/filefield.git] / field_file.inc
1 <?php
2 // $Id$
3
4 /**
5 * @file
6 * Common functionality for file handling CCK field modules.
7 */
8
9 /**
10 * Load a file from the database.
11 *
12 * @param $fid
13 * A numeric file id or string containing the file path.
14 * @param $reset
15 * Whether to reset the internal file_load cache.
16 * @return
17 * A file array.
18 */
19 function field_file_load($fid, $reset = NULL) {
20 // Reset internal cache.
21 if (isset($reset)) {
22 _field_file_cache(NULL, TRUE);
23 }
24
25 if (empty($fid)) {
26 return array('fid' => 0, 'filepath' => '', 'filename' => '', 'filemime' => '', 'filesize' => 0);
27 }
28
29 $files = _field_file_cache();
30
31 // Serve file from internal cache if available.
32 if (empty($files[$fid])) {
33 if (is_numeric($fid)) {
34 $file = db_fetch_object(db_query('SELECT f.* FROM {files} f WHERE f.fid = %d', $fid));
35 }
36 else {
37 $file = db_fetch_object(db_query("SELECT f.* FROM {files} f WHERE f.filepath = '%s'", $fid));
38 }
39
40 if (!$file) {
41 $file = (object) array('fid' => 0, 'filepath' => '', 'filename' => '', 'filemime' => '', 'filesize' => 0);
42 }
43
44 foreach (module_implements('file_load') as $module) {
45 if ($module != 'field') {
46 $function = $module .'_file_load';
47 $function($file);
48 }
49 }
50
51 // Cache the fully loaded file for later use.
52 $files = _field_file_cache($file);
53 }
54
55 // Cast to an array for the field storage.
56 // Contrary to fields, hook_file() and core file functions expect objects.
57 return isset($files[$fid]) ? (array) $files[$fid] : FALSE;
58 }
59
60 /**
61 * Save a file upload to a new location.
62 * The source file is validated as a proper upload and handled as such. By
63 * implementing hook_file($op = 'insert'), modules are able to act on the file
64 * upload and to add their own properties to the file.
65 *
66 * The file will be added to the files table as a temporary file. Temporary
67 * files are periodically cleaned. To make the file permanent file call
68 * file_set_status() to change its status.
69 *
70 * @param $source
71 * A string specifying the name of the upload field to save.
72 * @param $validators
73 * An optional, associative array of callback functions used to validate the
74 * file. The keys are function names and the values arrays of callback
75 * parameters which will be passed in after the user and file objects. The
76 * functions should return an array of error messages, an empty array
77 * indicates that the file passed validation. The functions will be called in
78 * the order specified.
79 * @param $dest
80 * A string containing the directory $source should be copied to. If this is
81 * not provided or is not writable, the temporary directory will be used.
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) {
86 if (!$file = file_save_upload($source, $validators, $dest, FILE_EXISTS_RENAME)) {
87 return 0;
88 }
89 if (!@chmod($file->filepath, 0664)) {
90 watchdog('filefield', 'Could not set permissions on destination file: %file', array('%file' => $file->filepath));
91 }
92
93 // Let modules add additional properties to the yet barebone file object.
94 foreach (module_implements('file_insert') as $module) {
95 $function = $module .'_file_insert';
96 $function($file);
97 }
98 _field_file_cache($file); // cache the file in order to minimize load queries
99 return (array)$file;
100 }
101
102 /**
103 * Save a file into a file node after running all the associated validators.
104 *
105 * This function is usually used to move a file from the temporary file
106 * directory to a permanent location. It may be used by import scripts or other
107 * modules that want to save an existing file into the database.
108 *
109 * @param $filepath
110 * The local file path of the file to be saved.
111 * @param $validators
112 * An optional, associative array of callback functions used to validate the
113 * file. The keys are function names and the values arrays of callback
114 * parameters which will be passed in after the user and file objects. The
115 * functions should return an array of error messages, an empty array
116 * indicates that the file passed validation. The functions will be called in
117 * the order specified.
118 * @param $dest
119 * A string containing the directory $source should be copied to. If this is
120 * not provided or is not writable, the temporary directory will be used.
121 * @param $account
122 * The user account object that should associated with the uploaded file.
123 * @return
124 * An array containing the file information, or 0 in the event of an error.
125 */
126 function field_file_save_file($filepath, $validators = array(), $dest = FALSE, $account = NULL) {
127 if (!isset($account)) {
128 $account = $GLOBALS['user'];
129 }
130
131 // Add in our check of the the file name length.
132 $validators['file_validate_name_length'] = array();
133
134 // Begin building file object.
135 $file = new stdClass();
136 $file->uid = $account->uid;
137 $file->filename = basename($filepath);
138 $file->filepath = $filepath;
139 $file->filemime = module_exists('mimedetect') ? mimedetect_mime($file) : file_get_mimetype($file->filename);
140
141 // Rename potentially executable files, to help prevent exploits.
142 if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
143 $file->filemime = 'text/plain';
144 $file->filepath .= '.txt';
145 $file->filename .= '.txt';
146 }
147
148 // If the destination is not provided, or is not writable, then use the
149 // temporary directory.
150 if (empty($dest) || file_check_path($dest) === FALSE) {
151 $dest = file_directory_temp();
152 }
153
154 $file->source = 'field_file_save_file';
155 $file->destination = file_destination(file_create_path($dest .'/'. $file->filename), FILE_EXISTS_RENAME);
156 $file->filesize = filesize($filepath);
157
158 // Call the validation functions.
159 $errors = array();
160 foreach ($validators as $function => $args) {
161 // Add the $file variable to the list of arguments and pass it by
162 // reference (required for PHP 5.3 and higher).
163 array_unshift($args, NULL);
164 $args[0] = &$file;
165 $errors = array_merge($errors, call_user_func_array($function, $args));
166 }
167
168 // Check for validation errors.
169 if (!empty($errors)) {
170 $message = t('The selected file %name could not be saved.', array('%name' => $file->filename));
171 if (count($errors) > 1) {
172 $message .= '<ul><li>'. implode('</li><li>', $errors) .'</li></ul>';
173 }
174 else {
175 $message .= ' '. array_pop($errors);
176 }
177 form_set_error($file->source, $message);
178 return 0;
179 }
180
181 if (!file_copy($file, $file->destination, FILE_EXISTS_RENAME)) {
182 form_set_error($file->source, t('File upload error. Could not move uploaded file.'));
183 watchdog('file', 'Upload error. Could not move file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->destination));
184 return 0;
185 }
186
187 // If we made it this far it's safe to record this file in the database.
188 $file->status = FILE_STATUS_TEMPORARY;
189 $file->timestamp = time();
190 // Insert new record to the database.
191 drupal_write_record('files', $file);
192
193 // Let modules add additional properties to the yet barebone file object.
194 foreach (module_implements('file_insert') as $module) {
195 $function = $module .'_file_insert';
196 $function($file);
197 }
198 _field_file_cache($file); // cache the file in order to minimize load queries
199 return (array)$file;
200 }
201
202 /**
203 * Save a node file. Delete items if necessary and set new items as permanent.
204 *
205 * @param $node
206 * Node object this file is be associated with.
207 * @param $file
208 * File to be inserted, passed by reference since fid should be attached.
209 * @return array
210 */
211 function field_file_save($node, &$file) {
212 // If this item is marked for deletion.
213 if (!empty($file['delete']) || !empty($file['_remove'])) {
214 // If we're creating a new revision, return an empty array so CCK will
215 // remove the item.
216 if (!empty($node->old_vid)) {
217 return array();
218 }
219 // Otherwise delete the file and return an empty array.
220 if (field_file_delete($file)) {
221 return array();
222 }
223 }
224
225 // Cast to object since core functions use objects.
226 $file = (object)$file;
227
228 // Set permanent status on files if unset.
229 if (empty($file->status)) {
230 file_set_status($file, FILE_STATUS_PERMANENT);
231 }
232
233 // Let modules update their additional file properties too.
234 foreach (module_implements('file_update') as $module) {
235 $function = $module .'_file_update';
236 $function($file);
237 }
238 _field_file_cache($file); // update the cache, in case the file has changed
239
240 $file = (array)$file;
241 return $file;
242 }
243
244 /**
245 * Delete a field file and its database record.
246 *
247 * @param $path
248 * A file object.
249 * @param $force
250 * Force File Deletion ignoring reference counting.
251 * @return mixed
252 * TRUE for success, Array for reference count block, or FALSE in the event of an error.
253 */
254 function field_file_delete($file, $force = FALSE) {
255 $file = (object)$file;
256 // If any module returns a value from the reference hook, the
257 // file will not be deleted from Drupal, but file_delete will
258 // return a populated array that tests as TRUE.
259 if (!$force && $references = module_invoke_all('file_references', $file)) {
260 $references = array_filter($references); // only keep positive values
261 if (!empty($references)) {
262 return $references;
263 }
264 }
265
266 // Let other modules clean up on delete.
267 module_invoke_all('file_delete', $file);
268
269 // Make sure the file is deleted before removing its row from the
270 // database, so UIs can still find the file in the database.
271 if (file_delete($file->filepath)) {
272 db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
273 _field_file_cache(NULL, $file); // delete the file from the cache
274 return TRUE;
275 }
276 return FALSE;
277 }
278
279 /**
280 * Internal cache, in order to minimize database queries for loading files.
281 */
282 function _field_file_cache($file = NULL, $reset = FALSE) {
283 static $files = array();
284
285 // Reset internal cache.
286 if (is_object($reset)) { // file object, uncache just that one
287 unset($files[$reset->fid]);
288 unset($files[$reset->filepath]);
289 }
290 else if ($reset) { // TRUE, delete the whole cache
291 $files = array();
292 }
293
294 // Cache the file by both fid and filepath.
295 // Use non-copying objects to save memory.
296 if (!empty($file->fid)) {
297 $files[$file->fid] = $file;
298 $files[$file->filepath] = $file;
299 }
300 return $files;
301 }
302
303 /**
304 * A silent version of file.inc's file_check_directory().
305 *
306 * This function differs from file_check_directory in that it checks for
307 * files when doing the directory check and it does not use drupal_set_message()
308 * when creating directories. This function may be removed in Drupal 7.
309 *
310 * Check that the directory exists and is writable. Directories need to
311 * have execute permissions to be considered a directory by FTP servers, etc.
312 *
313 * @param $directory A string containing the name of a directory path.
314 * @param $mode A Boolean value to indicate if the directory should be created
315 * if it does not exist or made writable if it is read-only.
316 * @param $form_item An optional string containing the name of a form item that
317 * any errors will be attached to. This is useful for settings forms that
318 * require the user to specify a writable directory. If it can't be made to
319 * work, a form error will be set preventing them from saving the settings.
320 * @return FALSE when directory not found, or TRUE when directory exists.
321 */
322 function field_file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
323 $directory = rtrim($directory, '/\\');
324
325 // Error if the directory is a file.
326 if (is_file($directory)) {
327 watchdog('file system', 'The path %directory was checked as a directory, but it is a file.', array('%directory' => $directory), WATCHDOG_ERROR);
328 if ($form_item) {
329 form_set_error($form_item, t('The directory %directory is a file and cannot be overwritten.', array('%directory' => $directory)));
330 }
331 return FALSE;
332 }
333
334 // Create the directory if it is missing.
335 if (!is_dir($directory) && $mode & FILE_CREATE_DIRECTORY && !@mkdir($directory, 0775, TRUE)) {
336 watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
337 if ($form_item) {
338 form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
339 }
340 return FALSE;
341 }
342
343 // Check to see if the directory is writable.
344 if (!is_writable($directory) && $mode & FILE_MODIFY_PERMISSIONS && !@chmod($directory, 0775)) {
345 watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
346 if ($form_item) {
347 form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
348 }
349 return FALSE;
350 }
351
352 if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
353 $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
354 if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
355 fclose($fp);
356 chmod($directory .'/.htaccess', 0664);
357 }
358 else {
359 $repl = array('%directory' => $directory, '!htaccess' => nl2br(check_plain($htaccess_lines)));
360 form_set_error($form_item, t("Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines:<br /><code>!htaccess</code>", $repl));
361 watchdog('security', "Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines:<br /><code>!htaccess</code>", $repl, WATCHDOG_ERROR);
362 }
363 }
364
365 return TRUE;
366 }
367
368 /**
369 * Remove a possible leading file directory path from the given path.
370 */
371 function field_file_strip_path($path) {
372 $dirpath = file_directory_path();
373 $dirlen = drupal_strlen($dirpath);
374 if (drupal_substr($path, 0, $dirlen + 1) == $dirpath .'/') {
375 $path = drupal_substr($path, $dirlen + 1);
376 }
377 return $path;
378 }
379
380 /**
381 * Return a count of the references to a file by all modules.
382 */
383 function field_file_references($file) {
384 $references = (array) module_invoke_all('file_references', $file);
385 $reference_count = 0;
386 foreach ($references as $module => $count) {
387 $reference_count += $count;
388 }
389 return $reference_count;
390 }