field_file.inc 14 KB
Newer Older
1
<?php
2
// $Id$
3

4 5 6 7
/**
 * @file
 * Common functionality for file handling CCK field modules.
 */
8 9

/**
10
 * Load a file from the database.
11 12 13 14 15
 *
 * @param $fid
 *   A numeric file id or string containing the file path.
 * @param $reset
 *   Whether to reset the internal file_load cache.
16 17
 * @return
 *   A file array.
18 19
 */
function field_file_load($fid, $reset = NULL) {
20 21 22
  // Reset internal cache.
  if (isset($reset)) {
    _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 33 34 35 36 37 38
  if (empty($files[$fid])) {
    if (is_numeric($fid)) {
      $file = db_fetch_object(db_query('SELECT f.* FROM {files} f WHERE f.fid = %d', $fid));
    }
    else {
      $file = db_fetch_object(db_query("SELECT f.* FROM {files} f WHERE f.filepath = '%s'", $fid));
    }
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) {
quicksketch's avatar
quicksketch committed
45
      $function = $module .'_file_load';
46
      $function($file);
47
    }
48

49
    // Cache the fully loaded file for later use.
50
    $files = _field_file_cache($file);
51
  }
52

53 54
  // Cast to an array for the field storage.
  // Contrary to fields, hook_file() and core file functions expect objects.
55
  return isset($files[$fid]) ? (array) $files[$fid] : FALSE;
56 57
}

58
/**
59 60 61 62
 * Save a file upload to a new location.
 * The source file is validated as a proper upload and handled as such. By
 * implementing hook_file($op = 'insert'), modules are able to act on the file
 * upload and to add their own properties to the file.
63
 *
64 65
 * The file will be added to the files table as a temporary file. Temporary
 * files are periodically cleaned. To make the file permanent file call
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
 * file_set_status() to change its status.
 *
 * @param $source
 *   A string specifying the name of the upload field to save.
 * @param $validators
 *   An optional, associative array of callback functions used to validate the
 *   file. The keys are function names and the values arrays of callback
 *   parameters which will be passed in after the user and file objects. The
 *   functions should return an array of error messages, an empty array
 *   indicates that the file passed validation. The functions will be called in
 *   the order specified.
 * @param $dest
 *   A string containing the directory $source should be copied to. If this is
 *   not provided or is not writable, the temporary directory will be used.
 * @return
 *   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) {
  if (!$file = file_save_upload($source, $validators, $dest, FILE_EXISTS_RENAME)) {
85 86
    return 0;
  }
87
  if (!@chmod($file->filepath, 0664)) {
88
    watchdog('filefield', 'Could not set permissions on destination file: %file', array('%file' => $file->filepath));
89
  }
drewish's avatar
drewish committed
90

91
  // Let modules add additional properties to the yet barebone file object.
92 93 94 95 96 97 98 99 100 101 102
  foreach (module_implements('file_insert') as $module) {
    $function =  $module .'_file_insert';
    $function($file);
  }
  _field_file_cache($file); // cache the file in order to minimize load queries
  return (array)$file;
}

/**
 * Save a file into a file node after running all the associated validators.
 *
103 104 105 106 107 108
 * This function is usually used to move a file from the temporary file
 * directory to a permanent location. It may be used by import scripts or other
 * modules that want to save an existing file into the database.
 *
 * @param $filepath
 *   The local file path of the file to be saved.
109 110 111 112 113 114 115 116 117 118
 * @param $validators
 *   An optional, associative array of callback functions used to validate the
 *   file. The keys are function names and the values arrays of callback
 *   parameters which will be passed in after the user and file objects. The
 *   functions should return an array of error messages, an empty array
 *   indicates that the file passed validation. The functions will be called in
 *   the order specified.
 * @param $dest
 *   A string containing the directory $source should be copied to. If this is
 *   not provided or is not writable, the temporary directory will be used.
119 120
 * @param $account
 *   The user account object that should associated with the uploaded file.
121 122 123
 * @return
 *   An array containing the file information, or 0 in the event of an error.
 */
