Oops. Er. Of course we want to return an array, not an object. Ehem.
[project/filefield.git] / field_file.inc
1 <?php
2 // $Id$
3
4 /**
5 * Load a file object from the database.
6 *
7 * @param $fid
8 * A numeric file id or string containing the file path.
9 *
10 * @param $reset
11 * Whether to reset the internal file_load cache.
12 */
13 function field_file_load($fid, $reset = NULL) {
14 static $files = array();
15
16 if (empty($fid)) {
17 return FALSE;
18 }
19
20 // Reset internal cache.
21 if ($reset) {
22 $files = array();
23 }
24
25 // Serve file from internal cache if available.
26 if (!empty($fid) && !empty($files[$fid])) {
27 return (array)$files[$fid];
28 }
29
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 FALSE;
39 }
40
41 foreach(module_implements('file') as $module) {
42 $function = $module .'_file';
43 $function('load', $file);
44 }
45
46 // Cache the fully loaded value by both fid and filepath.
47 // use non-copying objects to save memory.
48 $files[$fid] = $file;
49 $files[$file->filepath] = $file;
50
51 // Cast to array for field. hook_file() expects objects as well as
52 // core file functions.
53 return (array)$file;
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 file properties, and save initial values
90 // to the database if they like to do so.
91 foreach(module_implements('file') as $module) {
92 $function = $module .'_file';
93 $function('insert', $file);
94 }
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 // Set permanent status on files if unset.
122 if (empty($file['status'])) {
123 // Cast to object since core functions us objects.
124 $file = (object)$file;
125 file_set_status($file, FILE_STATUS_PERMANENT);
126 $file = (array)$file;
127 }
128
129 // Let modules update their additional file properties too.
130 foreach(module_implements('file') as $module) {
131 $function = $module .'_file';
132 $function('update', $file);
133 }
134 return $file;
135 }
136
137 /**
138 * Delete a field file and its database record.
139 *
140 * @param $path
141 * A file object.
142 * @param $force
143 * Force File Deletion ignoring reference counting.
144 * @return mixed
145 * TRUE for success, Array for reference count block, or FALSE in the event of an error.
146 */
147 function field_file_delete($file, $force = FALSE) {
148 $file = (object)$file;
149 // If any module returns a value from the reference hook, the
150 // file will not be deleted from Drupal, but file_delete will
151 // return a populated array that tests as TRUE.
152 if (!$force && $references = module_invoke_all('file', 'references', $file)) {
153 return $references;
154 }
155
156 // Let other modules clean up on delete.
157 module_invoke_all('file', 'delete', $file, $field);
158
159 // Make sure the file is deleted before removing its row from the
160 // database, so UIs can still find the file in the database.
161 if (file_delete($file->filepath)) {
162 db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
163 return TRUE;
164 }
165 return FALSE;
166 }
167
168 /**
169 * A silent version of file.inc:file_check_directory it's only talkative
170 * on errors.
171 *
172 * Check that the directory exists and is writable. Directories need to
173 * have execute permissions to be considered a directory by FTP servers, etc.
174 *
175 * @param $directory A string containing the name of a directory path.
176 * @param $mode A Boolean value to indicate if the directory should be created
177 * if it does not exist or made writable if it is read-only.
178 * @param $form_item An optional string containing the name of a form item that
179 * any errors will be attached to. This is useful for settings forms that
180 * require the user to specify a writable directory. If it can't be made to
181 * work, a form error will be set preventing them from saving the settings.
182 * @return FALSE when directory not found, or TRUE when directory exists.
183 */
184 function field_file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
185 $directory = rtrim($directory, '/\\');
186
187 // Check if the directory exists.
188 if (!is_dir($directory)) {
189 if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory)) {
190 @chmod($directory, 0775); // Necessary for non-webserver users.
191 }
192 else {
193 if ($form_item) {
194 form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
195 }
196 watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
197 return FALSE;
198 }
199 }
200
201 // Check to see if the directory is writable.
202 if (!is_writable($directory)) {
203 if (($mode & FILE_MODIFY_PERMISSIONS) && !@chmod($directory, 0775)) {
204 if ($form_item) {
205 form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
206 }
207 watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
208 return FALSE;
209 }
210 }
211
212 if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
213 $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
214 if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
215 fclose($fp);
216 chmod($directory .'/.htaccess', 0664);
217 }
218 else {
219 $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>";
220 $repl = array('%directory' => $directory, '!htaccess' => '<br />'. nl2br(check_plain($htaccess_lines)));
221 form_set_error($form_item, t($message, $repl));
222 watchdog('security', $message, $repl, WATCHDOG_ERROR);
223 }
224 }
225
226 return TRUE;
227 }
228
229 /**
230 * Remove a possible leading file directory path from the given path.
231 */
232 function field_file_strip_path($path) {
233 $dirpath = file_directory_path();
234 $dirlen = strlen($dirpath);
235 if (substr($path, 0, $dirlen + 1) == $dirpath .'/') {
236 $path = substr($path, $dirlen + 1);
237 }
238 return $path;
239 }