/**
  * Validate the IPN notification
  *
  * @param none
  * @return boolean
  */
 public function validateIpn()
 {
     if (empty($_POST)) {
         // Redirect
         if (!empty($_REQUEST)) {
             $this->response['status'] = isset($_REQUEST['status']) ? $_REQUEST['status'] : "N/A";
             $this->response['responseData']['transactionID'] = isset($_REQUEST['reference']) ? $_REQUEST['reference'] : "N/A";
             $this->response['responseData']['responseMessage'] = isset($_REQUEST['error']) ? $_REQUEST['error'] : "N/A";
             $this->response['responseData']['hash'] = isset($_REQUEST['hash']) ? $_REQUEST['hash'] : "N/A";
         }
         $xml = "n/a";
     } else {
         // Get XML POST notification
         $xml = file_get_contents('php://input', NULL, NULL, 0, 1024);
         $this->response = $this->_parseResponse($xml);
         $this->response['status'] = $this->response['status'] == true ? "approved" : "declined";
     }
     $this->response['attendee_id'] = isset($_REQUEST['id']) ? $_REQUEST['id'] : 0;
     $this->response['reg_id'] = espresso_registration_id($this->response['attendee_id']);
     if (isset($xml) && isset($this->response['status']) && $this->_calculateHash($this->response, 'redirect') == $this->response['responseData']['hash']) {
         // Valid IPN transaction.
         $this->logResults(true);
         return true;
     } else {
         $this->lastError = isset($this->response['error']) ? $this->response['error'] : $this->response['responseData']['responseMessage'];
         $this->logResults(false);
         return false;
     }
 }
Example #2
0
 function event_espresso_send_payment_notification($atts)
 {
     global $wpdb, $org_options;
     do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
     //Extract the attendee_id and registration_id
     extract($atts);
     if (empty($registration_id)) {
         $registration_id = espresso_registration_id($attendee_id);
     }
     if (empty($registration_id)) {
         return __('No ID Supplied', 'event_espresso');
     }
     //Get the attendee  id or registration_id and create the sql statement
     $sql = "SELECT a.* FROM " . EVENTS_ATTENDEE_TABLE . " a ";
     $sql .= " WHERE a.registration_id = '" . $registration_id . "' ";
     //$sql .= "  ORDER BY id LIMIT 1 ";
     $attendees = $wpdb->get_results($sql);
     if ($org_options['default_mail'] == 'Y') {
         foreach ($attendees as $attendee) {
             $attendee_id = $attendee->id;
             event_espresso_email_confirmations(array('attendee_id' => $attendee_id, 'send_admin_email' => 'false', 'send_attendee_email' => 'true', 'custom_data' => array('email_type' => 'payment', 'payment_subject' => $org_options['payment_subject'], 'payment_message' => $org_options['payment_message'])));
         }
     }
     return;
 }
