/**
  * Responds to requests activated from the main emergency alert button.
  *
  * @link https://developer.wordpress.org/reference/hooks/wp_ajax__requestaction/
  *
  * @global $_POST
  *
  * @uses WP_Buoy_Plugin::$prefix
  * @uses check_ajax_referer()
  * @uses get_current_user_id()
  * @uses WP_Buoy_User_Settings::get()
  * @uses sanitize_text_field()
  * @uses stripslashes_deep()
  * @uses WP_Buoy_Alert::set()
  * @uses WP_Buoy_Alert::save()
  * @uses WP_Buoy_Alert::get_hash()
  * @uses wp_send_json_error()
  * @uses wp_send_json_success()
  * @uses wp_safe_redirect()
  *
  * @return void
  */
 public static function handleNewAlert()
 {
     check_ajax_referer(self::$prefix . '_new_alert', self::$prefix . '_nonce');
     $postarr = array();
     $meta_input = array();
     // Collect info from the browser via Ajax request
     $alert_position = empty($_POST['pos']) ? false : $_POST['pos'];
     // TODO: array_map and sanitize this?
     if ($alert_position) {
         $meta_input['geo_latitude'] = $alert_position['latitude'];
         $meta_input['geo_longitude'] = $alert_position['longitude'];
     }
     if (isset($_POST[self::$prefix . '_teams']) && is_array($_POST[self::$prefix . '_teams'])) {
         $my_teams = array_map('absint', $_POST[self::$prefix . '_teams']);
         $valid_teams = array();
         foreach ($my_teams as $team_id) {
             $team = new WP_Buoy_Team($team_id);
             if (get_current_user_id() == $team->wp_post->post_author) {
                 $valid_teams[] = $team_id;
             }
         }
         $meta_input[self::$prefix . '_teams'] = $valid_teams;
     }
     // Create and publish the new alert.
     $buoy_user = new WP_Buoy_User(get_current_user_id());
     $postarr['post_title'] = empty($_POST['msg']) ? $buoy_user->get_crisis_message() : sanitize_text_field(stripslashes_deep($_POST['msg']));
     if (!empty($meta_input)) {
         $postarr['meta_input'] = $meta_input;
     }
     $err = new WP_Error();
     if (isset($_POST['scheduled-datetime-utc'])) {
         // TODO: Scheduled alerts should be their own function?
         $old_timezone = date_default_timezone_get();
         date_default_timezone_set('UTC');
         $when_utc = strtotime(stripslashes_deep($_POST['scheduled-datetime-utc']));
         if (!$when_utc) {
             $err->add('scheduled-datetime-utc', __('Buoy could not understand the date and time you entered.', 'buoy'));
         } else {
             $dt = new DateTime("@{$when_utc}");
             // TODO: This fails to offset the UTC time back to server-local time
             //       correctly if the WP site is manually offset by a 30 minute
             //       offset instead of an hourly offset.
             $dt->setTimeZone(new DateTimeZone(wp_get_timezone_string()));
             $postarr['post_date'] = $dt->format('Y-m-d H:i:s');
             $postarr['post_date_gmt'] = gmdate('Y-m-d H:i:s', $when_utc);
             $postarr['post_status'] = 'future';
         }
         date_default_timezone_set($old_timezone);
     }
     $buoy_alert = new self();
     $post_id = $buoy_alert->set($postarr)->save();
     if (is_wp_error($post_id)) {
         wp_send_json_error($post_id);
     } else {
         if (!empty($err->errors)) {
             wp_send_json_error($err);
         } else {
             if (isset($_POST['scheduled-datetime-utc']) && empty($err->errors)) {
                 wp_send_json_success(array('id' => $post_id, 'message' => __('Your timed alert has been scheduled. Schedule another?', 'buoy')));
             } else {
                 // Construct the redirect URL to the alerter's chat room
                 $next_url = wp_nonce_url(admin_url('?page=' . self::$prefix . '_chat' . '&' . self::$prefix . '_hash=' . $buoy_alert->get_hash()), self::$prefix . '_chat', self::$prefix . '_nonce');
                 if (isset($_SERVER['HTTP_ACCEPT'])) {
                     $accepts = explode(',', $_SERVER['HTTP_ACCEPT']);
                 }
                 if ($accepts && 'application/json' === array_shift($accepts)) {
                     wp_send_json_success($next_url);
                 } else {
                     wp_safe_redirect(html_entity_decode($next_url));
                     exit;
                 }
             }
         }
     }
 }
 /**
  * Setup the Marketo API client using the plugin settings
  * @return boolean| [description]
  */
 public static function get_api($return_exceptions = false)
 {
     // Setup the client
     $accessKey = self::get_setting('user_id');
     $secretKey = self::get_setting('encryption_key');
     $soapEndPoint = self::get_setting('endpoint');
     $debug = self::get_setting('debug');
     if (!self::check_soap()) {
         return false;
     }
     if (!empty($soapEndPoint)) {
         $parsed = @parse_url($soapEndPoint);
         if (isset($parsed['host'])) {
             $soapHost = $parsed['host'];
         }
     }
     if (empty($accessKey) || empty($secretKey) || empty($soapEndPoint)) {
         return false;
     }
     if (!class_exists("MarketoClient")) {
         require_once plugin_dir_path(__FILE__) . "api/Marketo_SOAP_PHP_Client.php";
     }
     try {
         $client = new MarketoClient($accessKey, $secretKey, $soapEndPoint, $debug);
         $client->setTimeZone(wp_get_timezone_string());
         if (defined('DOING_AJAX') || !current_user_can('manage_options') || is_admin()) {
             $client->setDebug(false);
         }
         if (current_user_can('manage_options') && isset($_GET['debug'])) {
             $client->setDebug(true);
         }
     } catch (Exception $e) {
         if ($return_exceptions) {
             return $e;
         }
         return false;
     }
     return $client;
 }