How to upload an auto-generated URL Screenshot in a User Submitted Post?

Question

I have a form that allows users to submit a post, and one of the fields is a URL. I would like the form to submit that post, and also upload a screenshot of the URL that is generated by the code. I have tried the following, but it is not working and I’m not sure where I am going wrong. Please refer to the section commented with “// Add Featured Image to Post ” onwards. I attached the full code just in case something else is going wrong. And just to assure people, when I remove that code, the form submits the rest of the user fields properly.

Could someone help?

class PG_Custom_Form_Mailer {

public $processed = false;
public $error = true;
public $message = 'The form was not submitted';
public $text = null;
public $html = null;

public function process( $arg_options = array() ) {

    $admin_email = get_option('admin_email');        

    $options = array(
        'form_id' => 'submit_tool_form_mailer_id',
        'send_to_email' => true,
        'email' => $admin_email,
        'title' => 'New Tool Submission',
        'intro' => 'We received a new tool submission:',
        'save_to_post_type' => true,
        'post_type' => 'tools',
        'captcha' => false,
        'captcha_key' => null,
        'captcha_secret' => null,
        'log_ip' => true,
        'success_message' => 'Thank you for letting us know!',
        'error_message' => 'There was a problem submitting this form. Please contact us directly.'
    );

    //merge options
    foreach($arg_options as $key => $value) {
        $options[ $key ] = $value;
    }

    if( !empty($_POST[$options['form_id']]) ) {
        //the form was submitted
        //we assume the browser did the validation
        $lf = "nr";

        $ignore_fields = array($options['form_id'], 'g-recaptcha-response');

        $text = $options['intro'].$lf.$lf;
        $html = "<p>{$options['intro']}</p>";

        $from_email = null;

        $this->processed = true;

        if($options['captcha']) {
            if(empty($options['captcha_key']) || empty($options['captcha_secret'])) {
                $this->error = 'Captcha key and secret are not set.';
                return true;
            }

            if(empty($_POST['g-recaptcha-response'])) {
                $this->error = 'Captcha response is not present.';
                return true;

            } else if($this->validate_rechapcha($_POST['g-recaptcha-response'], $options['captcha_secret']) !== true) {
                $this->error = 'Captcha validation failed.';
                return true;
            }
        }

        foreach($_POST as $key => $value) {
            if(!in_array( $key, $ignore_fields)) {
                $key = filter_var($key, FILTER_SANITIZE_STRING);
                $value = filter_var($value, FILTER_SANITIZE_STRING);

                $text .= "{$key}: {$value}".$lf;

                if($key == 'email' || $key == 'Email') {
                    $from_email = $value;
                }

                $html .= "<p><b>{$key}</b>: {$value}</p>";
            }
        }

        $stamp = "Submitted on ".date("F j, Y, g:i a");
        if($options['log_ip'] && !empty($_SERVER['REMOTE_ADDR'])) {
            $stamp .= " from ".$_SERVER['REMOTE_ADDR'];
        }

        $text .= $stamp;
        $html .= "<p><em>{$stamp}</em></p>";

        $this->text = $text;
        $this->html = $html;

        $emailed = null;
        $saved = null;

        if($options['send_to_email']) {
            $headers = 'From: '. $admin_email . "rn";
            $emailed = wp_mail($options['email'], $options['title'], $text, $headers);
        }

        $postID = null;
        $content = null;
        $content = sanitize_textarea_field($_POST['post_content']). '<p> [snapshot url="'.esc_url($_POST['url']).'" width="800" height="600"] </p>';

        if($options['save_to_post_type']) {
            if($postID = wp_insert_post( array(  
                'post_title' => sanitize_text_field( $_POST['post_title']),
                'post_content' => $content,                    
                'post_type' => 'tools',                 
                'post_status' => 'draft'
            ) )) {
                $saved = true;
                update_field('url', esc_url_raw($_POST['url']), $postID); // update ACF fields
                update_field('site_name', sanitize_text_field($_POST['post_title']), $postID);
                update_field('developers', sanitize_text_field($_POST['developers']), $postID);                         
                update_field('github', esc_url_raw($_POST['github']), $postID);    


                    // Add Featured Image to Post            
                    $src = 'http://s.wordpress.com/mshots/v1/' . urlencode( $_POST['url'] ) . '?w=800&h=600' ;

                    $image_url        = $src; // Define the image URL here
                    $image_name       = sanitize_text_field($_POST['post_title']);
                    $upload_dir       = wp_upload_dir(); // Set upload folder
                    $image_data       = file_get_contents($image_url); // Get image data
                    $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
                    $filename         = basename( $unique_file_name ); // Create image file name

                    // Check folder permission and define file location
                    if( wp_mkdir_p( $upload_dir['path'] ) ) {
                        $file = $upload_dir['path'] . '/' . $filename;
                    } else {
                        $file = $upload_dir['basedir'] . '/' . $filename;
                    }

                    // Create the image  file on the server
                    file_put_contents( $file, $image_data );

                    // Check image file type
                    $wp_filetype = wp_check_filetype( $filename, null );

                    // Set attachment data
                    $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title'     => sanitize_file_name( $filename ),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                    );

                    // Create the attachment
                    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

                    // Include image.php
                    require_once(ABSPATH . 'wp-admin/includes/image.php');

                    // Define attachment metadata
                    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

                    // Assign metadata to attachment
                    wp_update_attachment_metadata( $attach_id, $attach_data );

                    // And finally assign featured image to post
                    set_post_thumbnail( $post_id, $attach_id );


            } else {
                $saved = false;                    
            }                    

        }





        if((!$emailed && !$saved) || $emailed === false || $saved === false) {
            $this->error = true;
            $this->message = $options['error_message'];
        } else {
            $this->error = false;
            $this->message = $options['success_message'];
        }

        return true;
    } else {
        //the form was not submitted
        $this->processed = false;
        $this->error = false;
        return false;
    }

}

//source https://gist.github.com/jonathanstark/dfb30bdfb522318fc819
public function validate_rechapcha($response, $secret)
{
    // Verifying the user's response (https://developers.google.com/recaptcha/docs/verify)
    $verifyURL = 'https://www.google.com/recaptcha/api/siteverify';

    $query_data = [
        'secret' => $secret,
        'response' => $response,
        'remoteip' => (isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER['REMOTE_ADDR'])
    ];

    // Collect and build POST data
    $post_data = http_build_query($query_data, '', '&');

    // Send data on the best possible way
    if (function_exists('curl_init') && function_exists('curl_setopt') && function_exists('curl_exec'))
    {
        // Use cURL to get data 10x faster than using file_get_contents or other methods
        $ch = curl_init($verifyURL);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-type: application/x-www-form-urlencoded'));
        $response = curl_exec($ch);
        curl_close($ch);
    }
    else
    {
        // If server not have active cURL module, use file_get_contents
        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $post_data
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($verifyURL, false, $context);
    }

    // Verify all reponses and avoid PHP errors
    if ($response)
    {
        $result = json_decode($response);
        if ($result->success === true)
        {
            return true;
        }
        else
        {
            return $result;
        }
    }

    // Dead end
    return false;
}

}
0
, , , , gaurav 3 years 2020-06-08T02:10:24-05:00 0 Answers 91 views 0

Leave an answer

Browse
Browse