124 125 126 127
function field_file_save_file($filepath, $validators = array(), $dest = FALSE, $account = NULL) {
  if (!isset($account)) {
    $account = $GLOBALS['user'];
  }
128 129 130 131 132 133

  // Add in our check of the the file name length.
  $validators['file_validate_name_length'] = array();

  // Begin building file object.
  $file = new stdClass();
134
  $file->uid = $account->uid;
135 136
  $file->filename = basename($filepath);
  $file->filepath = $filepath;
137
  $file->filemime = module_exists('mimedetect') ? mimedetect_mime($file) : file_get_mimetype($file->filename);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

  // Rename potentially executable files, to help prevent exploits.
  if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
    $file->filemime = 'text/plain';
    $file->filepath .= '.txt';
    $file->filename .= '.txt';
  }

  // If the destination is not provided, or is not writable, then use the
  // temporary directory.
  if (empty($dest) || file_check_path($dest) === FALSE) {
    $dest = file_directory_temp();
  }

  $file->source = 'field_file_save_file';
153
  $file->destination = file_destination(file_create_path($dest .'/'. $file->filename), FILE_EXISTS_RENAME);
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  $file->filesize = filesize($filepath);

  // Call the validation functions.
  $errors = array();
  foreach ($validators as $function => $args) {
    array_unshift($args, $file);
    $errors = array_merge($errors, call_user_func_array($function, $args));
  }

  // Check for validation errors.
  if (!empty($errors)) {
    $message = t('The selected file %name could not be saved.', array('%name' => $file->filename));
    if (count($errors) > 1) {
      $message .= '<ul><li>'. implode('</li><li>', $errors) .'</li></ul>';
    }
    else {
      $message .= ' '. array_pop($errors);
    }
    form_set_error($file->source, $message);
    return 0;
  }

  if (!file_copy($file, $file->destination, FILE_EXISTS_RENAME)) {
177 178
    form_set_error($file->source, t('File upload error. Could not move uploaded file.'));
    watchdog('file', 'Upload error. Could not move file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->destination));
179 180 181 182 183 184
    return 0;
  }

  // If we made it this far it's safe to record this file in the database.
  $file->status = FILE_STATUS_TEMPORARY;
  $file->timestamp = time();
185
  // Insert new record to the database.
186 187 188
  drupal_write_record('files', $file);

  // Let modules add additional properties to the yet barebone file object.
189 190 191
  foreach (module_implements('file_insert') as $module) {
    $function =  $module .'_file_insert';
    $function($file);
192
  }
193
  _field_file_cache($file); // cache the file in order to minimize load queries
194
  return (array)$file;
195
}
196 197

/**
quicksketch's avatar
quicksketch committed
198
 * Save a node file. Delete items if necessary and set new items as permanent.
199 200 201 202 203 204 205 206 207
 *
 * @param $node
 *    Node object this file is be associated with.
 * @param $file
 *    File to be inserted, passed by reference since fid should be attached.
 * @return array
 */
function field_file_save($node, &$file) {
  // If this item is marked for deletion.
208
  if (!empty($file['delete']) || !empty($file['_remove'])) {
209 210 211
    // If we're creating a new revision, return an empty array so CCK will
    // remove the item.
    if (!empty($node->old_vid)) {
212 213
      return array();
    }
214
    // Otherwise delete the file and return an empty array.
215 216 217 218 219
    if (field_file_delete($file)) {
      return array();
    }
  }

220 221 222
  // Cast to object since core functions use objects.
  $file = (object)$file;

223
  // Set permanent status on files if unset.
224
  if (empty($file->status)) {
225 226
    file_set_status($file, FILE_STATUS_PERMANENT);
  }
227 228

  // Let modules update their additional file properties too.
229 230 231
  foreach (module_implements('file_update') as $module) {
    $function =  $module .'_file_update';
    $function($file);
232
  }
233 234
  _field_file_cache($file); // update the cache, in case the file has changed

235
  $file = (array)$file;
236 237 238 239 240 241
  return $file;
}

/**
 * Delete a field file and its database record.
 *
242
 * @param $path
243 244 245
 *   A file object.
 * @param $force
 *   Force File Deletion ignoring reference counting.
246
 * @return mixed
247 248 249 250 251 252 253
 *   TRUE for success, Array for reference count block, or FALSE in the event of an error.
 */
function field_file_delete($file, $force = FALSE) {
  $file = (object)$file;
  // If any module returns a value from the reference hook, the
  // file will not be deleted from Drupal, but file_delete will
  // return a populated array that tests as TRUE.
254
  if (!$force && $references = module_invoke_all('file_references', $file)) {
255 256 257 258
    $references = array_filter($references); // only keep positive values
    if (!empty($references)) {
      return $references;
    }
259 260 261
  }

  // Let other modules clean up on delete.
262
  module_invoke_all('file_delete', $file);
263

264
  // Make sure the file is deleted before removing its row from the
265 266 267
  // database, so UIs can still find the file in the database.
  if (file_delete($file->filepath)) {
    db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
268
    _field_file_cache(NULL, $file); // delete the file from the cache
269 270 271 272 273
    return TRUE;
  }
  return FALSE;
}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
/**
 * Internal cache, in order to minimize database queries for loading files.
 */
