/**
  * Processes contact form via ajax request.
  *
  * @todo add security precautions to filter out potential SQL injections or bad data (such as account escalation)
  * @version 1.0
  * Copyright 2011 Andy Potanin, Usability Dynamics, Inc.  <*****@*****.**>
  */
 function process_crm_message()
 {
     global $wp_crm;
     //** Server seems to return nothing somethines, adding space in beginning seems to solve */
     /** This needs to be removed - it causes a warning when the header items are set later in the code, when then causes the form NOT to work echo ' '; */
     //** watch for spam */
     if (!empty($_REQUEST['comment']) || !empty($_REQUEST['email']) || !empty($_REQUEST['name']) || !empty($_REQUEST['url'])) {
         die(json_encode(array('success' => 'false', 'message' => __('If you see this message, WP-CRM through you were a robot.  Please contact admin if you do not think are you one.', 'wp_crm'))));
     }
     $data = $_REQUEST['wp_crm'];
     $crm_action = $_REQUEST['crm_action'];
     if (empty($data)) {
         die;
     }
     //** Some other security */
     if (isset($data['user_data']['user_id'])) {
         //** Fail - user_id will never be passed in this manner unless somebody is screwing around */
         die(json_encode(array('success' => 'false', 'message' => __('Form could not be submitted.', 'wp_crm'))));
     }
     $md5_form_slug = $_REQUEST['form_slug'];
     $associated_object = $_REQUEST['associated_object'];
     foreach ($wp_crm['wp_crm_contact_system_data'] as $form_slug => $form_data) {
         if ($md5_form_slug == md5($form_slug)) {
             $confirmed_form_slug = $form_slug;
             $confirmed_form_data = $form_data;
             continue;
         }
     }
     if (!$confirmed_form_slug) {
         die;
     }
     if (isset($data['user_id'])) {
         //** User ID was passsed. Verify that current user is logged in */
         $current_user = wp_get_current_user();
         if (0 == $current_user->ID || $data['user_id'] != $current_user->ID) {
             //** User ID not found, or passed doesn't match. Either way, fail with ambigous messages.
             die(json_encode(array('success' => 'false', 'message' => __('Form could not be submitted.', 'wp_crm'))));
         } else {
             //** We have User ID, we are updating an existing profile */
             $data['user_data']['user_id']['default'][] = $current_user->ID;
         }
     }
     //** Get required fields */
     foreach ($wp_crm['data_structure']['attributes'] as $field_slug => $field_data) {
         if ($field_data['required']) {
             $required_fields[] = $field_slug;
         }
     }
     $check_fields = apply_filters('wp_crm_distinct_user_fields', array('user_email'));
     //** Do not check any fields if nothing to check */
     foreach ($data['user_data'] as $field_slug => $field_data) {
         foreach ($field_data as $value) {
             $value = WP_CRM_F::get_first_value($value);
             //** Check for completion */
             if ($wp_crm['data_structure']['attributes'][$field_slug]['required']) {
                 $error = apply_filters('wp_crm_contact_form_data_validation', false, array('field' => $field_slug, 'value' => $value));
                 if ($error) {
                     $bad_fields[$field_slug] = $error;
                     continue;
                 }
                 if (empty($value)) {
                     $bad_fields[$field_slug] = sprintf(__('%1s cannot be empty.', 'wp_crm'), $wp_crm['data_structure']['attributes'][$field_slug]['title']);
                 }
             }
             //** Check for data conlicts */
             if (is_array($check_fields) && in_array($field_slug, $check_fields)) {
                 //** Current field needs to be checked to avoid conflict */
                 if ($conflict_user_id = WP_CRM_F::check_data_field($field_slug, $value)) {
                     if ($data['user_data']['user_id']['default'][0] != $conflict_user_id) {
                         $bad_fields[$field_slug] = sprintf(__('This %1s belongs to a registered user, please login.', 'wp_crm'), $wp_crm['data_structure']['attributes'][$field_slug]['title']);
                     }
                 }
             }
         }
     }
     //** If this is a validation request, we check to make sure everything is good */
     if ($crm_action == 'system_validate') {
         if ($bad_fields) {
             die(json_encode(array('success' => true, 'validation_passed' => false, 'bad_fields' => $bad_fields)));
         } else {
             die(json_encode(array('success' => true, 'validation_passed' => true)));
         }
     }
     if ($bad_fields) {
         die(json_encode(array('success' => 'false', 'bad_fields' => $bad_fields, 'message' => __('Form could not be submitted. Please make sure you have entered your information properly.', 'wp_crm'))));
     }
     $user_data = @wp_crm_save_user_data($data['user_data'], 'default_role=' . $wp_crm['configuration']['new_contact_role'] . '&use_global_messages=false&match_login=true&no_redirect=true&return_detail=true');
     if (!$user_data) {
         if ($confirmed_form_data['message_field'] == 'on') {
             //** If contact form includes a message, notify that message could not be sent */
             die(json_encode(array('success' => 'false', 'message' => __('Message could not be sent. Please make sure you have entered your information properly.', 'wp_crm'))));
         } else {
             //** If contact form DOES NOT include a message, notify that it could not be submitted */
             die(json_encode(array('success' => 'false', 'message' => __('Form could not be submitted. Please make sure you have entered your information properly.', 'wp_crm'))));
         }
     } else {
         $user_id = $user_data['user_id'];
         if ($user_data['new_user']) {
             //** Log in DB that this account was created automatically via contact form */
             update_user_meta($user_id, 'wpc_cm_generated_account', true);
         }
     }
     $message = WP_CRM_F::get_first_value($_REQUEST['wp_crm']['user_data']['message_field']);
     if ($confirmed_form_data['notify_with_blank_message'] != 'on' && empty($message)) {
         //** No message submitted */
     } else {
         if (empty($message)) {
             $message = __(' -- No message. -- ', 'wp_crm');
         }
         //** Message is submitted. Do stuff. */
         $message_id = class_contact_messages::insert_message($user_id, $message, $confirmed_form_slug);
         $associated_object = !empty($associated_object) ? $associated_object : false;
         if ($associated_object) {
             class_contact_messages::insert_message_meta($message_id, 'associated_object', $associated_object);
         }
         //** Build default notification arguments */
         foreach ($wp_crm['data_structure']['attributes'] as $attribute => $attribute_data) {
             $notification_info[$attribute] = wp_crm_get_value($attribute, $user_id);
         }
         $notification_info['message_content'] = stripslashes($message);
         $notification_info['trigger_action'] = $confirmed_form_data['title'];
         $notification_info['profile_link'] = admin_url("admin.php?page=wp_crm_add_new&user_id={$user_id}");
         /** Add extra filters */
         $maybe_notification_info = apply_filters('wp_crm_notification_info', $notification_info, $associated_object);
         //** Make sure our array wasn't overwritten by a poorly written hooked in function, it shuold never be blank */
         if (!empty($maybe_notification_info) || !is_array($maybe_notification_info)) {
             $notification_info = $maybe_notification_info;
         }
         //** Pass the trigger and array of notification arguments to sender function */
         wp_crm_send_notification($confirmed_form_slug, $notification_info);
     }
     $result = array('success' => 'true', 'message' => $data['success_message']);
     if (current_user_can('manage_options')) {
         $result['user_id'] = $user_id;
     }
     echo json_encode($result);
     die;
 }