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