WP Offload Media Lite - return s3 image url - wordpress

I created a page that will allow admins to upload logos. These logos will be saved in the media folder as well as in the S3 bucket.
I am using the WP Offload Media Lite to upload any saved files/images in wordpress into my S3 bucket. I have that part working well and everything is saving properly but what i realized that i need the S3 url image to be saved in the metadata of the image.
How can i return the created the image url saved in S3 or have the url saved in metadata for the image?
This is my current code for uploading file/images. This uploads to the media library which also uploads to S3:
$file = array(
'name' => $_FILES["profile_logo"]["name"],
'type' => $_FILES["profile_logo"]["type"],
'tmp_name' => $_FILES["profile_logo"]["tmp_name"],
'size' => $_FILES["profile_logo"]["size"]
);
$upload = wp_handle_upload($file, array('test_form' => false));
if(!empty($upload['error'])){
echo "some error";
return false;
}
$check_page_exist = get_page_by_title($user->slug, OBJECT, 'page');
$attachment_id = wp_insert_attachment(array(
'guid' => $upload['url'],
'post_mime_type' => $upload['type'],
'post_title' => basename($upload['file']),
'post_content' => '',
'post_status' => 'inherit'
), $upload['file'], $check_page_exist->ID);
if(is_wp_error($attachment_id) || !$attachment_id){
wp_die('Upload error.');
}
wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $upload['file']));

Related

How to get filename after upload Drupal 8?

I am building a form and where te user can upload a file. Since I am using Drupal I am using the managed_file. The file is being uploaded but I cannot seem to get the filename out of the form... This is my code
Buildform:
$form['formfile'] = array(
'#type' => 'managed_file',
'#name' => 'formfile',
'#title' => t('File'),
'#upload_validators' => $validators,
'#upload_location' => 'public://trainingrequests/',
);
Submit
drupal_set_message($form_state->getValue('formfile'));
I have literally tried everything.
You first need to get the entity ID of the File entity, then load the entity:
$formfile = $form_state->getValue('formfile');
if ($formfile) {
$oNewFile = File::load(reset($formfile));
$oNewFile->setPermanent();
drupal_set_message('Filename: ' . $oNewFile->getFilename());
}
You can browse the source code of the File entity in your file system: core/modules/file/src/Entity/File.php

drupal 7 file_save_upload returning false

I have a custom form, with a field for the user to upload an image file (their logo). In the form validate hook, I've implemented file_save_upload, which is continually returning false. I can see that the file is in fact being saved in the correct location on upload, so why isn't file_save_upload working?
The form field:
$form['company_logo'] = array(
'#type' => 'managed_file',
'#title' => t('Company Logo'),
'#description' => t('Allowed extensions: gif png jpg jpeg'),
'#upload_location' => 'public://uploads/',
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
// Pass the maximum file size in bytes
//'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
),
);
The validation hook:
$file = file_save_upload( 'company_logo' , array(), 'public://uploads/', FILE_EXISTS_RENAME);
if (!$file) {
form_set_error('company_logo', t('Unable to access file or file is missing.'));
}
The managed file element handles moving the uploaded file for you, so there's no need to call file_save_upload() manually.
You're getting a NULL return because of these lines in file_save_upload():
// Make sure there's an upload to process.
if (empty($_FILES['files']['name'][$source])) {
return NULL;
}
As the file's already been processed there's nothing for the function to do.
You can persist the file entry by adding a submit handler to the form and using code similar to
$file = file_load($form_state['values']['company_logo']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

How do I properly add FILE field in drupal form via theme-setting.php?

I am building a theme with ability to upload custom background images but now I am stuck at a point.
How do I properly add FILE field in drupal form via theme-setting.php and after that how can I get public url to this file in my template files??
In your theme_form_system_theme_settings_alter hook you need to add the following form element:
$form['theme_settings']['background_file'] = array(
'#type' => 'managed_file',
'#title' => t('Background'),
'#required' => FALSE,
'#upload_location' => file_default_scheme() . '://theme/backgrounds/',
'#default_value' => theme_get_setting('background_file'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),
);
This will save the file id to your theme settigns variable 'background_file', notice that i set the upload location to theme/backgrounds, this will be inside your files folder.
Finally you'll get the complete URL to the file with file_create_url:
$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
Edit:
In your template.php you can add in the theme_preprocess_page hook the variable so all the tpl's can access it, this is how:
function theme_preprocess_page(&$variables, $hook) {
$fid = theme_get_setting('background_file');
$variables['background_url'] = file_create_url(file_load($fid)->uri);
}
Hope this helps! :D

Drupal 7 retain file upload

I have a file upload form
how can I retain this file when there are other validation errors so that the user doesn't have to upload the file again?
I tried this in my validation function but it doesn't work:
function mymodule_someform_validate($form, &$form_state) {
$form_state["values"]["some_field"] = some_value;
}
the $form_state["values"] variable is not available in my form definition function - mymodule_someform($form, &$form_state)
Any ideas?
Just use the managed_file type, it'll do it for you:
$form['my_file_field'] = array(
'#type' => 'managed_file',
'#title' => 'File',
'#upload_location' => 'public://my-folder/'
);
And then in your submit handler:
// Load the file via file.fid.
$file = file_load($form_state['values']['my_file_field']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);
If the validation fails and the user leaves the form, the file will be automatically deleted a few hours later (as all files in the file_managed table without FILE_STATUS_PERMANENT are). If the validation doesn't fail, the submit handler will be run and the file will be marked as permanent in the system.
Admin form example for others who may be looking:
function example_admin_form(){
$form = array();
$form['image'] = array(
'#type' => 'managed_file',
'#name' => 'image',
'#title' => t('upload your image here!'),
'#default_value' => variable_get('image', ''),
'#description' => t("Here you can upload an image"),
'#progress_indicator' => 'bar',
'#upload_location' => 'public://my_images/'
);
// Add your submit function to the #submit array
$form['#submit'][] = 'example_admin_form_submit';
return system_settings_form($form);
}
function example_admin_form_submit($form, &$form_state){
// Load the file
$file = file_load($form_state['values']['image']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);
}

Drupal user_hook in custom module

Modifying download_count module to include information about users who downloaded files. Want to show this info on users' profile pages.
Here's the code:
function download_count_user($op, &$edit, &$account, $caterory = NULL) {
if ($op == 'view')
{
$result = db_query("SELECT filename FROM file_downloads_users WHERE user_id = %d", $account->uid);
while ($file_array = db_fetch_object($result)) {
$file_str .= $file->filename . '<br/>';
}
$items['downloads'] = array(
'title' => t('Files'),
'value' => $file_str,
'class' => 'member'
);
return array(t('Downloads')=>$items);
}
}
Doesn't give me any errors but doesn't show anything on My Account page either.
You don't want to modify a module. Drupal is built very very carefully to avoid having to hack core or contrib. Unless of course you are contributing a patch back.
The right way is to build your own custom module to do this (that would require the user downloads module) and implement the hook almost exactly what you're doing here.
The function is getting run (module enabled, var_dump ing or krumo'ing causes output?, cache cleared)
The way you are keying your variables is for Drupal 5.x and below. In D6, you add to $account->content. Which version of drupal are you using?
Check out user_user() (in user.module):
$account->content['user_picture'] = array(
'#value' => theme('user_picture', $account),
'#weight' => -10,
);
$account->content['summary']['file_downloads'] = array(
'#type' => 'user_profile_item',
'#title' => t('File Downloads'),
'#value' => $file_str,
'#weight' => 1
);

Resources