<?php namespace Formine\api; class Controller { /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $formine The ID of this plugin. */ private $formine; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $formine The name of this plugin. * @param string $version The version of this plugin. */ public function __construct($formine, $version) { $this->formine = $formine; $this->version = $version; add_option('formation_email', "blank@blank.com"); } public function register_routes() { register_rest_route('hello', 'test', [ 'methods' => 'GET', 'callback' => [$this, 'test'] ]); register_rest_route('formine', 'submissions', [ 'methods' => 'POST', 'callback' => [$this, 'handle_form_submission'] ]); register_rest_route('formine', 'email', [ 'methods' => 'GET', 'callback' => [$this, 'retrieve_email_address'], 'permission_callback' => function () { return current_user_can('activate_plugins'); } ]); register_rest_route('formine', 'email', [ 'methods' => 'POST', 'callback' => [$this, 'assign_email_address'], 'permission_callback' => function () { return current_user_can('activate_plugins'); } ]); } public function test() { return get_site_url(); } public function handle_form_submission($data) { $headers = $data->get_headers(); $body = $data->get_json_params(); $nonce = $headers['x_wp_nonce'][0]; if (wp_verify_nonce($nonce, 'wp_rest')) { $post_id = wp_insert_post([ 'post_type' => 'formine_submissions', 'post_title' => $body['name'], 'post_status' => 'publish' ]); update_post_meta($post_id, 'form_data', $body); } if ($post_id) { $this->send_email_on_submit($body); return new \WP_REST_Response("{$post_id} {$body} Form successfully submitted!", 200); /* wp_safe_redirect(home_url()); */ /* exit(); */ } } public function send_email_on_submit($form_data) { $email_addresses = get_option('formine_email'); $title = "New Lead from {$form_data["name"]}: BoxStarMovers.com"; $headers = array("Content-Type: text/html; charset=UTF-8"); ob_start(); include plugin_dir_path(__FILE__) . 'boxstar.php'; $content = ob_get_clean(); foreach ($email_addresses as $email) { wp_mail($email, $title, $content, $headers); } } public function assign_email_address($data) { $body = $data->get_json_params(); update_option('formine_email', $body['email']); return rest_ensure_response($body['email']); } public function retrieve_email_address() { $email = get_option('formine_email'); return rest_ensure_response($email); } }