function _field_file_cache($file = NULL, $reset = FALSE) {
  static $files = array();

  // Reset internal cache.
  if (is_object($reset)) { // file object, uncache just that one
    unset($files[$reset->fid]);
    unset($files[$reset->filepath]);
  }
  else if ($reset) { // TRUE, delete the whole cache
    $files = array();
  }

  // Cache the file by both fid and filepath.
  // Use non-copying objects to save memory.
drewish's avatar
drewish committed
291
  if (!empty($file->fid)) {
292 293 294 295 296 297
    $files[$file->fid] = $file;
    $files[$file->filepath] = $file;
  }
  return $files;
}

298
/**
quicksketch's avatar
quicksketch committed
299 300 301 302 303
 * A silent version of file.inc's file_check_directory().
 *
 * This function differs from file_check_directory in that it checks for
 * files when doing the directory check and it does not use drupal_set_message()
 * when creating directories. This function may be removed in Drupal 7.
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
 *
 * Check that the directory exists and is writable. Directories need to
 * have execute permissions to be considered a directory by FTP servers, etc.
 *
 * @param $directory A string containing the name of a directory path.
 * @param $mode A Boolean value to indicate if the directory should be created
 *   if it does not exist or made writable if it is read-only.
 * @param $form_item An optional string containing the name of a form item that
 *   any errors will be attached to. This is useful for settings forms that
 *   require the user to specify a writable directory. If it can't be made to
 *   work, a form error will be set preventing them from saving the settings.
 * @return FALSE when directory not found, or TRUE when directory exists.
 */
function field_file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
  $directory = rtrim($directory, '/\\');

quicksketch's avatar
quicksketch committed
320
  // Error if the directory is a file.
321
  if (is_file($directory)) {
quicksketch's avatar
quicksketch committed
322 323 324 325
    watchdog('file system', 'The path %directory was checked as a directory, but it is a file.',  array('%directory' => $directory), WATCHDOG_ERROR);
    if ($form_item) {
      form_set_error($form_item, t('The directory %directory is a file and cannot be overwritten.', array('%directory' => $directory)));
    }
326 327 328
    return FALSE;
  }

quicksketch's avatar
quicksketch committed
329 330
  // Create the directory if it is missing.
  if (!is_dir($directory) && $mode & FILE_CREATE_DIRECTORY && !@mkdir($directory, 0775, TRUE)) {
331
    watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
quicksketch's avatar
quicksketch committed
332 333 334
    if ($form_item) {
      form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
    }
335
    return FALSE;
336 337 338
  }

  // Check to see if the directory is writable.
339 340
  if (!is_writable($directory) && $mode & FILE_MODIFY_PERMISSIONS && !@chmod($directory, 0775)) {
    watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
quicksketch's avatar
quicksketch committed
341 342 343
    if ($form_item) {
      form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
    }
344
    return FALSE;
345 346 347 348 349 350 351 352 353
  }

  if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
    $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
    if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
      fclose($fp);
      chmod($directory .'/.htaccess', 0664);
    }
    else {
354 355
      $repl = array('%directory' => $directory, '!htaccess' => nl2br(check_plain($htaccess_lines)));
      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));
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);
357 358 359 360 361 362
    }
  }

  return TRUE;
}

363 364 365 366 367
/**
 * Remove a possible leading file directory path from the given path.
 */
function field_file_strip_path($path) {
  $dirpath = file_directory_path();
368 369 370
  $dirlen = drupal_strlen($dirpath);
  if (drupal_substr($path, 0, $dirlen + 1) == $dirpath .'/') {
    $path = drupal_substr($path, $dirlen + 1);
371 372 373
  }
  return $path;
}
374 375

/**
376
 * Return a count of the references to a file by all modules.
377
 */
378 379 380 381 382
function field_file_references($file) {
  $references = (array) module_invoke_all('file_references', $file);
  $reference_count = 0;
  foreach ($references as $module => $count) {
    $reference_count += $count;
383
  }
384
  return $reference_count;
385
}