/** * Moves a private managed file to the public directory. */ function _os_files_deprivatize_file($fid) { $file = file_load($fid); // Builds new public path. $dest_uri = str_replace('private://', 'public://', $file->uri); $dest_path = _os_files_deprivatize_get_dest_path($dest_uri); // Creates the destination folder if it doesn't exist. if (!is_dir($dest_path)) { // Creates the folder. drupal_mkdir($dest_path, NULL, TRUE); } $moved_file = @file_move($file, $dest_uri); if ($moved_file) { drush_log(dt('File @name moved successfully.', array('@name' => $file->filename)), 'success'); } else { drush_log(dt('Error moving file @name.', array('@name' => $file->filename)), 'error'); return FALSE; } $file->uri = $moved_file->uri; $file_moved = file_save($file); if (isset($file_moved->fid)) { drush_log(dt('[O] File @name updated successfully.', array('@name' => $file->filename)), 'success'); return TRUE; } else { drush_log(dt('[!] Error updating file @name.', array('@name' => $file->filename)), 'error'); return FALSE; } }
public function parse(ServicesContextInterface $context) { global $user; $destination = DATASET_FILE_STORAGE_DESTINATION; if (substr($destination, -1) != '/') { $destination .= '/'; } $file = new stdClass(); $file->uid = $user->uid; $file->status = 0; $file->filename = uniqid('push-api_'); $file->uri = file_destination($destination . $file->filename, FILE_EXISTS_RENAME); $file->filemime = 'text/csv'; if ( false === file_put_contents($file->uri,$context->getRequestBody()) ) { throw new IllegalArgumentException(t('Could not store received data on file system')); } drupal_chmod($file->uri); file_save($file); return array(PARAMETER_NAME_CONTENT => $file); }
function addPicture($FID, $moduleName) { $f = file_load($FID); $f->status = FILE_STATUS_PERMANENT; file_save($f); addUsage($f, $moduleName); // tells Drupal we're using the file }
public function unhandleField($entity_type, $field_type, $field_name, &$value) { if (!is_array($value)) { return; } if (!array_key_exists('url', $value)) { return; } if (!array_key_exists('original_path', $value)) { return; } if (!array_key_exists('uuid', $value)) { return; } if (!array_key_exists('uid', $value)) { return; } // Make sure a file doesn't already exist with that UUID. $entity = Entity::loadByUUID($value['uuid'], 'file'); if ($entity) { $definition = $entity->definition; } else { // Make sure a file doesn't already exist with that URI. $query = db_select('file_managed', 'f'); $query->addField('f', 'fid'); $query->condition('f.uri', $value['original_path']); $query->range(0, 1); $result = $query->execute()->fetch(); if ($result) { $entity = Entity::load($result->fid, 'file'); if ($entity) { $definition = $entity->definition; } } } // If we haven't found the file yet, upload it. if (!isset($definition)) { // Decode the contents of the file. $contents = file_get_contents($value['url']); if ($contents === false) { throw new FileHandlerException('There was an error fetching the contents of the file.'); } // Save the file. $file = file_save_data($contents, $value['original_path']); if (!$file || !$file->fid) { throw new FileHandlerException('There was an error saving the file to the database.'); } $file->uuid = $value['uuid']; $file->uid = $value['uid']; file_save($file); $definition = $file; } // Don't completely reset the entity. foreach ((array) $definition as $key => $val) { $this->unresolved_definition->{$key} = $val; } }
private static function addFile($imageFileId, $moduleName, $fieldName) { /* if our file is already in use, then we don't need to re-do this and increase the count */ $count = db_query('SELECT `count` FROM {file_usage} WHERE fid=:fid', array('fid' => $imageFileId))->fetchField(); $file = file_load($imageFileId); if (empty($count)) { $file->status = FILE_STATUS_PERMANENT; file_save($file); file_usage_add($file, $moduleName, $fieldName, $imageFileId); } return $file; }
/** * Called when this activity gets activated and run by the containing * ConductorWorkflow's controller. */ public function run() { $state = $this->getState(); $mobile = $state->getContext('sms_number'); // Mobile Commons sends the international code in its payload. Remove it. $mobile = substr($mobile, -10); // Get user by mobile number if it exists. Otherwise create it. $user = dosomething_user_get_user_by_mobile($mobile); if (!$user) { $user = dosomething_user_create_user_by_mobile($mobile); } // Initialize reportback values, defaulting to create a new reportback. $values = array('rbid' => 0); // Check for a previously submitted reportback to update instead. if ($rbid = dosomething_reportback_exists($this->nid, $user->uid)) { $values['rbid'] = $rbid; } // Get the MMS URL from the provided context. $pictureUrl = $state->getContext($this->mmsContext); // Get the location for where file should be saved to. $fileDest = dosomething_reportback_get_file_dest(basename($pictureUrl), $this->nid, $user->uid); // Download and save file to that location. $pictureContents = file_get_contents($pictureUrl); $file = file_save_data($pictureContents, $fileDest); // Save UID and permanent status. $file->uid = $user->uid; $file->status = FILE_STATUS_PERMANENT; file_save($file); // Get the fid to submit with the report back. $values['fid'] = $file->fid; // Get answers from context and set them to their appropriate properties. foreach ($this->propertyToContextMap as $property => $context) { $values[$property] = $state->getContext($context); } // Set nid and uid. $values['nid'] = $this->nid; $values['uid'] = $user->uid; // Create/update a report back submission. $rbid = dosomething_reportback_save($values); // Update user's profile if this is the first completed campaign. $updateArgs = array(); if (empty($_REQUEST['profile_first_completed_campaign_id']) && !empty($this->mobileCommonsCompletedCampaignId)) { $updateArgs['person[first_completed_campaign_id]'] = $this->mobileCommonsCompletedCampaignId; } // Opt the user out of the main campaign. if (!empty($this->optOutCampaignId)) { dosomething_sms_mobilecommons_opt_out($mobile, $this->optOutCampaignId); } // Opt user into a path to send the confirmation message. dosomething_sms_mobilecommons_opt_in($mobile, $this->optInPathId, $updateArgs); $state->setContext('ignore_no_response_error', TRUE); $state->markCompleted(); }
function az_commercial_settings_form_submit(&$form, $form_state) { $image_fid = $form_state['values']['main_background']; $image = file_load($image_fid); if (is_object($image)) { if ($image->status == 0) { $image->status = FILE_STATUS_PERMANENT; file_save($image); file_usage_add($image, 'az_gov', 'theme', 1); } } }
/** * implements ddaycare_background_validate */ function daycare_background_validate($element, &$form_state) { global $base_url; $validators = array('file_validate_is_image' => array()); $file = file_save_upload('background', $validators, "public://", FILE_EXISTS_REPLACE); if ($file) { // change file's status from temporary to permanent and update file database $file->status = FILE_STATUS_PERMANENT; file_save($file); $file_url = file_create_url($file->uri); $file_url = str_ireplace($base_url . '/', '', $file_url); // set to form $form_state['values']['bg_file'] = $file_url; } }
function puzzle_settings_form_submit(&$form, &$form_state) { $image_fid = $form_state['values']['background_image']; $image = file_load($image_fid); if (is_object($image)) { // Check to make sure that the file is set to be permanent. if ($image->status == 0) { // Update the status. $image->status = FILE_STATUS_PERMANENT; // Save the update. file_save($image); // Add a reference to prevent warnings. file_usage_add($image, 'puzzle', 'theme', 1); } } }
/** * Submit handler for system_theme_settings(). */ function sizzle_form_system_theme_settings_submit($form, &$form_state) { $values = $form_state['values']; // Save images. foreach ($values as $name => $value) { if (preg_match('/_image$/', $name)) { if (!empty($values[$name])) { $file = file_load($values[$name]); $file->status = FILE_STATUS_PERMANENT; file_save($file); file_usage_add($file, 'sizzle', 'theme', 1); variable_set($name, $file->fid); } } } }
function brafton_admin_form_submit($form, &$form_state) { //reset the error report if ($form_state['values']['brafton_clear_report']) { variable_set('brafton_e_log', ''); //variable_set('brafton_clear_report', 0); } //runs importer if archive is loaded //Handles background image for videos if ($form_state['values']['brafton_video_end_cta_background'] != '') { $file = file_load($form_state['values']['brafton_video_end_cta_background']); // Change status to permanent. $file->status = FILE_STATUS_PERMANENT; // Save. $newfile = file_save($file); $name = basename('brafton.module', '.module'); file_usage_add($newfile, $name, $name, $newfile->fid); variable_set('brafton_video_end_cta_background_url', $newfile->uri); variable_set('brafton_video_end_cta_background_id', $newfile->fid); } else { if (!$form_state['values']['brafton_video_end_cta_background']['fid']) { variable_set('brafton_video_end_cta_background_url', ''); variable_del('brafton_video_end_cta_background_id'); } } //Handles Button Image for videos if ($form_state['values']['brafton_video_end_cta_button_image'] != '') { $file = file_load($form_state['values']['brafton_video_end_cta_button_image']); // Change status to permanent. $file->status = FILE_STATUS_PERMANENT; // Save. $newfile = file_save($file); $name = basename('brafton.module', '.module'); file_usage_add($newfile, $name, $name, $newfile->fid); variable_set('brafton_video_end_cta_button_image_url', $newfile->uri); variable_set('brafton_video_end_cta_button_image_id', $newfile->fid); } else { if (!$form_state['values']['brafton_video_end_cta_button_image']['fid']) { variable_set('brafton_video_end_cta_button_image_url', ''); variable_del('brafton_video_end_cta_button_image_id'); } } //Ensure that the run manual imports $form_state['values']['brafton_clear_report'] = 0; }
function parallax_bg_region5_validate($element, &$form_state) { global $base_url; $validateFile = array('file_validate_is_image' => array()); $UploadedFile = file_save_upload('parallax_bg_region5_image', $validateFile, "public://", FILE_EXISTS_REPLACE); if ($form_state['values']['delete_parallax_bg_region5_image'] == TRUE) { file_unmanaged_delete($form_state['values']['parallax_bg_region5_preview']); $form_state['values']['parallax_bg_region5_preview'] = NULL; } if ($UploadedFile) { $UploadedFile->status = FILE_STATUS_PERMANENT; file_save($UploadedFile); $file_url = file_create_url($UploadedFile->uri); $file_url = str_ireplace($base_url, '', $file_url); // set to form $form_state['values']['parallax_bg_region5_preview'] = $file_url; } }
/** * Logs with an arbitrary level. * * @param string $level * @param string $message * @param array $context * * @return void */ function logger(string $level, string $message, array $context = []) : void { if (empty($context['file'])) { $context['file'] = 'qnd.log'; } $file = path('log', $context['file']); file_save($file, '[' . $level . '][' . date('r') . '] ' . $message . "\n\n", FILE_APPEND); }
/** * Helper function to write the CSS override file. * * If a file already existed, the old one is set to a temporary file so Drupal cleans it up. Returns the new file fid. * * @param string $content * * @return int */ function _platon_store_css_override_file($content) { global $user; // If a file already existed, set it to a temporary file so // Drupal cleans it up. if ($file = _platon_get_css_override_file()) { $file->status = 0; file_save($file); } if (empty($content)) { return 0; } // Create a new file. $filename = uniqid(md5($content)) . '_platon_override.css'; $uri = "public://{$filename}"; $f = fopen($uri, 'w'); // If the write succeeds, store it as a managed file. if (fwrite($f, $content)) { fclose($f); $file = (object) array('uri' => $uri, 'filename' => $filename, 'status' => FILE_STATUS_PERMANENT, 'uid' => $user->uid); file_save($file); // Return the file id. return $file->fid; } else { // The write didn't succeed. Return 0. return 0; } }
/** * Implement the save function for the entity. */ public function entity_save($entity) { file_save($entity); }
echo "<br />"; $msg = array(); function file_save($filename, $content, $flags = 0) { if (!($file = fopen($filename, 'w'))) { return FALSE; } $n = fwrite($file, $content); fclose($file); return $n ? $n : FALSE; } if (!file_exists("chat.php")) { file_save("chat.php", "<?php\n\$msg = " . var_export($msg, TRUE) . "\n?>"); } include "chat.php"; while (count($msg) >= 100) { array_shift($msg); } $msg2 = array_reverse($msg); echo "<div align='center' class='chat'><table width='92%'>"; include INCL_PATH . 'offset.php'; for ($i = 0; $i < count($msg2); ++$i) { echo "<tr><td class='header' align='left'>" . security::html_safe($msg2[$i]['pseudo']) . " [" . date("d/m/y H:i:s", $msg2[$i]['date'] - $offset) . "]</td></tr><tr><td class='lista' align='left'>" . format_shout($msg2[$i]['texte']) . "</td></tr>"; } echo "</table></div>"; file_save("chat.php", "<?php\n\$msg = " . var_export($msg, TRUE) . "\n?>"); print "<br />"; block_end(); print "<br />"; print "<div align='center'><a href='javascript: window.close()'>" . CLOSE . "</a></div>"; stdfoot(false);
<?php require_once 'includes/header.inc.php'; require_once 'includes/uploads.inc.php'; function form_file() { form_dump(array('file' => array('file', 'file'), 'submit' => array('submit', 'Save post')), 'enctype="multipart/form-data"'); } if (!isset($_POST['submit']) || empty($_POST['submit'])) { echo 'Please select the file to upload:<br />'; } else { if ($fname = file_save($_FILES['file'])) { echo 'file saved under <file><a href="/forum/uploads/' . $fname . '"></file>' . $fname . "</a><br />\n<br />\n"; } else { echo 'failed to save file'; } echo '<br />' . "\n"; } form_file(); echo '<br /><br />' . "\n"; require_once 'includes/footer.inc.php';
function site_bg_validate($element, &$form_state) { global $base_url; $validateFile = array('file_validate_is_image' => array()); $UploadedFile = file_save_upload('site_bg_image', $validateFile, "public://", FILE_EXISTS_REPLACE); if ($form_state['values']['delete_site_bg_image'] == TRUE) { // Delete layer file file_unmanaged_delete($form_state['values']['site_bg_preview']); $form_state['values']['site_bg_preview'] = NULL; } if ($UploadedFile) { // change file's status from temporary to permanent and update file database $UploadedFile->status = FILE_STATUS_PERMANENT; file_save($UploadedFile); $file_url = file_create_url($UploadedFile->uri); $file_url = str_ireplace($base_url, '', $file_url); // set to form $form_state['values']['site_bg_preview'] = $file_url; } }
/** * Validation callback for platon_form_system_theme_settings_alter(). */ function platon_form_system_theme_settings_alter_validate($form, &$form_state) { if (!empty($_FILES['files']['name']['platon_header_image_upload'])) { $file = file_save_upload('platon_header_image_upload', array('file_validate_is_image' => array(), 'file_validate_extensions' => array('png gif jpg jpeg')), 'public://'); if ($file) { $file->status = FILE_STATUS_PERMANENT; file_save($file); $form_state['storage']['header_file'] = $file; } else { form_set_error('platon_header_image_upload', t("Couldn't upload file.")); } } if (!empty($_FILES['files']['name']['platon_home_page_image_upload'])) { $file = file_save_upload('platon_home_page_image_upload', array('file_validate_is_image' => array(), 'file_validate_extensions' => array('png gif jpg jpeg')), 'public://'); if ($file) { $file->status = FILE_STATUS_PERMANENT; file_save($file); $form_state['storage']['home_file'] = $file; } else { form_set_error('platon_home_page_image_upload', t("Couldn't upload file.")); } } if (!empty($form_state['values']['platon_css_override_content'])) { if ($fid = _platon_store_css_override_file($form_state['values']['platon_css_override_content'])) { $form_state['storage']['css_fid'] = $fid; } else { form_set_error('platon_css_override_content', t("Could not save the CSS in a file. Perhaps the server has no write access. Check your public files folder permissions.")); } } }
/** * Save uploaded file. Call this from the form submit handler * @return * true if success, false if not * @param object $file_field[optional] * field name of the form * @param object $file_type[optional] * acceptable MIME type substring, e.g. 'image/' */ function saveFile($file_field = 'attachment', $file_type = '') { if (isset($_FILES[$file_field]) && !empty($_FILES[$file_field]['name'])) { // we only care about single file uploads here $uploadkey = ''; //the original name of the file is $_FILES[$file_field]['name'][$upload_key] if (is_array($_FILES[$file_field]['name'])) { foreach ($_FILES[$file_field]['name'] as $key => $val) { $uploadkey = $key; break; } } // valid attachment ? if ($file_type != '') { if (!eregi($file_type, $uploadkey == '' ? $_FILES[$file_field]['type'] : $_FILES[$file_field]['type'][$uploadkey])) { // invalid data mime type found return false; } } //01. we store the file into the file_managed table temporarily, and get the file object $file = file_save_upload($uploadkey, array(), NULL); //02. we get the file id in the file_managed table, and by using the file id together with the original filename, we create the new filename //also, we store the file id into the last_upload_id $filename = $file->fid . $_FILES[$file_field]['name'][$uploadkey]; $this->last_uploaded_id = $file->fid; //03. we save the file to be uploaded into the public file directory. $file = file_move($file, 'public://' . $filename, FILE_EXISTS_REPLACE); //04. set file the status to be permanently and save the file. $file->status = FILE_STATUS_PERMANENT; variable_set('file_id', $file->fid); file_save($file); //upload success; return true; } else { // invalid attachment data found return false; } }
/** * Saves the file as a temporary managed file. * * @param array $file_info * An array of information about the file. It should be in the following * format: * array( * 'uri' => 'Directory1/Filename1.jpg", * 'name' => 'Filename1.jpg', // this is an optional parameter * 'description' => 'File description 1', // this is an optional * // parameter * 'scheme' => 'private', // this is an optional parameter * ) * * @return object * Saved file object. */ protected static function saveFile($file_info) { $filename = !empty($file_info['name']) ? $file_info['name'] : drupal_basename($file_info['uri']); $scheme = !empty($file_info['scheme']) ? $file_info['scheme'] : 'public'; $file_temp = file_get_contents($file_info['uri']); // We add a random string in front of the file name to avoid race condition // in file upload with the same name in case we are running multiple // concurrent PHPUnit processes. $file_temp = file_save_data($file_temp, $scheme . '://' . Utils::getRandomString(20) . '_' . $filename, FILE_EXISTS_RENAME); if (!$file_temp) { return FALSE; } // Set file status to temporary otherwise there is validation error. $file_temp->status = 0; file_save($file_temp); return $file_temp; }
/** * ajax upload image */ function ajax_upload_image($form, &$form_state) { $file = file_save_upload('favicon_upload', array('file_validate_extensions' => array('png gif jpg jpeg')), "public://", $replace = FILE_EXISTS_REPLACE); if ($file) { $file->status = FILE_STATUS_PERMANENT; file_save($file); $form['favicon']['settings']['favicon_file']['favicon_preview'] = array('#prefix' => '<div id="favicon-preview"><div class="image-preview"><img src="' . file_create_url($file->uri) . '"/></div><div class="rm-favicon"><input type="button" value="Remove" class="rm-button"/></div>', '#suffix' => '</div></div>'); } else { drupal_set_message('No file uploaded.'); } return $form['favicon']['settings']['favicon_file']['favicon_preview']; }
continue; } $file = file_load($personal_photo['fid']); // Building the new path of the file. $destination = str_replace('private://', 'public://', $file->uri); // Create the destined folder if it's not exists. if (!is_dir(get_destination_dir($destination))) { // Creating the folder. drupal_mkdir($destination_folder, NULL, TRUE); } $moved_file = @file_move($file, $destination); if ($moved_file) { drush_log(dt('File @name moved successfully.', array('@name' => $file->filename)), 'success'); } $file->uri = $moved_file->uri; file_save($file); drush_log(dt('File @name updated successfully.', array('@name' => $file->filename)), 'success'); $flush_cache = TRUE; } // Flushing caches for rebuild filed data. if ($flush_cache) { drush_log(dt('Flushing the cache for update the files field data.'), 'warning'); drupal_flush_all_caches(); } /** * Returning the destined path for the file. * * @param $uri * The original URI of the file. * * @return
/** * Implements of hook_builder_content_saved_alter($delta, $content, $bid) */ function HOOK_builder_content_saved_alter($delta = '', $content, $bid) { switch ($delta) { case 'image': if (!empty($content['settings']['image'])) { $fid = $content['settings']['image']; if ($file = file_load($fid)) { if ($file->status !== FILE_STATUS_PERMANENT) { $file->status = FILE_STATUS_PERMANENT; file_save($file); file_usage_add($file, 'builder', 'builder', $bid); } } } break; } }
/** * Save settings data. */ function surreal_settings_submit(&$form, &$form_state) { $settings = array(); // Region parallax upload for ($i = 1; $i <= 6; $i++) { $fg = 'parallax_fg_region' . $i . '_image'; if ($file = file_load($form_state['values'][$fg])) { $file->status = FILE_STATUS_PERMANENT; file_save($file); file_usage_add($file, 'user', 'user', 1); variable_set($fg, $file->fid); } $bg = 'parallax_bg_region' . $i . '_image'; if ($file = file_load($form_state['values'][$bg])) { $file->status = FILE_STATUS_PERMANENT; file_save($file); file_usage_add($file, 'user', 'user', 1); variable_set($bg, $file->fid); } } // Update image field foreach ($form_state['input']['images'] as $image) { if (is_array($image)) { $image = $image['image']; if ($image['image_delete']) { // Delete banner file file_unmanaged_delete($image['image_path']); // Delete banner thumbnail file file_unmanaged_delete($image['image_thumb']); } else { // Update image $settings[] = $image; } } } // Check for a new uploaded file, and use that if available. if ($file = file_save_upload('image_upload')) { $file->status = FILE_STATUS_PERMANENT; if ($image = _surreal_save_image($file)) { // Put new image into settings $settings[] = $image; } } // Save settings surreal_set_banners($settings); }
/** * An adaptation of file_save_upload() that includes more verbose errors. * * @param string $source * A string specifying the filepath or URI of the uploaded file to save. * * @return stdClass * The saved file object. * * @throws \RestfulBadRequestException * @throws \RestfulServiceUnavailable * * @see file_save_upload() */ protected function fileSaveUpload($source) { static $upload_cache; $account = $this->getAccount(); $options = $this->getPluginKey('options'); $validators = $options['validators']; $destination = $options['scheme'] . "://"; $replace = $options['replace']; // Return cached objects without processing since the file will have // already been processed and the paths in _FILES will be invalid. if (isset($upload_cache[$source])) { return $upload_cache[$source]; } // Make sure there's an upload to process. if (empty($_FILES['files']['name'][$source])) { return NULL; } // Check for file upload errors and return FALSE if a lower level system // error occurred. For a complete list of errors: // See http://php.net/manual/features.file-upload.errors.php. switch ($_FILES['files']['error'][$source]) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $message = format_string('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $_FILES['files']['name'][$source], '%maxsize' => format_size(file_upload_max_size()))); throw new \RestfulBadRequestException($message); case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: $message = format_string('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$source])); throw new \RestfulBadRequestException($message); case UPLOAD_ERR_OK: // Final check that this is a valid upload, if it isn't, use the // default error handler. if (is_uploaded_file($_FILES['files']['tmp_name'][$source])) { break; } // Unknown error default: $message = format_string('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$source])); throw new \RestfulServiceUnavailable($message); } // Begin building file object. $file = new stdClass(); $file->uid = $account->uid; $file->status = 0; $file->filename = trim(drupal_basename($_FILES['files']['name'][$source]), '.'); $file->uri = $_FILES['files']['tmp_name'][$source]; $file->filemime = file_get_mimetype($file->filename); $file->filesize = $_FILES['files']['size'][$source]; $extensions = ''; if (isset($validators['file_validate_extensions'])) { if (isset($validators['file_validate_extensions'][0])) { // Build the list of non-munged extensions if the caller provided them. $extensions = $validators['file_validate_extensions'][0]; } else { // If 'file_validate_extensions' is set and the list is empty then the // caller wants to allow any extension. In this case we have to remove the // validator or else it will reject all extensions. unset($validators['file_validate_extensions']); } } else { // No validator was provided, so add one using the default list. // Build a default non-munged safe list for file_munge_filename(). $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'; $validators['file_validate_extensions'] = array(); $validators['file_validate_extensions'][0] = $extensions; } if (!empty($extensions)) { // Munge the filename to protect against possible malicious extension hiding // within an unknown file type (ie: filename.html.foo). $file->filename = file_munge_filename($file->filename, $extensions); } // Rename potentially executable files, to help prevent exploits (i.e. will // rename filename.php.foo and filename.php to filename.php.foo.txt and // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads' // evaluates to TRUE. if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) { $file->filemime = 'text/plain'; $file->uri .= '.txt'; $file->filename .= '.txt'; // The .txt extension may not be in the allowed list of extensions. We have // to add it here or else the file upload will fail. if (!empty($extensions)) { $validators['file_validate_extensions'][0] .= ' txt'; // Unlike file_save_upload() we don't need to let the user know that // for security reasons, your upload has been renamed, since RESTful // will return the file name in the response. } } // If the destination is not provided, use the temporary directory. if (empty($destination)) { $destination = 'temporary://'; } // Assert that the destination contains a valid stream. $destination_scheme = file_uri_scheme($destination); if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) { $message = format_string('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination)); throw new \RestfulServiceUnavailable($message); } $file->source = $source; // A URI may already have a trailing slash or look like "public://". if (substr($destination, -1) != '/') { $destination .= '/'; } $file->destination = file_destination($destination . $file->filename, $replace); // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and // there's an existing file so we need to bail. if ($file->destination === FALSE) { $message = format_string('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $source, '%directory' => $destination)); throw new \RestfulServiceUnavailable($message); } // Add in our check of the the file name length. $validators['file_validate_name_length'] = array(); // Call the validation functions specified by this function's caller. $errors = file_validate($file, $validators); // Check for errors. if (!empty($errors)) { $message = format_string('The specified file %name could not be uploaded.', array('%name' => $file->filename)); if (count($errors) > 1) { $message .= theme('item_list', array('items' => $errors)); } else { $message .= ' ' . array_pop($errors); } throw new \RestfulServiceUnavailable($message); } // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary // directory. This overcomes open_basedir restrictions for future file // operations. $file->uri = $file->destination; if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) { watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri)); $message = 'File upload error. Could not move uploaded file.'; throw new \RestfulServiceUnavailable($message); } // Set the permissions on the new file. drupal_chmod($file->uri); // If we are replacing an existing file re-use its database record. if ($replace == FILE_EXISTS_REPLACE) { $existing_files = file_load_multiple(array(), array('uri' => $file->uri)); if (count($existing_files)) { $existing = reset($existing_files); $file->fid = $existing->fid; } } // If we made it this far it's safe to record this file in the database. if ($file = file_save($file)) { // Add file to the cache. $upload_cache[$source] = $file; return $file; } // Something went wrong, so throw a general exception. throw new \RestfulServiceUnavailable('Unknown error has occurred.'); }
/** * Override. Handle the file upload process before creating an actual entity. * The file could be a straight replacement, and this is where we handle that. */ public function createEntity() { if ($this->checkEntityAccess('create', 'file', NULL) === FALSE && $this->checkGroupAccess('create') === FALSE) { // User does not have access to create entity. $params = array('@resource' => $this->getPluginKey('label')); throw new RestfulForbiddenException(format_string('You do not have access to create a new @resource resource.', $params)); } $destination = 'public://'; // do spaces/private file stuff here if (isset($this->request['private'])) { $destination = 'private://'; } if (isset($this->request['vsite'])) { $path = db_select('purl', 'p')->fields('p', array('value'))->condition('id', $this->request['vsite'])->execute()->fetchField(); $destination .= $path . '/files'; } $writable = file_prepare_directory($destination, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY); if ($entity = file_save_upload('upload', $this->getValidators(), $destination, FILE_EXISTS_REPLACE)) { if (isset($this->request['vsite'])) { og_group('node', $this->request['vsite'], array('entity_type' => 'file', 'entity' => $entity)); $entity = file_load($entity->fid); } if ($entity->status != FILE_STATUS_PERMANENT) { $entity->status = FILE_STATUS_PERMANENT; $entity = file_save($entity); } $wrapper = entity_metadata_wrapper($this->entityType, $entity); return array($this->viewEntity($wrapper->getIdentifier())); } elseif (isset($_FILES['files']) && $_FILES['files']['errors']['upload']) { throw new RestfulUnprocessableEntityException('Error uploading new file to server.'); } elseif (isset($this->request['embed']) && module_exists('media_internet')) { $provider = media_internet_get_provider($this->request['embed']); $provider->validate(); $validators = array(); // TODO: How do we populate this? $file = $provider->getFileObject(); if ($validators) { $file = $provider->getFileObject(); // Check for errors. @see media_add_upload_validate calls file_save_upload(). // this code is ripped from file_save_upload because we just want the validation part. // Call the validation functions specified by this function's caller. $errors = array_merge($errors, file_validate($file, $validators)); } if (!empty($errors)) { throw new MediaInternetValidationException(implode("\n", $errors)); } else { // Providers decide if they need to save locally or somewhere else. // This method returns a file object $entity = $provider->save(); if ($entity->status != FILE_STATUS_PERMANENT) { $entity->status = FILE_STATUS_PERMANENT; $entity = file_save($entity); } if ($this->request['vsite']) { og_group('node', $this->request['vsite'], array('entity_type' => 'file', 'entity' => $entity)); $entity = file_load($entity->fid); } $wrapper = entity_metadata_wrapper($this->entityType, $entity); return array($this->viewEntity($wrapper->getIdentifier())); } } else { if (!$writable) { throw new RestfulServerConfigurationException('Unable to create directory for target file.'); } else { // we failed for some other reason. What? throw new RestfulBadRequestException('Unable to process request.'); } } }
/** * Save settings data. */ function stability_settings_submit($form, &$form_state) { $settings = array(); if (isset($form_state['input']['sub_header_images'])) { foreach ($form_state['input']['sub_header_images'] as $image) { if (is_array($image)) { $image = $image['image']; if ($image['image_delete']) { $image['fid'] && ($file = file_load($image['fid'])) ? file_delete($file) : file_unmanaged_delete($image['image_path']); } else { $settings[] = $image; } } } } if ($file = file_save_upload('image_upload', array(), 'public://')) { $file->status = 1; file_save($file); $settings[] = array('fid' => $file->fid, 'image_path' => $file->uri); } variable_set(variable_get('theme_default', 'none') . '_sub_headers', $settings); }
function kurr_settings_form_submit(&$form, $form_state) { $testimonials_bg_image_fid = $form_state['values']['testimonials_bg']; $testimonials_bg_image = file_load($testimonials_bg_image_fid); if (is_object($testimonials_bg_image)) { // Check to make sure that the file is set to be permanent. if ($testimonials_bg_image->status == 0) { // Update the status. $testimonials_bg_image->status = FILE_STATUS_PERMANENT; // Save the update. file_save($testimonials_bg_image); // Add a reference to prevent warnings. file_usage_add($testimonials_bg_image, 'kurr', 'theme', 1); } } $quote_bg_image_fid = $form_state['values']['quote_bg']; $quote_bg_image = file_load($quote_bg_image_fid); if (is_object($quote_bg_image)) { // Check to make sure that the file is set to be permanent. if ($quote_bg_image->status == 0) { // Update the status. $quote_bg_image->status = FILE_STATUS_PERMANENT; // Save the update. file_save($quote_bg_image); // Add a reference to prevent warnings. file_usage_add($quote_bg_image, 'kurr', 'theme', 1); } } $social_bg_image_fid = $form_state['values']['social_bg']; $social_bg_image = file_load($social_bg_image_fid); if (is_object($social_bg_image)) { // Check to make sure that the file is set to be permanent. if ($social_bg_image->status == 0) { // Update the status. $social_bg_image->status = FILE_STATUS_PERMANENT; // Save the update. file_save($social_bg_image); // Add a reference to prevent warnings. file_usage_add($social_bg_image, 'kurr', 'theme', 1); } } }
$directoryString = $directory->getRealPath(); $tei = new TeiParser($directoryString); //Create file node first for XML files $file = new stdClass(); //XML file info $file->filename = $tei->filename; //Check if uri exists - if it does - get the info we need $fileArray = entity_load('file', FALSE, array('uri' => $tei->filePath)); if (empty($fileArray)) { $file->uri = $tei->filePath; $file->filemime = mime_content_type($tei->filePath); $file->filesize = filesize($tei->filePath); $file->timestamp = time(); $file->uid = '1'; //Save it $fileObj = file_save($file); } else { $fileObj = reset($fileArray); } //Drupal node instantiation $node = new stdClass(); // Create a new node object // this is where you set the node type, replace with whatever the machine name is for the node in question $node->type = "letterupload"; // Or page, or whatever content type you like node_object_prepare($node); // Set some default values $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled $node->uid = 1; // UID of the author of the node; or use $node->name