Fix lots of E_NOTICE errors.
[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();
25 }
26 $files = _field_file_cache();
27
28 // Serve file from internal cache if available.
29 if (empty($files[$fid])) {
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 array();
39 }
40
41 foreach (module_implements('file') as $module) {
42 $function = $module .'_file';
43 $function('load', $file);
44 }
45
46 // Cache the fully loaded file for later reusability.
47 $files = _field_file_cache($file);
48 }
49
50 // Cast to array for field. hook_file() expects objects as well as
51 // core file functions.
52 return (array)$files[$fid];
53 }
54
55 /**
56 * Save a file upload to a new location. The source file is validated as a
57 * proper upload and handled as such. By implementing hook_file($op = 'insert'),
58 * modules are able to act on the file upload and to add their own properties
59 * to the file.
60 *
61 * The file will be added to the files table as a temporary file. Temporary files
62 * are periodically cleaned. To make the file permanent file call
63 * file_set_status() to change its status.
64 *
65 * @param $source
66 * A string specifying the name of the upload field to save.
67 * @param $validators
68 * An optional, associative array of callback functions used to validate the
69 * file. The keys are function names and the values arrays of callback
70 * parameters which will be passed in after the user and file objects. The
71 * functions should return an array of error messages, an empty array
72 * indicates that the file passed validation. The functions will be called in
73 * the order specified.
74 * @param $dest
75 * A string containing the directory $source should be copied to. If this is
76 * not provided or is not writable, the temporary directory will be used.
77 * @param $replace
78 * A boolean indicating whether an existing file of the same name in the
79 * destination directory should overwritten. A false value will generate a
80 * new, unique filename in the destination directory.
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, $replace = FILE_EXISTS_RENAME) {
85 if (!$file = file_save_upload($source, $validators, $dest, $replace)) {
86 return 0;
87 }
88 // Let modules add additional properties to the yet barebone file object.
89 foreach (module_implements('file') as $module) {
90 $function = $module .'_file';
91 $function('insert', $file);
92 }
93 _field_file_cache($file); // cache the file in order to minimize load queries
94 return (array)$file;
95 }
96
97 /**
98 * Update an field item file. Delete marked items if neccessary and set new items as permamant.
99 *
100 * @param $node
101 * Node object this file is be associated with.
102 * @param $file
103 * File to be inserted, passed by reference since fid should be attached.
104 * @return array
105 */
106 function field_file_save($node, &$file) {
107 // If this item is marked for deletion.
108 if (!empty($file['delete'])) {
109 // If we're creating a new revision, return an empty array so CCK will
110 // remove the item.
111 if (!empty($node->old_vid)) {
112 return array();
113 }
114 // Otherwise delete the file and return an empty array.
115 if (field_file_delete($file)) {
116 return array();
117 }
118 }
119
120 // Cast to object since core functions use objects.
121 $file = (object)$file;
122
123 // Set permanent status on files if unset.
124 if (empty($file->status)) {
125 file_set_status($file, FILE_STATUS_PERMANENT);
126 }
127
128 // Let modules update their additional file properties too.
129 foreach (module_implements('file') as $module) {
130 $function = $module .'_file';
131 $function('update', $file);
132 }
133 _field_file_cache($file); // update the cache, in case the file has changed
134
135 $file = (array)$file;
136 return $file;
137 }
138
139 /**
140 * Delete a field file and its database record.
141 *
142 * @param $path
143 * A file object.
144 * @param $force
145 * Force File Deletion ignoring reference counting.
146 * @return mixed
147 * TRUE for success, Array for reference count block, or FALSE in the event of an error.
148 */
149 function field_file_delete($file, $force = FALSE) {
150 $file = (object)$file;
151 // If any module returns a value from the reference hook, the
152 // file will not be deleted from Drupal, but file_delete will
153 // return a populated array that tests as TRUE.
154 if (!$force && $references = module_invoke_all('file', 'references', $file)) {
155 return $references;
156 }
157
158 // Let other modules clean up on delete.
159 module_invoke_all('file', 'delete', $file);
160
161 // Make sure the file is deleted before removing its row from the
162 // database, so UIs can still find the file in the database.
163 if (file_delete($file->filepath)) {
164 db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
165 _field_file_cache(NULL, $file); // delete the file from the cache
166 return TRUE;
167 }
168 return FALSE;
169 }
170
171 /**
172 * Internal cache, in order to minimize database queries for loading files.
173 */
174 function _field_file_cache($file = NULL, $reset = FALSE) {
175 static $files = array();
176
177 // Reset internal cache.
178 if (is_object($reset)) { // file object, uncache just that one
179 unset($files[$reset->fid]);
180 unset($files[$reset->filepath]);
181 }
182 else if ($reset) { // TRUE, delete the whole cache
183 $files = array();
184 }
185
186 // Cache the file by both fid and filepath.
187 // Use non-copying objects to save memory.
188 if (isset($file)) {
189 $files[$file->fid] = $file;
190 $files[$file->filepath] = $file;
191 }
192 return $files;
193 }
194
195 /**
196 * A silent version of file.inc:file_check_directory it's only talkative
197 * on errors.
198 *
199 * Check that the directory exists and is writable. Directories need to
200 * have execute permissions to be considered a directory by FTP servers, etc.
201 *
202 * @param $directory A string containing the name of a directory path.
203 * @param $mode A Boolean value to indicate if the directory should be created
204 * if it does not exist or made writable if it is read-only.
205 * @param $form_item An optional string containing the name of a form item that
206 * any errors will be attached to. This is useful for settings forms that
207 * require the user to specify a writable directory. If it can't be made to
208 * work, a form error will be set preventing them from saving the settings.
209 * @return FALSE when directory not found, or TRUE when directory exists.
210 */
211 function field_file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
212 $directory = rtrim($directory, '/\\');
213
214 // Check if the directory exists.
215 if (!is_dir($directory)) {
216 if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory)) {
217 @chmod($directory, 0775); // Necessary for non-webserver users.
218 }
219 else {
220 if ($form_item) {
221 form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
222 }
223 watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
224 return FALSE;
225 }
226 }
227
228 // Check to see if the directory is writable.
229 if (!is_writable($directory)) {
230 if (($mode & FILE_MODIFY_PERMISSIONS) && !@chmod($directory, 0775)) {
231 if ($form_item) {
232 form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
233 }
234 watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
235 return FALSE;
236 }
237 }
238
239 if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
240 $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
241 if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
242 fclose($fp);
243 chmod($directory .'/.htaccess', 0664);
244 }
245 else {
246 $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>";
247 $repl = array('%directory' => $directory, '!htaccess' => '<br />'. nl2br(check_plain($htaccess_lines)));
248 form_set_error($form_item, t($message, $repl));
249 watchdog('security', $message, $repl, WATCHDOG_ERROR);
250 }
251 }
252
253 return TRUE;
254 }
255
256 /**
257 * Remove a possible leading file directory path from the given path.
258 */
259 function field_file_strip_path($path) {
260 $dirpath = file_directory_path();
261 $dirlen = drupal_strlen($dirpath);
262 if (drupal_substr($path, 0, $dirlen + 1) == $dirpath .'/') {
263 $path = drupal_substr($path, $dirlen + 1);
264 }
265 return $path;
266 }