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