Example #3
0
function espresso_quantity_for_registration($attendee_id)
{
    global $wpdb;
    $cnt = $wpdb->get_var("SELECT quantity FROM " . EVENTS_ATTENDEE_TABLE . " WHERE registration_id='" . espresso_registration_id($attendee_id) . "' ORDER BY id ");
    return $cnt;
}
function espresso_display_mwarrior($payment_data)
{
    extract($payment_data);
    // Setup class
    include_once 'Mwarrior.php';
    $mwarrior = new Espresso_Mwarrior();
    // initiate an instance of the class
    echo '<!--Event Espresso Merchant Warrior Gateway Version ' . $mwarrior->gateway_version . '-->';
    global $org_options;
    //global $attendee_id;
    $mwarrior_settings = get_option('event_espresso_mwarrior_settings');
    $mwarrior_id = empty($mwarrior_settings['mwarrior_id']) ? '' : $mwarrior_settings['mwarrior_id'];
    $mwarrior_apikey = empty($mwarrior_settings['mwarrior_apikey']) ? '' : $mwarrior_settings['mwarrior_apikey'];
    $mwarrior_passphrase = empty($mwarrior_settings['mwarrior_passphrase']) ? '' : $mwarrior_settings['mwarrior_passphrase'];
    $mwarrior_cur = empty($mwarrior_settings['currency_format']) ? '' : $mwarrior_settings['currency_format'];
    $logo_url = empty($mwarrior_settings['image_url']) ? '' : $mwarrior_settings['image_url'];
    $use_sandbox = $mwarrior_settings['use_sandbox'];
    if ($use_sandbox) {
        // Enable test mode if needed
        $mwarrior->enableTestMode();
    }
    $salt = $mwarrior->_generateHashSalt();
    $mwarrior->setMerchantInfo($mwarrior_id, $mwarrior_apikey, $mwarrior_passphrase);
    //Post variables
    $mwarrior->addField('method', 'processCard');
    $mwarrior->addField('merchantUUID', $mwarrior_id);
    $mwarrior->addField('apiKey', $mwarrior_apikey);
    $mwarrior->addField('customerName', $fname . " " . $lname);
    $mwarrior->addField('customerEmail', $attendee_email);
    $mwarrior->addField('customerAddress', $address);
    $mwarrior->addField('customerCity', $city);
    $mwarrior->addField('customerPostCode', $zip);
    $mwarrior->addField('customerState', $state);
    $mwarrior->addField('customerCountry', empty($country) ? '' : $country);
    $mwarrior->addField('customerPhone', $phone);
    $mwarrior->addField('transactionProduct', stripslashes_deep($event_name));
    $mwarrior->addField('transactionAmount', number_format($event_cost, 2, '.', ''));
    $mwarrior->addField('transactionCurrency', $mwarrior_cur);
    $mwarrior->addField('logoURL', $logo_url);
    if ($mwarrior_settings['force_ssl_return']) {
        $home = str_replace("http://", "https://", home_url());
    } else {
        $home = home_url();
    }
    $mwarrior->addField('returnURL', $home . '/?page_id=' . $org_options['return_url'] . '&id=' . $attendee_id . '&r_id=' . $registration_id . '&event_id=' . $event_id . '&attendee_action=post_payment&form_action=payment&type=mwarrior');
    //$mwarrior->addField('cancel_return', $home.'/?page_id='.$org_options['cancel_return']);
    $mwarrior->addField('notifyURL', $home . '/?page_id=' . $org_options['return_url'] . '&id=' . $attendee_id . '&r_id=' . $registration_id . '&event_id=' . $event_id . '&attendee_action=post_payment&form_action=payment&type=mwarrior');
    $mwarrior->addField('urlHash', $mwarrior->_calculateHash($mwarrior->fields, "url"));
    $mwarrior->addField('hash', $mwarrior->_calculateHash($mwarrior->fields, "transaction"));
    $mwarrior->addField('hashSalt', $salt);
    //Enable this function if you want to send payment notification before the person has paid.
    //This function is copied on the payment processing page
    //event_espresso_send_payment_notification($attendee_id, $txn_id, $amount_pd);
    //Decide if you want to auto redirect to your payment website or display a payment button.
    if (!empty($mwarrior_settings['bypass_payment_page']) && $mwarrior_settings['bypass_payment_page'] == 'Y') {
        $mwarrior->submitPayment();
        //Enable auto redirect to payment site
    } else {
        if (empty($mwarrior_settings['button_url'])) {
            if (file_exists(EVENT_ESPRESSO_GATEWAY_DIR . "/mwarrior/mwarrior-logo.png")) {
                $button_url = EVENT_ESPRESSO_GATEWAY_DIR . "/mwarrior/mwarrior-logo.png";
            } else {
                $button_url = EVENT_ESPRESSO_PLUGINFULLURL . "gateways/mwarrior/mwarrior-logo.png";
            }
        } elseif (file_exists($mwarrior_settings['button_url'])) {
            $button_url = $mwarrior_settings['button_url'];
        } else {
            //If no other buttons exist, then use the default location
            $button_url = EVENT_ESPRESSO_PLUGINFULLURL . "gateways/mwarrior/mwarrior-logo.png";
        }
        $mwarrior->submitButton($button_url, 'mwarrior');
        //Display payment button
    }
    // Store the salt temporarily in the database
    $mwarrior->_storeHashSalt($salt, espresso_registration_id($attendee_id));
    if ($use_sandbox) {
        echo '<h3 style="color:#ff0000;" title="Payments will not be processed">' . __('Debug Mode Is Turned On', 'event_espresso') . '</h3>';
        $mwarrior->dump_fields();
        // for debugging, output a table of all the fields
    }
}
Example #5
0
function espresso_process_firstdata($payment_data)
{
    global $wpdb;
    $attendee_id = $payment_data['attendee_id'];
    $registration_id = espresso_registration_id($attendee_id);
    $sql = "SELECT ea.amount_pd, ed.event_name FROM " . EVENTS_ATTENDEE_TABLE . " ea ";
    $sql .= "JOIN " . EVENTS_DETAIL_TABLE . " ed ";
    $sql .= "ON ed.id = ea.event_id ";
    $sql .= " WHERE registration_id = '" . $registration_id . "' ";
    $sql .= " ORDER BY ea.id ASC LIMIT 1";
    $r = $wpdb->get_row($sql);
    if (!$r || $wpdb->num_rows == 0) {
        exit("Looks like something went wrong.  Please try again or notify the website administrator.");
    }
    $firstdata_settings = get_option('event_espresso_firstdata_settings');
    $pem_file = EVENT_ESPRESSO_PLUGINFULLPATH . "gateways/firstdata/" . $firstdata_settings['firstdata_store_id'] . ".pem";
    if (file_exists(EVENT_ESPRESSO_GATEWAY_DIR . "firstdata/" . $firstdata_settings['firstdata_store_id'] . ".pem")) {
        $pem_file = EVENT_ESPRESSO_GATEWAY_DIR . "firstdata/" . $firstdata_settings['firstdata_store_id'] . ".pem";
    }
    if (empty($firstdata_settings['use_verify_peer'])) {
        $firstdata_settings['use_verify_peer'] = false;
    }
    include "lphp.php";
    $mylphp = new Espresso_Linkpoint();
    $myorder['verify_peer'] = $firstdata_settings['use_verify_peer'];
    $myorder["debugging"] = $firstdata_settings['use_sandbox'];
    $myorder["host"] = $myorder["debugging"] ? "staging.linkpt.net" : "secure.linkpt.net";
    $myorder["port"] = "1129";
    $myorder["keyfile"] = $pem_file;
    # Change this to the name and location of your certificate file
    $myorder["configfile"] = $firstdata_settings['firstdata_store_id'];
    # Change this to your store number
    $myorder["ordertype"] = "SALE";
    $myorder["result"] = "LIVE";
    # For a test, set result to GOOD, DECLINE, or DUPLICATE
    $myorder["cardnumber"] = $_POST['card_num'];
    $myorder["cardexpmonth"] = $_POST['expmonth'];
    $myorder["cardexpyear"] = $_POST['expyear'];
    $myorder["chargetotal"] = $payment_data['total_cost'];
    $myorder["name"] = $_POST['first_name'] . ' ' . $_POST['last_name'];
    $myorder["address1"] = $_POST['address'];
    $myorder["city"] = $_POST["city"];
    $myorder["state"] = $_POST["state"];
    $myorder["email"] = $_POST["email"];
    /**
     * It looks like firstdata requires addrnum, the beginning
     * number of the address.  On their test forms, they have a specific
     * field for this.  I am just going to grab the address, split it and grab
     * index 0.  Will see how this goes before adding a new field.  If can't split the
     * address, will pass it full.
     */
    $addrnum = $_POST['address'];
    $temp_address = explode(" ", $_POST['address']);
    if (count($temp_address > 0)) {
        $addrnum = $temp_address[0];
    }
    $myorder["addrnum"] = $addrnum;
    $myorder["zip"] = $_POST["zip"];
    $payment_data['txn_type'] = 'First Data';
    $payment_data['payment_status'] = "Incomplete";
    $payment_data['txn_id'] = 0;
    $payment_data['txn_details'] = serialize($_REQUEST);
    $result = $mylphp->curl_process($myorder);
    # use curl methods
    if (!is_array($result)) {
        //sometimes curl_process returns a string instead of an array, which is dumb.
        //but we can use their decodeXML method to fix that
        $result = $mylphp->decodeXML($result);
    }
    if ($myorder["debugging"]) {
        echo "<p>var_dump of order data:</p> ";
        var_dump($myorder);
        echo "<br />";
        echo "<p>var_dump of result:</p> ";
        var_dump($result);
        echo '<h3 style="color:#ff0000;" title="Payments will not be processed">' . __('End of Debugging / Sandbox output (this will go away when you switch to live transactions)', 'event_espresso') . '</h3>';
    }
    if (!empty($result)) {
        $payment_data['txn_details'] = serialize($result);
        $payment_data['txn_id'] = isset($result["r_ordernum"]) ? $result["r_ordernum"] : '';
        if ($result["r_approved"] != "APPROVED" && $result["r_approved"] != "DECLINED") {
            if ($result['r_approved'] != '<') {
                echo "<br />Status: " . $result['r_approved'];
            }
            if ($result['r_error'] != '<') {
                echo "<br />Error: " . $result['r_error'];
            }
            echo "<br />";
        } elseif ($result["r_approved"] == "DECLINED") {
            $payment_data['payment_status'] = 'Payment Declined';
        } else {
            // success
            $payment_data['payment_status'] = 'Completed';
        }
    }
    //add_action('action_hook_espresso_email_after_payment', 'espresso_email_after_payment');
    return $payment_data;
}
$payment_date = $_POST['notify_time'];
$txn_id = $_POST['notify_id'];
$amount_pd = $_POST['total_fee'];
$txn_type = $_POST['notify_type'];
$alipay_settings = get_option('event_espresso_alipay_settings');
require_once "alipay_notify.php";
require_once "alipay_config.php";
$alipay = new alipay_notify($partner, $security_code, $sign_type, $_input_charset, $transport);
$verify_result = $alipay->notify_verify();
if ($verify_result) {
    // out_trade_no= $_POST["out_trade_no"]
    // status = $_POST["trade_status"]
    // put the database string here, to update the database
    $payment_status = 'Completed';
    global $wpdb;
    $sql = "UPDATE " . EVENTS_ATTENDEE_TABLE . " SET payment_status = '{$payment_status}', txn_type = '{$txn_type}', txn_id = '{$txn_id}', amount_pd = '{$amount_pd}',  payment_date ='{$payment_date}', transaction_details = '" . serialize($_POST) . "' WHERE registration_id ='" . espresso_registration_id($attendee_id) . "' ";
    $wpdb->query($sql);
    $email_before_payment = $org_options['email_before_payment'];
    //Send payment confirmation emails
    event_espresso_send_payment_notification(array('attendee_id' => $attendee_id));
    //Send the email confirmation
    //@params $attendee_id, $send_admin_email, $send_attendee_email
    if ($email_before_payment == 'N') {
        event_espresso_email_confirmations(array('attendee_id' => $attendee_id, 'send_admin_email' => 'true', 'send_attendee_email' => 'true'));
    }
    echo "success";
    log_result("verify_success");
} else {
    echo "fail";
    log_result("verify_failed");
}
 function espresso_attendee_price($atts)
 {
     do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
     global $wpdb;
     isset($atts) ? extract($atts) : '';
     /**
      * If the registration_id is empty, then retrieve it
      * */
     $generated_registration_id = false;
     if (!isset($registration_id)) {
         if (!isset($attendee_id)) {
             return;
         } else {
             $registration_id = espresso_registration_id($attendee_id);
         }
     }
     //Found use of single price only in payment option in attendee record edit page for admin.
     if (isset($single_price) && ($single_price = true && isset($attendee_id) && $attendee_id > 0)) {
         $sql = "SELECT final_price FROM " . EVENTS_ATTENDEE_TABLE;
         $sql .= " WHERE id ='%d' LIMIT 0,1";
         $res = $wpdb->get_row($wpdb->prepare($sql, $attendee_id));
         if ($res) {
             return number_format($res->final_price, 2, '.', '');
         }
     }
     //Return the total amount paid for this registration
     if (isset($reg_total) && ($reg_total = true)) {
         $sql = "SELECT amount_pd as total FROM " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s' order by id limit 1";
         $total_cost = $wpdb->get_var($wpdb->prepare($sql, $registration_id));
         return number_format($total_cost, 2, '.', '');
     }
     //Return the total amount paid for a session. Uses the registration id.
     if (isset($session_total) && ($session_total = true)) {
         $attendee_session = $wpdb->get_var($wpdb->prepare("select attendee_session from " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s' ", $registration_id));
         if (!empty($attendee_session)) {
             //If attendee_session is empty then return only single attendee information
             $total_cost = 0;
             $total_cost = $wpdb->get_var($wpdb->prepare("select sum(amount_pd) as amount_pd from " . EVENTS_ATTENDEE_TABLE . " where attendee_session = '%s'", $attendee_session));
             return number_format($total_cost, 2, '.', '');
         } else {
             $primary_registration_id = $registration_id;
             $rs = $wpdb->get_row($wpdb->prepare("select primary_registration_id from " . EVENTS_MULTI_EVENT_REGISTRATION_ID_GROUP_TABLE . " where registration_id = '%s' limit 0,1 ", $registration_id));
             if ($rs !== NULL) {
                 $primary_registration_id = $rs->primary_registration_id;
             }
             $sql = "select sum(amount_pd) as total from " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s' ";
             $total_cost = $wpdb->get_var($wpdb->prepare($sql, $primary_registration_id));
             return number_format($total_cost, 2, '.', '');
         }
     }
     //Return the amount paid for an individual attendee
     if (isset($attendee_id) && $attendee_id > 0) {
         $sql = "SELECT final_price, quantity FROM " . EVENTS_ATTENDEE_TABLE;
         $sql .= " WHERE id ='%d' LIMIT 0,1";
         $res = $wpdb->get_row($wpdb->prepare($sql, $attendee_id));
         if ($res) {
             $total_cost = $res->final_price * $res->quantity;
             return number_format($total_cost, 2, '.', '');
         }
     }
     //If no results are returned above or the registration id was passed, then get the price by looking in EVENTS_ATTENDEE_TABLE
     $sql = "SELECT amount_pd FROM " . EVENTS_ATTENDEE_TABLE . " WHERE registration_id ='" . $registration_id . "' ORDER BY id LIMIT 0,1";
     $wpdb->get_results($sql);
     if ($wpdb->num_rows >= 1) {
         return number_format($wpdb->last_result[0]->amount_pd, 2, '.', '');
     }
     return NULL;
 }
Example #8
0
?>
					</th>
					<td  valign="top">
						<span class="event_espresso_value"><?php 
echo stripslashes_deep($attendee_name);
?>
 (<?php 
echo $attendee_email;
?>
) 
<?php 
echo '<a href="' . home_url() . '/?page_id=' . $event_page_id . '&amp;registration_id=' . $registration_id . '&amp;id=' . $attendee_id . '&amp;regevent_action=edit_attendee&amp;primary=' . $attendee_id . '&amp;event_id=' . $event_id . '&amp;attendee_num=' . $attendee_num . '">' . __('Edit', 'event_espresso') . '</a>';
// removed p_id='.$p_id.'&amp; coupon_code='.$coupon_code.'&amp;groupon_code='.$groupon_code.'&amp;
//Create additional attendees
$sql = "SELECT * FROM " . EVENTS_ATTENDEE_TABLE;
$sql .= " WHERE registration_id = '" . espresso_registration_id($attendee_id) . "' AND id != '" . $attendee_id . "' ";
//echo $sql;
$x_attendees = $wpdb->get_results($sql, ARRAY_A);
if ($wpdb->num_rows > 0) {
    foreach ($x_attendees as $x_attendee) {
        $attendee_num++;
        //echo $attendee_num;
        //print_r($x_attendees);
        echo "<br/>" . $x_attendee['fname'] . " " . $x_attendee['lname'] . " ";
        if ($x_attendee['email'] != '') {
            echo "(" . $x_attendee['email'] . ") ";
        }
        //Create edit link
        echo '<a href="' . home_url() . '/?page_id=' . $event_page_id . '&amp;registration_id=' . $registration_id . '&amp;id=' . $x_attendee['id'] . '&amp;regevent_action=register&amp;form_action=edit_attendee&amp;primary=' . $attendee_id . '&amp;p_id=' . $attendee_id . '&amp;attendee_num=' . $attendee_num . '&amp;event_id=' . $event_id . '">' . __('Edit', 'event_espresso') . '</a>';
        // removed coupon_code='.$coupon_code.'&amp;groupon_code='.$groupon_code.'&amp;
        //Create delete link
Example #9
0
/**
 * espresso_attendee_price()
 *
 * @return float|null  the price paid for an event by attendee id or the registration id, if information not found then it will return null
 */
function espresso_attendee_price($atts)
{
    global $wpdb;
    isset($atts) ? extract($atts) : '';
    /**
     * If the registration_id is empty, then retrieve it
     * */
    $generated_registration_id = false;
    if (!isset($registration_id)) {
        if (!isset($attendee_id)) {
            return;
        } else {
            $registration_id = espresso_registration_id($attendee_id);
        }
    }
    /**
     * Check if the attendee is from old age i.e. before 3.1.10
     * */
    $ice_age = true;
    $ice_row = $wpdb->get_row($wpdb->prepare("select * from " . EVENTS_ATTENDEE_COST_TABLE . " inner join " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s'", $registration_id));
    if ($ice_row !== NULL) {
        $ice_age = false;
    }
    /**
     * Found use of single price only in payment option in attendee record edit page for admin.
     * */
    if (isset($single_price) && ($single_price = true && isset($attendee_id) && $attendee_id > 0)) {
        $sql = '';
        $sql = "SELECT cost amount_pd FROM " . EVENTS_ATTENDEE_COST_TABLE . " eac ";
        $sql .= " WHERE eac.attendee_id ='%d' LIMIT 0,1";
        $res = $wpdb->get_results($wpdb->prepare($sql, $attendee_id));
        if ($wpdb->num_rows >= 1 && $wpdb->last_result[0]->amount_pd != NULL) {
            $total_cost = $wpdb->last_result[0]->amount_pd;
            return number_format($total_cost, 2, '.', '');
        }
    }
    /**
     * Return the total amount paid for this registration
     * */
    if (isset($reg_total) && ($reg_total = true)) {
        $sql = "select amount_pd as total from " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s' order by id limit 1";
        $total_cost = $wpdb->get_var($wpdb->prepare($sql, $registration_id));
        return number_format($total_cost, 2, '.', '');
    }
    /**
     * Return the total amount paid for a session. Uses the registration id.
     * */
    if (isset($session_total) && ($session_total = true)) {
        $attendee_session = $wpdb->get_var($wpdb->prepare("select attendee_session from " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s' ", $registration_id));
        if (trim($attendee_session == '')) {
            /**
             * If attendee_session is empty then return only single attendee information
             * */
            $total_cost = 0;
            $total_cost = $wpdb->get_var($wpdb->prepare("select sum(amount_pd) as amount_pd from " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s'", $registration_id));
            return number_format($total_cost, 2, '.', '');
        } else {
            if ($ice_age) {
                $sql = "select amount_pd from " . EVENTS_ATTENDEE_TABLE . "  where attendee_session = '%s' order by id limit 1";
                $total_cost = $wpdb->get_var($wpdb->prepare($sql, $attendee_session));
                return number_format($total_cost, 2, '.', '');
            } else {
                $primary_registration_id = $registration_id;
                $rs = $wpdb->get_row($wpdb->prepare("select primary_registration_id from " . EVENTS_MULTI_EVENT_REGISTRATION_ID_GROUP_TABLE . " where registration_id = '%s' limit 0,1 ", $registration_id));
                if ($rs !== NULL) {
                    $primary_registration_id = $rs->primary_registration_id;
                }
                $sql = "select sum(amount_pd) as total from " . EVENTS_ATTENDEE_TABLE . " where registration_id = '%s' ";
                $total_cost = $wpdb->get_var($wpdb->prepare($sql, $primary_registration_id));
                return number_format($total_cost, 2, '.', '');
            }
        }
    }
    /**
     * Returnt the amount paid for an individual attendee
     * */
    if (isset($attendee_id) && $attendee_id > 0) {
        $sql = '';
        $sql = "SELECT cost amount_pd, quantity FROM " . EVENTS_ATTENDEE_COST_TABLE . " WHERE attendee_id ='" . $attendee_id . "' ORDER BY attendee_id  LIMIT 0,1";
        $res = $wpdb->get_results($sql);
        if ($wpdb->num_rows >= 1 && $wpdb->last_result[0]->amount_pd != NULL) {
            $total_cost = $wpdb->last_result[0]->amount_pd * $wpdb->last_result[0]->quantity;
            return number_format($total_cost, 2, '.', '');
        }
    }
    /**
     * If no results are returned above or the registration id was passed, then get the price by looking in EVENTS_ATTENDEE_TABLE
     * */
    $sql = '';
    $sql = "SELECT amount_pd FROM " . EVENTS_ATTENDEE_TABLE . " WHERE registration_id ='" . $registration_id . "' ORDER BY id LIMIT 0,1";
    $wpdb->get_results($sql);
    if ($wpdb->num_rows >= 1) {
        return number_format($wpdb->last_result[0]->amount_pd, 2, '.', '');
    }
    return NULL;
}
function attendee_edit_record()
{
    global $wpdb, $org_options;
    do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
    $id = isset($_REQUEST['id']) ? absint($_REQUEST['id']) : FALSE;
    $registration_id = isset($_REQUEST['registration_id']) ? wp_strip_all_tags($_REQUEST['registration_id']) : FALSE;
    $req_primary = isset($_REQUEST['primary']) ? wp_strip_all_tags(absint($_REQUEST['primary'])) : $id;
    $req_p_id = isset($_REQUEST['p_id']) ? wp_strip_all_tags(absint($_REQUEST['p_id'])) : FALSE;
    if (isset($_REQUEST['r_id']) && !empty($_REQUEST['r_id'])) {
        $registration_id = wp_strip_all_tags($_REQUEST['r_id']);
    }
    if ($id && $registration_id) {
        if (!empty($_REQUEST['delete_attendee']) && $_REQUEST['delete_attendee'] == 'true') {
            $SQL = " DELETE FROM " . EVENTS_ATTENDEE_TABLE . " WHERE id = %d";
            $wpdb->query($wpdb->prepare($SQL, $id));
            $SQL = "SELECT id from " . EVENTS_ATTENDEE_TABLE . " WHERE registration_id = %s";
            $wpdb->query($wpdb->prepare($SQL, $registration_id));
            if ($wpdb->num_rows == 0) {
                $SQL = " UPDATE " . EVENTS_ATTENDEE_TABLE . " ";
                $SQL .= "SET quantity = IF(quantity IS NULL ,NULL,IF(quantity > 0,IF(quantity-1>0,quantity-1,1),0)) ";
                $SQL .= "WHERE registration_id = %s";
                $wpdb->query($wpdb->prepare($SQL, $registration_id));
                event_espresso_cleanup_multi_event_registration_id_group_data();
            }
            if (isset($req_primary) && isset($req_p_id)) {
                return events_payment_page($req_primary);
            }
        }
        // end delete attendee
        $counter = 0;
        $additional_attendees = NULL;
        $SQL = "SELECT  att.*, evt.event_name, evt.question_groups, evt.event_meta ";
        $SQL .= "FROM " . EVENTS_ATTENDEE_TABLE . " att ";
        $SQL .= "JOIN " . EVENTS_DETAIL_TABLE . " evt ON att.event_id = evt.id ";
        $SQL .= "WHERE att.id = %d AND att.registration_id = %s ";
        $SQL .= "ORDER BY att.id";
        $attendee = $wpdb->get_row($wpdb->prepare($SQL, $id, $registration_id));
        if ($attendee != FALSE) {
            $display_attendee_form = TRUE;
            $id = $attendee->id;
            $registration_id = $attendee->registration_id;
            $lname = $attendee->lname;
            $fname = $attendee->fname;
            $address = $attendee->address;
            $city = $attendee->city;
            $state = $attendee->state;
            $zip = $attendee->zip;
            $email = $attendee->email;
            $payment = $attendee->payment;
            $phone = $attendee->phone;
            $date = $attendee->date;
            $payment_status = $attendee->payment_status;
            $txn_type = $attendee->txn_type;
            $txn_id = $attendee->txn_id;
            $amount_pd = $attendee->amount_pd;
            $quantity = $attendee->quantity;
            $payment_date = $attendee->payment_date;
            $event_id = $attendee->event_id;
            $event_name = stripslashes_deep($attendee->event_name);
            $question_groups = maybe_unserialize($attendee->question_groups);
            $event_meta = maybe_unserialize($attendee->event_meta);
            if (!$attendee->is_primary && isset($event_meta['add_attendee_question_groups']) && $event_meta['add_attendee_question_groups'] != NULL) {
                $question_groups = $event_meta['add_attendee_question_groups'];
            }
            //printr( $question_groups, '$question_groups  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
            $questions_in = '';
            foreach ($question_groups as $g_id) {
                $questions_in .= $g_id . ',';
            }
            $questions_in = substr($questions_in, 0, -1);
            //			echo '<h4>$questions_in : ' . $questions_in . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
            $group_name = '';
            $counter = 0;
            //pull the list of questions that are relevant to this event
            $SQL = "SELECT q.*, q.id AS q_id, qg.group_name FROM " . EVENTS_QUESTION_TABLE . " q ";
            $SQL .= "JOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id ";
            $SQL .= "JOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id ";
            $SQL .= "WHERE qgr.group_id in ( {$questions_in} ) ";
            $SQL .= "AND q.admin_only != 'Y' ";
            $SQL .= "ORDER BY qg.group_order, qg.id, q.sequence ASC";
            $questions = $wpdb->get_results($wpdb->prepare($SQL, NULL));
            //			echo '<h4>last_query : ' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
            //			printr( $questions, '$questions  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
            $SQL = "SELECT question_id, answer FROM " . EVENTS_ANSWER_TABLE . " ans WHERE ans.attendee_id = %d";
            $answers = $wpdb->get_results($wpdb->prepare($SQL, $id));
            $answer_a = array();
            foreach ($answers as $answer) {
                array_push($answer_a, $answer->question_id);
            }
            // Update the attendee information
            if (isset($_REQUEST['attendee_action']) && $_REQUEST['attendee_action'] == 'update_attendee') {
                $fname = !empty($_POST['fname']) ? ee_sanitize_value($_POST['fname']) : '';
                $lname = !empty($_POST['lname']) ? ee_sanitize_value($_POST['lname']) : '';
                $address = !empty($_POST['address']) ? ee_sanitize_value($_POST['address']) : '';
                $city = !empty($_POST['city']) ? ee_sanitize_value($_POST['city']) : '';
                $state = !empty($_POST['state']) ? ee_sanitize_value($_POST['state']) : '';
                $zip = !empty($_POST['zip']) ? ee_sanitize_value($_POST['zip']) : '';
                $phone = !empty($_POST['phone']) ? ee_sanitize_value($_POST['phone']) : '';
                $email = !empty($_POST['email']) ? ee_sanitize_value($_POST['email']) : '';
                $SQL = "UPDATE " . EVENTS_ATTENDEE_TABLE . " SET fname=%s, lname=%s, address=%s, city=%s, state=%s, zip=%s, phone=%s, email=%s WHERE id =%d";
                $wpdb->query($wpdb->prepare($SQL, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $id));
                if ($questions) {
                    foreach ($questions as $question) {
                        switch ($question->question_type) {
                            case "TEXT":
                            case "TEXTAREA":
                            case "DROPDOWN":
                            case "SINGLE":
                                $post_val = $question->system_name != '' ? ee_sanitize_value($_POST[$question->system_name]) : ee_sanitize_value($_POST[$question->question_type . '_' . $question->q_id]);
                                break;
                            case "MULTIPLE":
                                $post_val = '';
                                if (!empty($_POST[$question->question_type . '_' . $question->id])) {
                                    for ($i = 0; $i < count($_POST[$question->question_type . '_' . $question->id]); $i++) {
                                        $post_val .= trim(ee_sanitize_value($_POST[$question->question_type . '_' . $question->id][$i])) . ',';
                                    }
                                }
                                $post_val = substr($post_val, 0, -1);
                                break;
                        }
                        $post_val = html_entity_decode($post_val, ENT_QUOTES, 'UTF-8');
                        if (in_array($question->q_id, $answer_a)) {
                            $SQL = "UPDATE " . EVENTS_ANSWER_TABLE . " SET answer = %s WHERE attendee_id = %d AND question_id =%d";
                            $wpdb->query($wpdb->prepare($SQL, $post_val, $id, $question->q_id));
                        } else {
                            $SQL = "INSERT INTO " . EVENTS_ANSWER_TABLE . " ( registration_id, answer, attendee_id, question_id ) VALUES ( %s, %s, %d, %d )";
                            $wpdb->query($wpdb->prepare($SQL, $registration_id, $post_val, $id, $question->q_id));
                        }
                        //echo '<h4>LQ : ' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                    }
                }
                //If this is not an attendee returing to edit their details, then we need to return to the payment page
                if (!isset($_REQUEST['single'])) {
                    if (espresso_registration_id($req_primary) == $registration_id && espresso_registration_id($id) == $registration_id) {
                        return events_payment_page($req_primary);
                        exit;
                    } else {
                        _e('Sorry, it seems there was an error verifying the attendee id or primary attendee id record.', 'event_espresso');
                        return;
                    }
                }
            }
        } else {
            $display_attendee_form = FALSE;
        }
        ?>

	<div id="edit-attendee-record-dv" class="event-display-boxes ui-widget">
		<h3 class="event_title ui-widget-header ui-corner-top">
			<?php 
        _e('Edit Registration', 'event_espresso');
        ?>
		</h3>
		<div class="event_espresso_form_wrapper event-data-display ui-widget-content ui-corner-bottom">

<?php 
        if ($display_attendee_form) {
            ?>

			
			<p>
				<strong><?php 
            _e('Event:', 'event_espresso');
            ?>
</strong> <?php 
            echo $event_name;
            ?>
			</p>
			
			<form method="post" action="<?php 
            echo home_url();
            ?>
/?page_id=<?php 
            echo $org_options['event_page_id'];
            ?>
" class="espresso_form" id="registration_form">
<?php 
            if (count($question_groups) > 0) {
                $questions_in = '';
                foreach ($question_groups as $g_id) {
                    $questions_in .= $g_id . ',';
                }
                $questions_in = substr($questions_in, 0, -1);
                //					echo '<h4>$questions_in : ' . $questions_in . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                $FILTER = isset($event_meta['additional_attendee_reg_info']) && $event_meta['additional_attendee_reg_info'] == '2' && isset($_REQUEST['attendee_num']) && $_REQUEST['attendee_num'] > 1 ? ' AND qg.system_group = 1 ' : '';
                //pull the list of questions that are relevant to this event
                $SQL = "SELECT q.*, q.id AS q_id, at.*, qg.group_name, qg.show_group_description, qg.show_group_name ";
                $SQL .= "FROM " . EVENTS_QUESTION_TABLE . " q ";
                $SQL .= "LEFT JOIN " . EVENTS_ANSWER_TABLE . " at on q.id = at.question_id ";
                $SQL .= "JOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id ";
                $SQL .= "JOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id ";
                $SQL .= "WHERE qg.id in ( {$questions_in} ) ";
                $SQL .= "AND (  at.attendee_id IS NULL OR at.attendee_id = %d ) ";
                $SQL .= "AND q.admin_only != 'Y' ";
                $SQL .= $FILTER;
                $SQL .= "ORDER BY qg.group_order, qg.id, q.sequence ASC";
                if ($questions = $wpdb->get_results($wpdb->prepare($SQL, $id))) {
                    //						printr( $questions, '$questions  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
                    //						echo '<h4>last_query : ' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                    //Output the questions
                    $question_displayed = array();
                    $group_name = '';
                    $counter = 0;
                    $total_questions = count($questions);
                    foreach ($questions as $question) {
                        if (!in_array($question->id, $question_displayed)) {
                            $question_displayed[] = $question->id;
                            // if question group has changed, close prev group tags
                            echo $group_name != '' && $group_name != $question->group_name ? '
					</fieldset>
				</div>' : '';
                            // new group ?
                            if ($group_name != $question->group_name) {
                                $question->group_identifier = !empty($question->group_identifier) ? ' id="' . $question->group_identifier . '"' : '';
                                $question->group_description = !empty($question->group_description) ? $question->group_description : '';
                                echo '
				<div class="event_questions"' . $question->group_identifier . '>
					<fieldset>';
                                echo $question->show_group_name != 0 ? '
						<h3 class="section-title">' . $question->group_name . '</h3>' : '';
                                echo $question->show_group_description != 0 && $question->group_description != '' ? '
						<p>
							' . $question->group_description . '
						</p>' : '';
                                $group_name = $question->group_name;
                            }
                            echo event_form_build_edit($question, $question->answer, $show_admin_only = FALSE);
                            $counter++;
                            echo $counter == $total_questions ? '
					</fieldset>
				</div>' : '';
                        }
                    }
                }
                //end questions display
            }
            //	registration_id=1-5072fa1b52696
            //	id=318
            //	regevent_action=register
            //	form_action=edit_attendee
            //	primary=318
            //	event_id=1
            //	coupon_code=
            //	groupon_code=
            //	attendee_num=1
            ?>

				<input type="hidden" name="id" value="<?php 
            echo $id;
            ?>
" />
				<input type="hidden" name="r_id" value="<?php 
            echo $registration_id;
            ?>
" />
				<input type="hidden" name="event_id" value="<?php 
            echo $event_id;
            ?>
" />
				<input type="hidden" name="attendee_action" value="update_attendee" />
				<input type="hidden" name="regevent_action" value="edit_attendee" />
				<input type="hidden" name="primary" value="<?php 
            echo $req_primary;
            ?>
" />
				
				<p class="event_form_submit">
					<input class="event-form-submit-btn" type="submit" name="submit" value="<?php 
            _e('Update Record', 'event_espresso');
            ?>
" />
				</p>
				
			</form>
			
<?php 
        } else {
            ?>
	
			<div class="event_espresso_error">
				<h3><?php 
            _e('An error occured.', 'event_espresso');
            ?>
</h3>
				<p>
					<?php 
            _e('The requested attendee data could not be found.<br/>Please refresh the page and try again or contact the site admin if problem\'s persist.', 'event_espresso');
            ?>
				</p>
			</div>
	
<?php 
        }
        ?>

		</div><!-- / .event-display-boxes -->
	</div><!-- / .event_espresso_form_wrapper .event-data-display -->

<?php 
    } else {
        _e('No attendee record was found.', 'event_espresso');
    }
}
 function event_espresso_send_payment_notification($atts)
 {
     do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
     global $wpdb, $org_options;
     //Extract the attendee_id and registration_id
     extract($atts);
     $registration_id = is_array($registration_id) ? $registration_id[0] : $registration_id;
     if (empty($registration_id) && isset($attendee_id)) {
         $registration_id = espresso_registration_id($attendee_id);
     }
     if (empty($registration_id)) {
         return __('No Registration ID was supplied', 'event_espresso');
     }
     //Get the attendee  id or registration_id and create the sql statement
     $SQL = "SELECT a.* FROM " . EVENTS_ATTENDEE_TABLE . " a ";
     $SQL .= " WHERE a.registration_id = %s ";
     $attendees = $wpdb->get_results($wpdb->prepare($SQL, $registration_id));
     if ($org_options['default_mail'] == 'Y') {
         foreach ($attendees as $attendee) {
             event_espresso_email_confirmations(array('attendee_id' => $attendee->id, 'send_admin_email' => 'false', 'send_attendee_email' => 'true', 'custom_data' => array('email_type' => 'payment', 'payment_subject' => $org_options['payment_subject'], 'payment_message' => $org_options['payment_message'])));
         }
     }
     return;
 }
function espresso_process_paypal_pro($payment_data)
{
    extract($payment_data);
    global $wpdb;
    // Included required files.
    require_once 'includes/paypal.nvp.class.php';
    $paypal_pro_settings = get_option('event_espresso_paypal_pro_settings');
    $sandbox = $paypal_pro_settings['paypal_pro_use_sandbox'];
    // Setup PayPal object
    $PayPalConfig = array('Sandbox' => $sandbox, 'APIUsername' => $paypal_pro_settings['paypal_api_username'], 'APIPassword' => $paypal_pro_settings['paypal_api_password'], 'APISignature' => $paypal_pro_settings['paypal_api_signature']);
    $PayPal = new PayPal($PayPalConfig);
    //Find the correct amount so that unsavory characters don't change it in the previous form
    $sql = "SELECT ea.amount_pd, ed.event_name FROM " . EVENTS_ATTENDEE_TABLE . " ea ";
    $sql .= "JOIN " . EVENTS_DETAIL_TABLE . " ed ";
    $sql .= "ON ed.id = ea.event_id ";
    $sql .= " WHERE registration_id = '" . espresso_registration_id($_POST['id']) . "' ";
    $sql .= " ORDER BY ea.id ASC LIMIT 1";
    $r = $wpdb->get_row($sql);
    if (!$r || $wpdb->num_rows == 0) {
        exit("Looks like something went wrong.  Please try again or notify the website administrator.");
    }
    // Populate data arrays with order data.
    $DPFields = array('paymentaction' => 'Sale', 'ipaddress' => $_SERVER['REMOTE_ADDR'], 'returnfmfdetails' => '1');
    $CCDetails = array('creditcardtype' => $_POST['creditcardtype'], 'acct' => $_POST['card_num'], 'expdate' => $_POST['expmonth'] . $_POST['expyear'], 'cvv2' => $_POST['cvv'], 'startdate' => '', 'issuenumber' => '');
    $PayerInfo = array('email' => $_POST['email'], 'payerid' => '', 'payerstatus' => '', 'business' => '');
    $PayerName = array('salutation' => '', 'firstname' => $_POST['first_name'], 'middlename' => '', 'lastname' => $_POST['last_name'], 'suffix' => '');
    $BillingAddress = array('street' => $_POST['address'], 'street2' => '', 'city' => $_POST['city'], 'state' => $_POST['state'], 'countrycode' => 'US', 'zip' => $_POST['zip'], 'phonenum' => empty($_POST['phone']) ? '' : $_POST['phone']);
    $ShippingAddress = array('shiptoname' => '', 'shiptostreet' => '', 'shiptostreet2' => '', 'shiptocity' => '', 'shiptostate' => '', 'shiptozip' => '', 'shiptocountrycode' => '', 'shiptophonenum' => '');
    $PaymentDetails = array('amt' => $r->amount_pd, 'currencycode' => $paypal_pro_settings['currency_format'], 'itemamt' => '', 'shippingamt' => '', 'handlingamt' => '', 'taxamt' => '', 'desc' => stripslashes_deep($r->event_name), 'custom' => '', 'invnum' => '', 'notifyurl' => '');
    $OrderItems = array();
    $Item = array('l_name' => stripslashes_deep($r->event_name), 'l_desc' => stripslashes_deep($r->event_name), 'l_amt' => $_POST['amount'], 'l_number' => '', 'l_qty' => '1', 'l_taxamt' => '', 'l_ebayitemnumber' => '', 'l_ebayitemauctiontxnid' => '', 'l_ebayitemorderid' => '');
    array_push($OrderItems, $Item);
    // Wrap all data arrays into a single, "master" array which will be passed into the class function.
    $PayPalRequestData = array('DPFields' => $DPFields, 'CCDetails' => $CCDetails, 'PayerName' => $PayerName, 'BillingAddress' => $BillingAddress, 'PaymentDetails' => $PaymentDetails, 'OrderItems' => $OrderItems);
    $PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData);
    $payment_data['payment_status'] = 'Incomplete';
    $payment_data['txn_type'] = 'PPP';
    $payment_data['txn_id'] = 0;
    $payment_data['txn_details'] = serialize($_REQUEST);
    $payment_data = apply_filters('filter_hook_espresso_prepare_event_link', $payment_data);
    $payment_data = apply_filters('filter_hook_espresso_get_total_cost', $payment_data);
    $Errors = GetErrors($PayPalResult);
    if (!empty($PayPalResult)) {
        $payment_data['txn_id'] = $PayPalResult['TRANSACTIONID'];
        $payment_data['txn_details'] = serialize($PayPalResult);
        if (!APICallSuccessful($PayPalResult['ACK'])) {
            DisplayErrors($Errors);
        } else {
            $payment_data['payment_status'] = 'Completed';
        }
    } else {
        ?>
		<p><?php 
        _e('There was no response from Paypal.', 'event_espresso');
        ?>
</p>
		<?php 
    }
    $payment_data = apply_filters('filter_hook_espresso_update_attendee_payment_data_in_db', $payment_data);
    do_action('action_hook_espresso_email_after_payment', $payment_data);
    return $payment_data;
}