Skip to content

Instantly share code, notes, and snippets.

@antonmaju
Last active January 2, 2023 21:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save antonmaju/eccf799602e95e386670 to your computer and use it in GitHub Desktop.
Save antonmaju/eccf799602e95e386670 to your computer and use it in GitHub Desktop.
Gravity form filter to handle file upload integration with WP Offload S3 Lite plugin. Adapted from https://wordpress.org/support/topic/support-for-gravity-forms-uploads.
<?php
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
require_once WP_CONTENT_DIR.'/plugins/amazon-web-services/vendor/aws/aws-autoloader.php';
use \Aws\S3\S3Client;
add_filter('gform_upload_path', 'gform_change_upload_path', 10, 2);
add_action('gform_after_submission', 'gform_submit_to_s3', 10, 2);
//change gravity form upload path to point to S3
function gform_change_upload_path($path_info, $form_id)
{
$bucket_info = get_option('tantan_wordpress_s3');
$as3cf_is_active = is_plugin_active('amazon-s3-and-cloudfront/wordpress-s3.php');
if(!empty($bucket_info['bucket']) && $as3cf_is_active )
{
$gform_link = explode('wp-content/uploads/', $path_info["url"]);
$domain = $bucket_info['bucket'];
if($bucket_info['domain'] == 'subdomain')
{
$domain = $bucket_info['bucket'].'.s3.amazonaws.com';
}
else if($bucket_info['domain'] == 'path')
{
$domain = 's3.amazonaws.com/'.$bucket_info['bucket'];
}
else if($bucket_info['domain'] == 'cloudfront')
{
$domain = $bucket_info['cloudfront'];
}
$protocol = ($bucket_info['ssl'] !== 'request' ? $bucket_info['ssl'] : 'http'.(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 's' : ''));
$path_info["url"] = (strpos($domain, 'http') === false ? $protocol : '')."://".$domain.'/'.$gform_link[1];
}
return $path_info;
}
//submit file to s3
function gform_submit_to_s3($entry, $form)
{
$bucket_info = get_option('tantan_wordpress_s3');
$as3cf_is_active = is_plugin_active('amazon-s3-and-cloudfront/wordpress-s3.php');
if(!empty($form['fields']) && !empty($bucket_info['bucket']) && $as3cf_is_active )
{
$s3Client =S3Client::factory(array(
'key' => AWS_ACCESS_KEY_ID,
'secret' => AWS_SECRET_ACCESS_KEY
));
foreach ($form['fields'] as $field)
{
if($field->type == 'fileupload' && !empty($entry[$field->id]))
{
$gform_link = explode('/gravity_forms/', $entry[$field->id]);
$upload_dir = wp_upload_dir();
$file_url = $upload_dir['baseurl'].'/gravity_forms/'.$gform_link[1];
$url_parts = parse_url( $file_url );
$full_path = $_SERVER['DOCUMENT_ROOT'] . $url_parts['path'];
$s3Client->putObject(array(
'Bucket' => $bucket_info['bucket'],
'Key' => 'gravity_forms/'.$gform_link[1],
'SourceFile' => $full_path,
'ACL' => 'public-read',
));
}
}
}
}
?>
@ruccola
Copy link

ruccola commented Oct 12, 2018

Sorry, but where do I put this file? Can I put all logic in functions.php?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment