Example #1
0
 function get_bookings($ids_only = false, $status = false)
 {
     global $wpdb;
     $status_condition = $blog_condition = '';
     if (is_multisite()) {
         if (!is_main_site()) {
             //not the main blog, force single blog search
             $blog_condition = "AND e.blog_id=" . get_current_blog_id();
         } elseif (is_main_site() && !get_option('dbem_ms_global_events')) {
             $blog_condition = "AND (e.blog_id=" . get_current_blog_id() . ' OR e.blog_id IS NULL)';
         }
     }
     if (is_numeric($status)) {
         $status_condition = " AND booking_status={$status}";
     } elseif (EM_Object::array_is_numeric($status)) {
         $status_condition = " AND booking_status IN (" . implode(',', $status) . ")";
     }
     $EM_Booking = em_get_booking();
     //empty booking for fields
     $results = $wpdb->get_results("SELECT b." . implode(', b.', array_keys($EM_Booking->fields)) . " FROM " . EM_BOOKINGS_TABLE . " b, " . EM_EVENTS_TABLE . " e WHERE e.event_id=b.event_id AND person_id={$this->ID} {$blog_condition} {$status_condition} ORDER BY " . get_option('dbem_bookings_default_orderby', 'event_start_date') . " " . get_option('dbem_bookings_default_order', 'ASC'), ARRAY_A);
     $bookings = array();
     if ($ids_only) {
         foreach ($results as $booking_data) {
             $bookings[] = $booking_data['booking_id'];
         }
         return apply_filters('em_person_get_bookings', $bookings, $this);
     } else {
         foreach ($results as $booking_data) {
             $bookings[] = em_get_booking($booking_data);
         }
         return apply_filters('em_person_get_bookings', new EM_Bookings($bookings), $this);
     }
 }
 /**
  * Run on init, actions that need taking regarding offline bookings are caught here, e.g. registering manual bookings and adding payments 
  */
 function actions()
 {
     global $EM_Notices, $EM_Booking, $EM_Event, $wpdb;
     //Check if manual payment has been added
     if (!empty($_REQUEST['booking_id']) && !empty($_REQUEST['action']) && !empty($_REQUEST['_wpnonce'])) {
         $EM_Booking = em_get_booking($_REQUEST['booking_id']);
         if ($_REQUEST['action'] == 'gateway_add_payment' && is_object($EM_Booking) && wp_verify_nonce($_REQUEST['_wpnonce'], 'gateway_add_payment')) {
             if (!empty($_REQUEST['transaction_total_amount']) && is_numeric($_REQUEST['transaction_total_amount'])) {
                 $this->record_transaction($EM_Booking, $_REQUEST['transaction_total_amount'], get_option('dbem_bookings_currency'), current_time('mysql'), '', 'Completed', $_REQUEST['transaction_note']);
                 $string = __('Payment has been registered.', 'em-pro');
                 $total = $wpdb->get_var('SELECT SUM(transaction_total_amount) FROM ' . EM_TRANSACTIONS_TABLE . " WHERE booking_id={$EM_Booking->booking_id}");
                 if ($total >= $EM_Booking->get_price()) {
                     $EM_Booking->approve();
                     $string .= " " . __('Booking is now fully paid and confirmed.', 'em-pro');
                 }
                 $EM_Notices->add_confirm($string, true);
                 do_action('em_payment_processed', $EM_Booking, $this);
                 wp_redirect(wp_get_referer());
                 exit;
             } else {
                 $EM_Notices->add_error(__('Please enter a valid payment amount. Numbers only, use negative number to credit a booking.', 'em-pro'));
                 unset($_REQUEST['action']);
                 unset($_POST['action']);
             }
         }
     }
 }
 function get_bookings($force_refresh = false)
 {
     global $wpdb;
     if (empty($this->bookings) || $force_refresh) {
         //get bookings related to this object and load into $bookings object
         if (!empty($this->booking_id)) {
             $booking_relationships = $wpdb->get_results("SELECT booking_id, event_id FROM " . EM_BOOKINGS_RELATIONSHIPS_TABLE . " WHERE booking_main_id='{$this->booking_id}'", ARRAY_A);
             $bookings = array();
             foreach ($booking_relationships as $booking_data) {
                 $EM_Booking = em_get_booking($booking_data['booking_id']);
                 if ($EM_Booking->booking_id != 0) {
                     //in case there's a booking that was already deleted
                     $this->bookings[$booking_data['event_id']] = $EM_Booking;
                 }
             }
         }
     }
     return $this->bookings;
 }
Example #4
0
/**
 * Not yet used fully - formats booking-related actions
 * @param string $action
 * @param object $activity
 * @return string
 */
function em_bp_events_format_activity_action_bookings($action, $activity)
{
    return '';
    $member_link = bp_core_get_userlink($activity->user_id);
    $EM_Booking = em_get_booking($activity->item);
    $action = '';
    switch ($activity->type) {
        case 'new_booking':
            if ($activity->component == 'groups') {
                $action = sprintf(__('%s is attending %s of the group %s.', 'dbem'), $member_link, $event_link, $group_link);
            } else {
                $action = sprintf(__('%s is attending %s.', 'dbem'), $member_link, $event_link);
            }
            break;
        case 'cancelled_booking':
            if ($activity->component == 'groups') {
                $action = sprintf(__('%s will not be attending %s of group %s anymore.', 'dbem'), $user_link, $event_link, $group_link);
            } else {
                $action = sprintf(__('%s will not be attending %s anymore.', 'dbem'), $user_link, $event_link);
            }
            break;
    }
    return apply_filters('bp_events_format_activity_action_bookings', $action, $activity);
}
 /**
  * Smart booking locator, saves a database read if possible.
  * @return EM_Booking 
  */
 function get_booking()
 {
     global $EM_Booking;
     if (is_object($this->booking) && get_class($this->booking) == 'EM_Booking' && ($this->booking->booking_id == $this->booking_id || empty($this->ticket_booking_id) && empty($this->booking_id))) {
         return $this->booking;
     } elseif (is_object($EM_Booking) && $EM_Booking->booking_id == $this->booking_id) {
         $this->booking = $EM_Booking;
     } else {
         if (is_numeric($this->booking_id)) {
             $this->booking = em_get_booking($this->booking_id);
         } else {
             $this->booking = em_get_booking();
         }
     }
     return apply_filters('em_ticket_booking_get_booking', $this->booking, $this);
 }
 /**
  * Runs when PayPal sends IPNs to the return URL provided during bookings and EM setup.
  * Bookings are updated and transactions are recorded accordingly.
  */
 function handle_payment_return()
 {
     // Read POST data
     // reading posted data directly from $_POST causes serialization issues with
     // array data in POST. Reading raw POST data from input stream instead.
     $raw_post_data = file_get_contents('php://input');
     $post = $this->decodePayPalIPN($raw_post_data);
     // PayPal IPN handling code
     if ((isset($post['status']) || isset($post['transaction_type'])) && isset($post['tracking_id'])) {
         //Verify IPN request
         if (get_option('em_' . $this->gateway . "_status") == 'live') {
             $domain = 'https://www.paypal.com/cgi-bin/webscr';
         } else {
             $domain = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
         }
         $req = 'cmd=_notify-validate&' . $raw_post_data;
         @set_time_limit(60);
         //add a CA certificate so that SSL requests always go through
         add_action('http_api_curl', 'EM_Gateway_Paypal_Chained::payment_return_local_ca_curl', 10, 1);
         //using WP's HTTP class
         $ipn_verification_result = wp_remote_get($domain . '?' . $req, array('httpversion', '1.1'));
         remove_action('http_api_curl', 'EM_Gateway_Paypal_Chained::payment_return_local_ca_curl', 10, 1);
         if (!is_wp_error($ipn_verification_result) && $ipn_verification_result['body'] == 'VERIFIED') {
             //log ipn request if needed, then move on
             EM_Pro::log($post['transaction_type'] . " successfully received for {$post['transaction'][0]['amount']} (TXN ID {$post['transaction'][0]['id']}) - Booking: {$post['tracking_id']}", 'paypal_chained');
         } else {
             //log error if needed, send error header and exit
             EM_Pro::log(array('IPN Verification Error', 'WP_Error' => $ipn_verification_result, '$_POST' => $post, '$req' => $domain . '?' . $req), 'paypal_chained');
             header('HTTP/1.0 502 Bad Gateway');
             exit;
         }
         //if we get past this, then the IPN went ok
         // handle cases that the system must ignore
         //Common variables
         $primary_transaction = null;
         // Locate primary transaction:
         foreach ($post['transaction'] as $transaction) {
             if ($transaction['is_primary_receiver']) {
                 $primary_transaction = $transaction;
                 break;
             }
         }
         // We're interested in the primary receiver transaction as that is the main payment for the booking
         // Any subsequent receivers is just the money being distributed based on the the em_gateway_paypal_chained_receivers hook
         // As we don't know what they could be we won't try to save that information
         $currency_amount = explode(' ', $primary_transaction['amount']);
         $amount = $currency_amount[1];
         $currency = $currency_amount[0];
         $timestamp = date('Y-m-d H:i:s', strtotime($post['payment_request_date']));
         $booking_id = $post['tracking_id'];
         $EM_Booking = em_get_booking($booking_id);
         if (!empty($EM_Booking->booking_id)) {
             //booking exists
             $EM_Booking->manage_override = true;
             //since we're overriding the booking ourselves.
             $user_id = $EM_Booking->person_id;
             // process PayPal response
             switch ($primary_transaction['status']) {
                 case 'Completed':
                     // case: successful payment
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $primary_transaction['id'], $primary_transaction['status'], '');
                     if ($amount >= $EM_Booking->get_price() && (!get_option('em_' . $this->gateway . '_manual_approval', false) || !get_option('dbem_bookings_approval'))) {
                         $EM_Booking->approve(true, true);
                         //approve and ignore spaces
                     } else {
                         //TODO do something if pp payment not enough
                         $EM_Booking->set_status(0);
                         //Set back to normal "pending"
                     }
                     do_action('em_payment_processed', $EM_Booking, $this);
                     break;
                 case 'Error':
                     $note = 'The payment failed and all attempted transfers failed or all completed transfers were successfully reversed';
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $primary_transaction['id'], $primary_transaction['status'], $note);
                     $EM_Booking->cancel();
                     do_action('em_payment_denied', $EM_Booking, $this);
                     break;
                 case 'Processing':
                 case 'Pending':
                     // case: payment is pending
                     $pending_str = array('address' => 'Customer did not include a confirmed shipping address', 'authorization' => 'Funds not captured yet', 'echeck' => 'eCheck that has not cleared yet', 'intl' => 'Payment waiting for aproval by service provider', 'multi-currency' => 'Payment waiting for service provider to handle multi-currency process', 'unilateral' => 'Customer did not register or confirm his/her email yet', 'upgrade' => 'Waiting for service provider to upgrade the PayPal account', 'verify' => 'Waiting for service provider to verify his/her PayPal account', 'paymentreview' => 'Paypal is currently reviewing the payment and will approve or reject within 24 hours', '*' => '');
                     $reason = @$primary_transaction['pending_reason'];
                     $note = 'Last transaction is pending. Reason: ' . (isset($pending_str[$reason]) ? $pending_str[$reason] : $pending_str['*']);
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $primary_transaction['id'], $primary_transaction['status'], $note);
                     do_action('em_payment_pending', $EM_Booking, $this);
                     break;
                 case 'Reversed':
                     // case: charge back
                     $note = 'Last transaction has been reversed. Reason: Payment has been reversed (charge back)';
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $primary_transaction['id'], $primary_transaction['status'], $note);
                     //We need to cancel their booking.
                     $EM_Booking->cancel();
                     do_action('em_payment_reversed', $EM_Booking, $this);
                     break;
                 case 'Refunded':
                     // case: refund
                     $note = 'Last transaction has been reversed. Reason: Payment has been refunded';
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $primary_transaction['id'], $primary_transaction['status'], $note);
                     if ($EM_Booking->get_price() >= $amount) {
                         $EM_Booking->cancel();
                     } else {
                         $EM_Booking->set_status(0);
                         //Set back to normal "pending"
                     }
                     do_action('em_payment_refunded', $EM_Booking, $this);
                     break;
                 default:
                     // case: various error cases
                     // https://developer.paypal.com/docs/classic/api/adaptive-payments/PaymentDetails_API_Operation/
             }
         } else {
             if (is_numeric($booking_id) && $primary_transaction['status'] == 'Completed') {
                 $message = apply_filters('em_gateway_paypal_chained_bad_booking_email', "\nA Payment has been received by PayPal for a non-existent booking.\n\nIt may be that this user's booking has timed out yet they proceeded with payment at a later stage.\n\nIn some cases, it could be that other payments not related to Events Manager are triggering this error. If that's the case, you can prevent this from happening by changing the URL in your IPN settings to:\n\n" . get_home_url() . "\n\nTo refund this transaction, you must go to your PayPal account and search for this transaction:\n\nTransaction ID : %transaction_id%\nEmail : %payer_email%\n\nWhen viewing the transaction details, you should see an option to issue a refund.\n\nIf there is still space available, the user must book again.\n\nSincerely,\nEvents Manager\n\t\t\t\t\t", $booking_id);
                 $message = str_replace(array('%transaction_id%', '%payer_email%'), array($primary_transaction['id'], $post['sender_email']), $message);
                 wp_mail(get_option('em_' . $this->gateway . "_email"), __('Unprocessed payment needs refund'), $message);
             } else {
                 //header('Status: 404 Not Found');
                 $error = 'Error: Bad IPN request, custom ID does not correspond with any pending booking.';
                 echo $error;
                 error_log($error);
                 exit;
             }
         }
         //fclose($log);
     } else {
         // Did not find expected POST variables. Possible access attempt from a non PayPal site.
         //header('Status: 404 Not Found');
         echo 'Error: Missing POST variables. Identification is not possible. If you are not PayPal and are visiting this page directly in your browser, this error does not indicate a problem, but simply means EM is correctly set up and ready to receive IPNs from PayPal only.';
         error_log('PayPal Chained IPN error: Missing POST variables. Identification is not possible.');
         exit;
     }
 }
 /**
  * Runs when PayPal sends IPNs to the return URL provided during bookings and EM setup. Bookings are updated and transactions are recorded accordingly. 
  */
 function handle_payment_return()
 {
     // PayPal IPN handling code
     if ((isset($_POST['payment_status']) || isset($_POST['txn_type'])) && isset($_POST['custom'])) {
         //Verify IPN request
         if (get_option('em_' . $this->gateway . "_status") == 'live') {
             $domain = 'https://www.paypal.com/cgi-bin/webscr';
         } else {
             $domain = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
         }
         $req = 'cmd=_notify-validate';
         if (!isset($_POST)) {
             $_POST = $HTTP_POST_VARS;
         }
         foreach ($_POST as $k => $v) {
             $req .= '&' . $k . '=' . urlencode(stripslashes($v));
         }
         @set_time_limit(60);
         //add a CA certificate so that SSL requests always go through
         add_action('http_api_curl', 'EM_Gateway_Paypal::payment_return_local_ca_curl', 10, 1);
         //using WP's HTTP class
         $ipn_verification_result = wp_remote_get($domain . '?' . $req, array('httpversion', '1.1'));
         remove_action('http_api_curl', 'EM_Gateway_Paypal::payment_return_local_ca_curl', 10, 1);
         if (!is_wp_error($ipn_verification_result) && $ipn_verification_result['body'] == 'VERIFIED') {
             //log ipn request if needed, then move on
             EM_Pro::log($_POST['payment_status'] . " successfully received for {$_POST['mc_gross']} {$_POST['mc_currency']} (TXN ID {$_POST['txn_id']}) - Custom Info: {$_POST['custom']}", 'paypal');
         } else {
             //log error if needed, send error header and exit
             EM_Pro::log(array('IPN Verification Error', 'WP_Error' => $ipn_verification_result, '$_POST' => $_POST, '$req' => $domain . '?' . $req), 'paypal');
             header('HTTP/1.0 502 Bad Gateway');
             exit;
         }
         //if we get past this, then the IPN went ok
         // handle cases that the system must ignore
         $new_status = false;
         //Common variables
         $amount = $_POST['mc_gross'];
         $currency = $_POST['mc_currency'];
         $timestamp = date('Y-m-d H:i:s', strtotime($_POST['payment_date']));
         $custom_values = explode(':', $_POST['custom']);
         $booking_id = $custom_values[0];
         $event_id = !empty($custom_values[1]) ? $custom_values[1] : 0;
         $EM_Booking = em_get_booking($booking_id);
         if (!empty($EM_Booking->booking_id) && count($custom_values) == 2) {
             //booking exists
             $EM_Booking->manage_override = true;
             //since we're overriding the booking ourselves.
             $user_id = $EM_Booking->person_id;
             // process PayPal response
             switch ($_POST['payment_status']) {
                 case 'Partially-Refunded':
                     break;
                 case 'Completed':
                 case 'Processed':
                     // case: successful payment
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $_POST['txn_id'], $_POST['payment_status'], '');
                     if ($_POST['mc_gross'] >= $EM_Booking->get_price() && (!get_option('em_' . $this->gateway . '_manual_approval', false) || !get_option('dbem_bookings_approval'))) {
                         $EM_Booking->approve(true, true);
                         //approve and ignore spaces
                     } else {
                         //TODO do something if pp payment not enough
                         $EM_Booking->set_status(0);
                         //Set back to normal "pending"
                     }
                     do_action('em_payment_processed', $EM_Booking, $this);
                     break;
                 case 'Reversed':
                     // case: charge back
                     $note = 'Last transaction has been reversed. Reason: Payment has been reversed (charge back)';
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $_POST['txn_id'], $_POST['payment_status'], $note);
                     //We need to cancel their booking.
                     $EM_Booking->cancel();
                     do_action('em_payment_reversed', $EM_Booking, $this);
                     break;
                 case 'Refunded':
                     // case: refund
                     $note = 'Last transaction has been reversed. Reason: Payment has been refunded';
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $_POST['txn_id'], $_POST['payment_status'], $note);
                     if ($EM_Booking->get_price() >= $amount) {
                         $EM_Booking->cancel();
                     } else {
                         $EM_Booking->set_status(0);
                         //Set back to normal "pending"
                     }
                     do_action('em_payment_refunded', $EM_Booking, $this);
                     break;
                 case 'Denied':
                     // case: denied
                     $note = 'Last transaction has been reversed. Reason: Payment Denied';
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $_POST['txn_id'], $_POST['payment_status'], $note);
                     $EM_Booking->cancel();
                     do_action('em_payment_denied', $EM_Booking, $this);
                     break;
                 case 'In-Progress':
                 case 'Pending':
                     // case: payment is pending
                     $pending_str = array('address' => 'Customer did not include a confirmed shipping address', 'authorization' => 'Funds not captured yet', 'echeck' => 'eCheck that has not cleared yet', 'intl' => 'Payment waiting for aproval by service provider', 'multi-currency' => 'Payment waiting for service provider to handle multi-currency process', 'unilateral' => 'Customer did not register or confirm his/her email yet', 'upgrade' => 'Waiting for service provider to upgrade the PayPal account', 'verify' => 'Waiting for service provider to verify his/her PayPal account', 'paymentreview' => 'Paypal is currently reviewing the payment and will approve or reject within 24 hours', '*' => '');
                     $reason = @$_POST['pending_reason'];
                     $note = 'Last transaction is pending. Reason: ' . (isset($pending_str[$reason]) ? $pending_str[$reason] : $pending_str['*']);
                     $this->record_transaction($EM_Booking, $amount, $currency, $timestamp, $_POST['txn_id'], $_POST['payment_status'], $note);
                     do_action('em_payment_pending', $EM_Booking, $this);
                     break;
                 default:
                     // case: various error cases
             }
         } else {
             if (is_numeric($event_id) && is_numeric($booking_id) && ($_POST['payment_status'] == 'Completed' || $_POST['payment_status'] == 'Processed')) {
                 $message = apply_filters('em_gateway_paypal_bad_booking_email', "\nA Payment has been received by PayPal for a non-existent booking. \n\nEvent Details : %event%\n\nIt may be that this user's booking has timed out yet they proceeded with payment at a later stage. \n\t\t\t\t\t\t\t\nIn some cases, it could be that other payments not related to Events Manager are triggering this error. If that's the case, you can prevent this from happening by changing the URL in your IPN settings to:\n\n" . get_home_url() . " \n\nTo refund this transaction, you must go to your PayPal account and search for this transaction:\n\nTransaction ID : %transaction_id%\nEmail : %payer_email%\n\nWhen viewing the transaction details, you should see an option to issue a refund.\n\nIf there is still space available, the user must book again.\n\nSincerely,\nEvents Manager\n\t\t\t\t\t", $booking_id, $event_id);
                 $EM_Event = new EM_Event($event_id);
                 $event_details = $EM_Event->name . " - " . date_i18n(get_option('date_format'), $EM_Event->start);
                 $message = str_replace(array('%transaction_id%', '%payer_email%', '%event%'), array($_POST['txn_id'], $_POST['payer_email'], $event_details), $message);
                 wp_mail(get_option('em_' . $this->gateway . "_email"), __('Unprocessed payment needs refund'), $message);
             } else {
                 //header('Status: 404 Not Found');
                 echo 'Error: Bad IPN request, custom ID does not correspond with any pending booking.';
                 //echo "<pre>"; print_r($_POST); echo "</pre>";
                 exit;
             }
         }
         //fclose($log);
     } else {
         // Did not find expected POST variables. Possible access attempt from a non PayPal site.
         //header('Status: 404 Not Found');
         echo 'Error: Missing POST variables. Identification is not possible. If you are not PayPal and are visiting this page directly in your browser, this error does not indicate a problem, but simply means EM is correctly set up and ready to receive IPNs from PayPal only.';
         exit;
     }
 }
Example #8
0
 /**
  * Get bookings that match the array of arguments passed.
  * @return array 
  * @static
  */
 public static function get($args = array(), $count = false)
 {
     global $wpdb, $current_user;
     $bookings_table = EM_BOOKINGS_TABLE;
     $events_table = EM_EVENTS_TABLE;
     $locations_table = EM_LOCATIONS_TABLE;
     //Quick version, we can accept an array of IDs, which is easy to retrieve
     if (self::array_is_numeric($args)) {
         //Array of numbers, assume they are event IDs to retreive
         //We can just get all the events here and return them
         $sql = "\n\t\t\t\tSELECT * FROM {$bookings_table} b \n\t\t\t\tLEFT JOIN {$events_table} e ON e.event_id=b.event_id \n\t\t\t\tWHERE booking_id" . implode(" OR booking_id=", $args);
         $results = $wpdb->get_results(apply_filters('em_bookings_get_sql', $sql), ARRAY_A);
         $bookings = array();
         foreach ($results as $result) {
             $bookings[] = em_get_booking($result);
         }
         return $bookings;
         //We return all the bookings matched as an EM_Booking array.
     }
     //We assume it's either an empty array or array of search arguments to merge with defaults
     $args = self::get_default_search($args);
     $limit = $args['limit'] && is_numeric($args['limit']) ? "LIMIT {$args['limit']}" : '';
     $offset = $limit != "" && is_numeric($args['offset']) ? "OFFSET {$args['offset']}" : '';
     //Get the default conditions
     $conditions = self::build_sql_conditions($args);
     //Put it all together
     $where = count($conditions) > 0 ? " WHERE " . implode(" AND ", $conditions) : '';
     //Get ordering instructions
     $EM_Booking = em_get_booking();
     $accepted_fields = $EM_Booking->get_fields(true);
     $accepted_fields['date'] = 'booking_date';
     $orderby = self::build_sql_orderby($args, $accepted_fields);
     //Now, build orderby sql
     $orderby_sql = count($orderby) > 0 ? 'ORDER BY ' . implode(', ', $orderby) : 'ORDER BY booking_date';
     //Selector
     $selectors = $count ? 'COUNT(*)' : '*';
     //Create the SQL statement and execute
     $sql = "\n\t\t\tSELECT {$selectors} FROM {$bookings_table} \n\t\t\tLEFT JOIN {$events_table} ON {$events_table}.event_id={$bookings_table}.event_id \n\t\t\tLEFT JOIN {$locations_table} ON {$locations_table}.location_id={$events_table}.location_id\n\t\t\t{$where}\n\t\t\t{$orderby_sql}\n\t\t\t{$limit} {$offset}\n\t\t";
     //If we're only counting results, return the number of results
     if ($count) {
         return apply_filters('em_bookings_get_count', $wpdb->get_var($sql), $args);
     }
     $results = $wpdb->get_results(apply_filters('em_events_get_sql', $sql, $args), ARRAY_A);
     //If we want results directly in an array, why not have a shortcut here?
     if ($args['array'] == true) {
         return $results;
     }
     //Make returned results EM_Booking objects
     $results = is_array($results) ? $results : array();
     $bookings = array();
     foreach ($results as $booking) {
         $bookings[] = em_get_booking($booking);
     }
     $EM_Bookings = new EM_Bookings($bookings);
     return apply_filters('em_bookings_get', $EM_Bookings);
 }
    static function view_page()
    {
        global $EM_Notices, $EM_Coupon, $wpdb;
        //check that user can access this page
        if (is_object($EM_Coupon) && !$EM_Coupon->can_manage('manage_bookings', 'manage_others_bookings')) {
            ?>
			<div class="wrap"><h2><?php 
            esc_html_e_emp('Unauthorized Access', 'dbem');
            ?>
</h2><p><?php 
            echo sprintf(esc_html__emp('You do not have the rights to manage this %s.', 'dbem'), __('coupon', 'em-pro'));
            ?>
</p></div>
			<?php 
            return false;
        } elseif (!is_object($EM_Coupon)) {
            $EM_Coupon = new EM_Coupon();
        }
        $limit = !empty($_GET['limit']) ? $_GET['limit'] : 20;
        //Default limit
        $page = !empty($_GET['pno']) ? $_GET['pno'] : 1;
        $offset = $page > 1 ? ($page - 1) * $limit : 0;
        //a bit hacky, but this is the only way at least for now
        $coupon_search = str_replace('a:1:{', '', serialize(array('coupon_code' => $EM_Coupon->coupon_code)));
        $coupon_search = substr($coupon_search, 0, strlen($coupon_search) - 1);
        $bookings = $wpdb->get_col('SELECT booking_id FROM ' . EM_BOOKINGS_TABLE . " WHERE booking_meta LIKE '%{$coupon_search}%' LIMIT {$limit} OFFSET {$offset}");
        //FIXME : coupon count not syncing correctly, using this as a fallback
        $coupons_count = $wpdb->get_var('SELECT COUNT(*) FROM ' . EM_BOOKINGS_TABLE . " WHERE booking_meta LIKE '%{$coupon_search}%'");
        $bookings_count = 0;
        $EM_Bookings = array();
        foreach ($bookings as $booking_id) {
            $EM_Booking = em_get_booking($booking_id);
            if (!empty($EM_Booking->booking_meta['coupon'])) {
                $coupon = new EM_Coupon($EM_Booking->booking_meta['coupon']);
                if ($EM_Coupon->coupon_code == $coupon->coupon_code && $EM_Coupon->coupon_id == $coupon->coupon_id) {
                    $bookings_count++;
                    $EM_Bookings[] = $EM_Booking;
                }
            }
        }
        ?>
		<div class='wrap nosubsub'>
			<div class="icon32" id="icon-bookings"><br></div>
			<h2><?php 
        _e('Coupon Usage History', 'em-pro');
        ?>
</h2>
			<?php 
        echo $EM_Notices;
        ?>
			<p><?php 
        echo sprintf(__('You are viewing the details of coupon %s - <a href="%s">edit</a>', 'em-pro'), '<code>' . $EM_Coupon->coupon_code . '</code>', add_query_arg(array('action' => 'edit')));
        ?>
</p>
			<p>
				<strong><?php 
        echo __('Uses', 'em-pro');
        ?>
:</strong> 
				<?php 
        if (!empty($EM_Coupon->coupon_max)) {
            echo esc_html($coupons_count . ' / ' . $EM_Coupon->coupon_max);
        } else {
            echo esc_html($coupons_count . '/' . __('Unlimited', 'em-pro'));
        }
        ?>
			</p>
			<?php 
        if ($coupons_count >= $limit) {
            ?>
			<div class='tablenav'>
				<?php 
            $bookings_nav = em_admin_paginate($coupons_count, $limit, $page, array());
            echo $bookings_nav;
            ?>
				<div class="clear"></div>
			</div>
			<?php 
        }
        ?>
			<div class="clear"></div>
			<?php 
        if ($bookings_count > 0) {
            ?>
			<div class='table-wrap'>
				<table id='dbem-bookings-table' class='widefat post '>
					<thead>
						<tr>
							<th class='manage-column' scope='col'><?php 
            esc_html_e_emp('Event', 'dbem');
            ?>
</th>
							<th class='manage-column' scope='col'><?php 
            esc_html_e_emp('Booker', 'dbem');
            ?>
</th>
							<th class='manage-column' scope='col'><?php 
            esc_html_e_emp('Spaces', 'dbem');
            ?>
</th>
							<th><?php 
            _e('Original Total Price', 'em-pro');
            ?>
</th>
							<th><?php 
            _e('Coupon Discount', 'em-pro');
            ?>
</th>
							<th><?php 
            _e('Final Price', 'em-pro');
            ?>
</th>
							<th>&nbsp;</th>
						</tr>
					</thead>
					<tfoot>
						<tr>
							<th class='manage-column' scope='col'><?php 
            esc_html_e_emp('Event', 'dbem');
            ?>
</th>
							<th class='manage-column' scope='col'><?php 
            esc_html_e_emp('Booker', 'dbem');
            ?>
</th>
							<th class='manage-column' scope='col'><?php 
            esc_html_e_emp('Spaces', 'dbem');
            ?>
</th>
							<th><?php 
            _e('Original Total Price', 'em-pro');
            ?>
</th>
							<th><?php 
            _e('Coupon Discount', 'em-pro');
            ?>
</th>
							<th><?php 
            _e('Final Price', 'em-pro');
            ?>
</th>
							<th>&nbsp;</th>
						</tr>
					</tfoot>
					<tbody>
						<?php 
            foreach ($EM_Bookings as $EM_Booking) {
                ?>
							<tr>
								<td><?php 
                echo $EM_Booking->output('#_BOOKINGSLINK');
                ?>
</td>
								<td><a href="<?php 
                echo EM_ADMIN_URL;
                ?>
&amp;page=events-manager-bookings&amp;person_id=<?php 
                echo $EM_Booking->person_id;
                ?>
"><?php 
                echo $EM_Booking->person->get_name();
                ?>
</a></td>
								<td><?php 
                echo $EM_Booking->get_spaces();
                ?>
</td>
								<td><?php 
                echo em_get_currency_formatted($EM_Booking->booking_meta['original_price']);
                ?>
</td>
								<td><?php 
                echo em_get_currency_formatted($EM_Booking->booking_meta['original_price'] - $EM_Booking->get_price());
                ?>
 <em>(<?php 
                echo $EM_Coupon->get_discount_text();
                ?>
)</em></td>
								<td><?php 
                echo em_get_currency_formatted($EM_Booking->get_price());
                ?>
</td>
								<td>										
									<?php 
                $edit_url = em_add_get_params($_SERVER['REQUEST_URI'], array('booking_id' => $EM_Booking->booking_id, 'em_ajax' => null, 'em_obj' => null));
                ?>
									<?php 
                if ($EM_Booking->can_manage()) {
                    ?>
									<a class="em-bookings-edit" href="<?php 
                    echo $edit_url;
                    ?>
"><?php 
                    esc_html_e_emp('Edit/View', 'dbem');
                    ?>
</a>
									<?php 
                }
                ?>
								</td>
							</tr>
							<?php 
            }
            ?>
					</tbody>
				</table>
			</div> <!-- table-wrap -->
			<?php 
        } else {
            ?>
			<p><?php 
            _e('Your coupon hasn\'t been used yet!', 'em-pro');
            ?>
</p>
			<?php 
        }
        ?>
		</div> <!-- wrap -->
		<?php 
    }
Example #10
0
/**
 * This function will load an event into the global $EM_Event variable during page initialization, provided an event_id is given in the url via GET or POST.
 * global $EM_Recurrences also holds global array of recurrence objects when loaded in this instance for performance
 * All functions (admin and public) can now work off this object rather than it around via arguments.
 * @return null
 */
function em_load_event()
{
    global $EM_Event, $EM_Recurrences, $EM_Location, $EM_Person, $EM_Booking, $EM_Category, $EM_Ticket, $current_user;
    if (!defined('EM_LOADED')) {
        $EM_Recurrences = array();
        if (isset($_REQUEST['event_id']) && is_numeric($_REQUEST['event_id']) && !is_object($EM_Event)) {
            $EM_Event = new EM_Event($_REQUEST['event_id']);
        } elseif (isset($_REQUEST['post']) && (get_post_type($_REQUEST['post']) == 'event' || get_post_type($_REQUEST['post']) == 'event-recurring')) {
            $EM_Event = em_get_event($_REQUEST['post'], 'post_id');
        } elseif (!empty($_REQUEST['event_slug']) && EM_MS_GLOBAL && is_main_site() && !get_site_option('dbem_ms_global_events_links')) {
            // single event page for a subsite event being shown on the main blog
            global $wpdb;
            $matches = array();
            if (preg_match('/\\-([0-9]+)$/', $_REQUEST['event_slug'], $matches)) {
                $event_id = $matches[1];
            } else {
                $event_id = $wpdb->get_var('SELECT event_id FROM ' . EM_EVENTS_TABLE . " WHERE event_slug='{$_REQUEST['event_slug']}' AND blog_id!=" . get_current_blog_id());
            }
            $EM_Event = em_get_event($event_id);
        }
        if (isset($_REQUEST['location_id']) && is_numeric($_REQUEST['location_id']) && !is_object($EM_Location)) {
            $EM_Location = new EM_Location($_REQUEST['location_id']);
        } elseif (isset($_REQUEST['post']) && get_post_type($_REQUEST['post']) == 'location') {
            $EM_Location = em_get_location($_REQUEST['post'], 'post_id');
        } elseif (!empty($_REQUEST['location_slug']) && EM_MS_GLOBAL && is_main_site() && !get_site_option('dbem_ms_global_locations_links')) {
            // single event page for a subsite event being shown on the main blog
            global $wpdb;
            $matches = array();
            if (preg_match('/\\-([0-9]+)$/', $_REQUEST['location_slug'], $matches)) {
                $location_id = $matches[1];
            } else {
                $location_id = $wpdb->get_var('SELECT location_id FROM ' . EM_LOCATIONS_TABLE . " WHERE location_slug='{$_REQUEST['location_slug']}' AND blog_id!=" . get_current_blog_id());
            }
            $EM_Location = em_get_location($location_id);
        }
        if (is_user_logged_in() || !empty($_REQUEST['person_id']) && is_numeric($_REQUEST['person_id'])) {
            //make the request id take priority, this shouldn't make it into unwanted objects if they use theobj::get_person().
            if (!empty($_REQUEST['person_id'])) {
                $EM_Person = new EM_Person($_REQUEST['person_id']);
            } else {
                $EM_Person = new EM_Person(get_current_user_id());
            }
        }
        if (isset($_REQUEST['booking_id']) && is_numeric($_REQUEST['booking_id']) && !is_object($_REQUEST['booking_id'])) {
            $EM_Booking = em_get_booking($_REQUEST['booking_id']);
        }
        if (isset($_REQUEST['category_id']) && is_numeric($_REQUEST['category_id']) && !is_object($_REQUEST['category_id'])) {
            $EM_Category = new EM_Category($_REQUEST['category_id']);
        } elseif (isset($_REQUEST['category_slug']) && !is_object($EM_Category)) {
            $EM_Category = new EM_Category($_REQUEST['category_slug']);
        }
        if (isset($_REQUEST['ticket_id']) && is_numeric($_REQUEST['ticket_id']) && !is_object($_REQUEST['ticket_id'])) {
            $EM_Ticket = new EM_Ticket($_REQUEST['ticket_id']);
        }
        define('EM_LOADED', true);
    }
}
 /**
  * Handles the silent post URL
  */
 function handle_payment_return()
 {
     global $wpdb;
     //We do it post-style here, since it's an AIM/SIM mix.
     /* Uncomment the below to debug locally. Visit the response page with this uncommented to trigger a response. DONT FORGET TO COMMENT BACK!		
     		$_POST = array ( 'x_response_code' => '1', 'x_response_reason_code' => '1', 'x_response_reason_text' => 'This transaction has been approved.', 'x_avs_code' => 'P', 'x_auth_code' => '', 'x_trans_id' => '2168914272', 'x_method' => 'CC', 'x_card_type' => 'American Express', 'x_account_number' => 'XXXX0002', 'x_first_name' => '', 'x_last_name' => '', 'x_company' => '', 'x_address' => '', 'x_city' => '', 'x_state' => '', 'x_zip' => '', 'x_country' => '', 'x_phone' => '', 'x_fax' => '', 'x_email' => '*****@*****.**', 'x_invoice_num' => '', 'x_description' => 'Kenny Wayne Shepherd', 'x_type' => 'credit', 'x_cust_id' => '', 'x_ship_to_first_name' => '', 'x_ship_to_last_name' => '', 'x_ship_to_company' => '', 'x_ship_to_address' => '', 'x_ship_to_city' => '', 'x_ship_to_state' => '', 'x_ship_to_zip' => '', 'x_ship_to_country' => '', 'x_amount' => '150.00', 'x_tax' => '0.00', 'x_duty' => '0.00', 'x_freight' => '0.00', 'x_tax_exempt' => 'FALSE', 'x_po_num' => '', 'x_MD5_Hash' => '502A0D462D3A8C3677277111E59EDFC3', 'x_cvv2_resp_code' => '', 'x_cavv_response' => '', 'x_test_request' => 'false', );
     		$_POST['x_trans_id'] = '2168915121'; //enter the txn id you want to mess with
     		$_POST['x_amount'] = '0.00'; //positive number if credit, 0.00 if void
     		$_POST['x_type'] = 'void'; //credit or void
     		$_POST['x_invoice_num'] = 10; //booking_id needed if this is a credit
     		$_POST['x_MD5_Hash'] = strtoupper(md5(get_option('em_'.$this->gateway.'_md5_hash').get_option('em_'.$this->gateway.'_user_login').$_POST['x_trans_id'].$_POST['x_amount'])); //the hash a.net would send you
     		*/
     //Make sure this is Authorize.net
     $amount = empty($_POST['x_amount']) || (int) $_POST['x_amount'] == 0 ? "0.00" : $_POST['x_amount'];
     $md5_1 = strtoupper(md5(get_option('em_' . $this->gateway . '_md5_hash') . get_option('em_' . $this->gateway . '_user_login') . $_POST['x_trans_id'] . $amount));
     $md5_2 = strtoupper(md5(get_option('em_' . $this->gateway . '_md5_hash') . get_option('em_' . $this->gateway . '_api_user') . $_POST['x_trans_id'] . $amount));
     $is_authorizenet = $md5_1 == $_POST['x_MD5_Hash'] || $md5_2 == $_POST['x_MD5_Hash'];
     if (!empty($_POST['x_response_code']) && $_POST['x_response_code'] == 1 && $is_authorizenet) {
         if ($_POST['x_type'] == 'credit') {
             //Since credit has another txn id we can find a booking by invoice number / booking id and cancel the booking, record new txn.
             $EM_Booking = em_get_booking($_POST['x_invoice_num']);
             if (!empty($EM_Booking->booking_id)) {
                 $EM_Booking->cancel();
                 $amount = $amount * -1;
                 $this->record_transaction($EM_Booking, $amount, 'USD', current_time('mysql'), $_POST['x_trans_id'], __('Refunded', 'em-pro'), '');
                 echo "Transaction Processed";
             } else {
                 echo "Transaction not found";
                 //meaningful output
             }
         } elseif ($_POST['x_type'] == 'void') {
             //Find the transaction and booking, void the transaction, cancel the booking.
             $txn = $wpdb->get_row($wpdb->prepare("SELECT transaction_id, transaction_gateway_id, transaction_total_amount, booking_id FROM " . EM_TRANSACTIONS_TABLE . " WHERE transaction_gateway_id = %s AND transaction_gateway = %s ORDER BY transaction_total_amount DESC LIMIT 1", $_POST['x_trans_id'], $this->gateway), ARRAY_A);
             if (is_array($txn) && $txn['transaction_gateway_id'] == $_POST['x_trans_id'] && !empty($txn['booking_id'])) {
                 $EM_Booking = em_get_booking($txn['booking_id']);
                 $EM_Booking->cancel();
                 $wpdb->update(EM_TRANSACTIONS_TABLE, array('transaction_status' => __('Voided', 'em-pro'), 'transaction_timestamp' => current_time('mysql')), array('transaction_id' => $txn['transaction_id']));
                 echo "Transaction Processed";
             } else {
                 echo "Transaction not found";
                 //meaningful output
             }
         } else {
             echo "Unprocessed transaction - " . $this->title;
         }
     } elseif (!$is_authorizenet) {
         update_option('silent_post', $_POST);
         //for debugging, could be removed, but useful since aim provides no history on this
         echo "MD5 Hash failed.";
     } else {
         echo "Response not recognized.";
     }
 }
Example #12
0
/**
 * Performs actions on init. This works for both ajax and normal requests, the return results depends if an em_ajax flag is passed via POST or GET.
 */
function em_init_actions()
{
    global $wpdb, $EM_Notices, $EM_Event;
    if (defined('DOING_AJAX') && DOING_AJAX) {
        $_REQUEST['em_ajax'] = true;
    }
    //NOTE - No EM objects are globalized at this point, as we're hitting early init mode.
    //TODO Clean this up.... use a uniformed way of calling EM Ajax actions
    if (!empty($_REQUEST['em_ajax']) || !empty($_REQUEST['em_ajax_action'])) {
        if (isset($_REQUEST['em_ajax_action']) && $_REQUEST['em_ajax_action'] == 'get_location') {
            if (isset($_REQUEST['id'])) {
                $EM_Location = new EM_Location($_REQUEST['id'], 'location_id');
                $location_array = $EM_Location->to_array();
                $location_array['location_balloon'] = $EM_Location->output(get_option('dbem_location_baloon_format'));
                echo EM_Object::json_encode($location_array);
            }
            die;
        }
        if (isset($_REQUEST['em_ajax_action']) && $_REQUEST['em_ajax_action'] == 'delete_ticket') {
            if (isset($_REQUEST['id'])) {
                $EM_Ticket = new EM_Ticket($_REQUEST['id']);
                $result = $EM_Ticket->delete();
                if ($result) {
                    $result = array('result' => true);
                } else {
                    $result = array('result' => false, 'error' => $EM_Ticket->feedback_message);
                }
            } else {
                $result = array('result' => false, 'error' => __('No ticket id provided', 'dbem'));
            }
            echo EM_Object::json_encode($result);
            die;
        }
        if (isset($_REQUEST['query']) && $_REQUEST['query'] == 'GlobalMapData') {
            $EM_Locations = EM_Locations::get($_REQUEST);
            $json_locations = array();
            foreach ($EM_Locations as $location_key => $EM_Location) {
                $json_locations[$location_key] = $EM_Location->to_array();
                $json_locations[$location_key]['location_balloon'] = $EM_Location->output(get_option('dbem_map_text_format'));
            }
            echo EM_Object::json_encode($json_locations);
            die;
        }
        if (isset($_REQUEST['ajaxCalendar']) && $_REQUEST['ajaxCalendar']) {
            //FIXME if long events enabled originally, this won't show up on ajax call
            echo EM_Calendar::output($_REQUEST, false);
            die;
        }
    }
    //Event Actions
    if (!empty($_REQUEST['action']) && substr($_REQUEST['action'], 0, 5) == 'event') {
        //Load the event object, with saved event if requested
        if (!empty($_REQUEST['event_id'])) {
            $EM_Event = new EM_Event($_REQUEST['event_id']);
        } else {
            $EM_Event = new EM_Event();
        }
        //Save Event, only via BP or via [event_form]
        if ($_REQUEST['action'] == 'event_save' && $EM_Event->can_manage('edit_events', 'edit_others_events')) {
            //Check Nonces
            if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'wpnonce_event_save')) {
                exit('Trying to perform an illegal action.');
            }
            //Grab and validate submitted data
            if ($EM_Event->get_post() && $EM_Event->save()) {
                //EM_Event gets the event if submitted via POST and validates it (safer than to depend on JS)
                $events_result = true;
                //Success notice
                if (is_user_logged_in()) {
                    if (empty($_REQUEST['event_id'])) {
                        $EM_Notices->add_confirm($EM_Event->output(get_option('dbem_events_form_result_success')), true);
                    } else {
                        $EM_Notices->add_confirm($EM_Event->output(get_option('dbem_events_form_result_success_updated')), true);
                    }
                } else {
                    $EM_Notices->add_confirm($EM_Event->output(get_option('dbem_events_anonymous_result_success')), true);
                }
                $redirect = !empty($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : wp_get_referer();
                $redirect = em_add_get_params($redirect, array('success' => 1));
                wp_redirect($redirect);
                exit;
            } else {
                $EM_Notices->add_error($EM_Event->get_errors());
                $events_result = false;
            }
        }
        if ($_REQUEST['action'] == 'event_duplicate' && wp_verify_nonce($_REQUEST['_wpnonce'], 'event_duplicate_' . $EM_Event->event_id)) {
            $EM_Event = $EM_Event->duplicate();
            if ($EM_Event === false) {
                $EM_Notices->add_error($EM_Event->errors, true);
            } else {
                $EM_Notices->add_confirm($EM_Event->feedback_message, true);
            }
            wp_redirect(wp_get_referer());
            exit;
        }
        if ($_REQUEST['action'] == 'event_delete' && wp_verify_nonce($_REQUEST['_wpnonce'], 'event_delete_' . $EM_Event->event_id)) {
            //DELETE action
            $selectedEvents = !empty($_REQUEST['events']) ? $_REQUEST['events'] : '';
            if (EM_Object::array_is_numeric($selectedEvents)) {
                $events_result = EM_Events::delete($selectedEvents);
            } elseif (is_object($EM_Event)) {
                $events_result = $EM_Event->delete();
            }
            $plural = count($selectedEvents) > 1 ? __('Events', 'dbem') : __('Event', 'dbem');
            if ($events_result) {
                $message = !empty($EM_Event->feedback_message) ? $EM_Event->feedback_message : sprintf(__('%s successfully deleted.', 'dbem'), $plural);
                $EM_Notices->add_confirm($message, true);
            } else {
                $message = !empty($EM_Event->errors) ? $EM_Event->errors : sprintf(__('%s could not be deleted.', 'dbem'), $plural);
                $EM_Notices->add_error($message, true);
            }
            wp_redirect(wp_get_referer());
            exit;
        } elseif ($_REQUEST['action'] == 'event_detach' && wp_verify_nonce($_REQUEST['_wpnonce'], 'event_detach_' . get_current_user_id() . '_' . $EM_Event->event_id)) {
            //Detach event and move on
            if ($EM_Event->detach()) {
                $EM_Notices->add_confirm($EM_Event->feedback_message, true);
            } else {
                $EM_Notices->add_error($EM_Event->errors, true);
            }
            wp_redirect(wp_get_referer());
            exit;
        } elseif ($_REQUEST['action'] == 'event_attach' && !empty($_REQUEST['undo_id']) && wp_verify_nonce($_REQUEST['_wpnonce'], 'event_attach_' . get_current_user_id() . '_' . $EM_Event->event_id)) {
            //Detach event and move on
            if ($EM_Event->attach($_REQUEST['undo_id'])) {
                $EM_Notices->add_confirm($EM_Event->feedback_message, true);
            } else {
                $EM_Notices->add_error($EM_Event->errors, true);
            }
            wp_redirect(wp_get_referer());
            exit;
        }
        //AJAX Exit
        if (isset($events_result) && !empty($_REQUEST['em_ajax'])) {
            if ($events_result) {
                $return = array('result' => true, 'message' => $EM_Event->feedback_message);
            } else {
                $return = array('result' => false, 'message' => $EM_Event->feedback_message, 'errors' => $EM_Event->errors);
            }
        }
    }
    //Location Actions
    if (!empty($_REQUEST['action']) && substr($_REQUEST['action'], 0, 8) == 'location') {
        global $EM_Location, $EM_Notices;
        //Load the location object, with saved event if requested
        if (!empty($_REQUEST['location_id'])) {
            $EM_Location = new EM_Location($_REQUEST['location_id']);
        } else {
            $EM_Location = new EM_Location();
        }
        if ($_REQUEST['action'] == 'location_save' && current_user_can('edit_locations')) {
            //Check Nonces
            em_verify_nonce('location_save');
            //Grab and validate submitted data
            if ($EM_Location->get_post() && $EM_Location->save()) {
                //EM_location gets the location if submitted via POST and validates it (safer than to depend on JS)
                $EM_Notices->add_confirm($EM_Location->feedback_message, true);
                $redirect = !empty($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : wp_get_referer();
                wp_redirect($redirect);
                exit;
            } else {
                $EM_Notices->add_error($EM_Location->get_errors());
                $result = false;
            }
        } elseif (!empty($_REQUEST['action']) && $_REQUEST['action'] == "location_delete") {
            //delete location
            //get object or objects
            if (!empty($_REQUEST['locations']) || !empty($_REQUEST['location_id'])) {
                $args = !empty($_REQUEST['locations']) ? $_REQUEST['locations'] : $_REQUEST['location_id'];
                $locations = EM_Locations::get($args);
                foreach ($locations as $location) {
                    if (!$location->delete()) {
                        $EM_Notices->add_error($location->get_errors());
                        $errors = true;
                    }
                }
                if (empty($errors)) {
                    $result = true;
                    $location_term = count($locations) > 1 ? __('Locations', 'dbem') : __('Location', 'dbem');
                    $EM_Notices->add_confirm(sprintf(__('%s successfully deleted', 'dbem'), $location_term));
                } else {
                    $result = false;
                }
            }
        } elseif (!empty($_REQUEST['action']) && $_REQUEST['action'] == "locations_search" && (!empty($_REQUEST['term']) || !empty($_REQUEST['q']))) {
            $results = array();
            if (is_user_logged_in() || get_option('dbem_events_anonymous_submissions') && user_can(get_option('dbem_events_anonymous_user'), 'read_others_locations')) {
                $location_cond = is_user_logged_in() && !current_user_can('read_others_locations') ? "AND location_owner=" . get_current_user_id() : '';
                if (!is_user_logged_in() && get_option('dbem_events_anonymous_submissions')) {
                    if (!user_can(get_option('dbem_events_anonymous_user'), 'read_private_locations')) {
                        $location_cond = " AND location_private=0";
                    }
                } elseif (is_user_logged_in() && !current_user_can('read_private_locations')) {
                    $location_cond = " AND location_private=0";
                } elseif (!is_user_logged_in()) {
                    $location_cond = " AND location_private=0";
                }
                $location_cond = apply_filters('em_actions_locations_search_cond', $location_cond);
                $term = isset($_REQUEST['term']) ? '%' . $_REQUEST['term'] . '%' : '%' . $_REQUEST['q'] . '%';
                $sql = $wpdb->prepare("\r\n\t\t\t\t\tSELECT \r\n\t\t\t\t\t\tlocation_id AS `id`,\r\n\t\t\t\t\t\tConcat( location_name )  AS `label`,\r\n\t\t\t\t\t\tlocation_name AS `value`,\r\n\t\t\t\t\t\tlocation_address AS `address`, \r\n\t\t\t\t\t\tlocation_town AS `town`, \r\n\t\t\t\t\t\tlocation_state AS `state`,\r\n\t\t\t\t\t\tlocation_region AS `region`,\r\n\t\t\t\t\t\tlocation_postcode AS `postcode`,\r\n\t\t\t\t\t\tlocation_country AS `country`\r\n\t\t\t\t\tFROM " . EM_LOCATIONS_TABLE . " \r\n\t\t\t\t\tWHERE ( `location_name` LIKE %s ) AND location_status=1 {$location_cond} LIMIT 10\r\n\t\t\t\t", $term);
                $results = $wpdb->get_results($sql);
            }
            echo EM_Object::json_encode($results);
            die;
        }
        if (isset($result) && $result && !empty($_REQUEST['em_ajax'])) {
            $return = array('result' => true, 'message' => $EM_Location->feedback_message);
            echo EM_Object::json_encode($return);
            die;
        } elseif (isset($result) && !$result && !empty($_REQUEST['em_ajax'])) {
            $return = array('result' => false, 'message' => $EM_Location->feedback_message, 'errors' => $EM_Notices->get_errors());
            echo EM_Object::json_encode($return);
            die;
        }
    }
    //Booking Actions
    if (!empty($_REQUEST['action']) && substr($_REQUEST['action'], 0, 7) == 'booking' && (is_user_logged_in() || $_REQUEST['action'] == 'booking_add' && get_option('dbem_bookings_anonymous'))) {
        global $EM_Event, $EM_Booking, $EM_Person;
        //Load the booking object, with saved booking if requested
        $EM_Booking = !empty($_REQUEST['booking_id']) ? em_get_booking($_REQUEST['booking_id']) : em_get_booking();
        if (!empty($EM_Booking->event_id)) {
            //Load the event object, with saved event if requested
            $EM_Event = $EM_Booking->get_event();
        } elseif (!empty($_REQUEST['event_id'])) {
            $EM_Event = new EM_Event($_REQUEST['event_id']);
        }
        $allowed_actions = array('bookings_approve' => 'approve', 'bookings_reject' => 'reject', 'bookings_unapprove' => 'unapprove', 'bookings_delete' => 'delete');
        $result = false;
        $feedback = '';
        if ($_REQUEST['action'] == 'booking_add') {
            //ADD/EDIT Booking
            ob_start();
            if (!defined('WP_CACHE') || !WP_CACHE) {
                em_verify_nonce('booking_add');
            }
            if (!is_user_logged_in() || get_option('dbem_bookings_double') || !$EM_Event->get_bookings()->has_booking(get_current_user_id())) {
                $EM_Booking->get_post();
                $post_validation = $EM_Booking->validate();
                do_action('em_booking_add', $EM_Event, $EM_Booking, $post_validation);
                if ($post_validation) {
                    //register the user - or not depending - according to the booking
                    $registration = em_booking_add_registration($EM_Booking);
                    $EM_Bookings = $EM_Event->get_bookings();
                    if ($registration && $EM_Bookings->add($EM_Booking)) {
                        if (is_user_logged_in() && is_multisite() && !is_user_member_of_blog(get_current_user_id(), get_current_blog_id())) {
                            add_user_to_blog(get_current_blog_id(), get_current_user_id(), get_option('default_role'));
                        }
                        $result = true;
                        $EM_Notices->add_confirm($EM_Bookings->feedback_message);
                        $feedback = $EM_Bookings->feedback_message;
                    } else {
                        $result = false;
                        $EM_Notices->add_error($EM_Bookings->get_errors());
                        $feedback = $EM_Bookings->feedback_message;
                    }
                    global $em_temp_user_data;
                    $em_temp_user_data = false;
                    //delete registered user temp info (if exists)
                } else {
                    $result = false;
                    $EM_Notices->add_error($EM_Booking->get_errors());
                }
            } else {
                $result = false;
                $feedback = get_option('dbem_booking_feedback_already_booked');
                $EM_Notices->add_error($feedback);
            }
            ob_clean();
        } elseif ($_REQUEST['action'] == 'booking_add_one' && is_object($EM_Event) && is_user_logged_in()) {
            //ADD/EDIT Booking
            em_verify_nonce('booking_add_one');
            if (!$EM_Event->get_bookings()->has_booking(get_current_user_id()) || get_option('dbem_bookings_double')) {
                $EM_Booking = em_get_booking(array('person_id' => get_current_user_id(), 'event_id' => $EM_Event->event_id, 'booking_spaces' => 1));
                //new booking
                $EM_Ticket = $EM_Event->get_bookings()->get_tickets()->get_first();
                //get first ticket in this event and book one place there. similar to getting the form values in EM_Booking::get_post_values()
                $EM_Ticket_Booking = new EM_Ticket_Booking(array('ticket_id' => $EM_Ticket->ticket_id, 'ticket_booking_spaces' => 1));
                $EM_Booking->tickets_bookings = new EM_Tickets_Bookings();
                $EM_Booking->tickets_bookings->booking = $EM_Ticket_Booking->booking = $EM_Booking;
                $EM_Booking->tickets_bookings->add($EM_Ticket_Booking);
                //Now save booking
                if ($EM_Event->get_bookings()->add($EM_Booking)) {
                    $result = true;
                    $EM_Notices->add_confirm($EM_Event->get_bookings()->feedback_message);
                    $feedback = $EM_Event->get_bookings()->feedback_message;
                } else {
                    $result = false;
                    $EM_Notices->add_error($EM_Event->get_bookings()->get_errors());
                    $feedback = $EM_Event->get_bookings()->feedback_message;
                }
            } else {
                $result = false;
                $feedback = get_option('dbem_booking_feedback_already_booked');
                $EM_Notices->add_error($feedback);
            }
        } elseif ($_REQUEST['action'] == 'booking_cancel') {
            //Cancel Booking
            em_verify_nonce('booking_cancel');
            if ($EM_Booking->can_manage() || $EM_Booking->person->ID == get_current_user_id() && get_option('dbem_bookings_user_cancellation')) {
                if ($EM_Booking->cancel()) {
                    $result = true;
                    if (!defined('DOING_AJAX')) {
                        if ($EM_Booking->person->ID == get_current_user_id()) {
                            $EM_Notices->add_confirm(get_option('dbem_booking_feedback_cancelled'), true);
                        } else {
                            $EM_Notices->add_confirm($EM_Booking->feedback_message, true);
                        }
                        wp_redirect($_SERVER['HTTP_REFERER']);
                        exit;
                    }
                } else {
                    $result = false;
                    $EM_Notices->add_error($EM_Booking->get_errors());
                    $feedback = $EM_Booking->feedback_message;
                }
            } else {
                $EM_Notices->add_error(__('You must log in to cancel your booking.', 'dbem'));
            }
            //TODO user action shouldn't check permission, booking object should.
        } elseif (array_key_exists($_REQUEST['action'], $allowed_actions) && $EM_Event->can_manage('manage_bookings', 'manage_others_bookings')) {
            //Event Admin only actions
            $action = $allowed_actions[$_REQUEST['action']];
            //Just do it here, since we may be deleting bookings of different events.
            if (!empty($_REQUEST['bookings']) && EM_Object::array_is_numeric($_REQUEST['bookings'])) {
                $results = array();
                foreach ($_REQUEST['bookings'] as $booking_id) {
                    $EM_Booking = em_get_booking($booking_id);
                    $result = $EM_Booking->{$action}();
                    $results[] = $result;
                    if (!in_array(false, $results) && !$result) {
                        $feedback = $EM_Booking->feedback_message;
                    }
                }
                $result = !in_array(false, $results);
            } elseif (is_object($EM_Booking)) {
                $result = $EM_Booking->{$action}();
                $feedback = $EM_Booking->feedback_message;
            }
            //FIXME not adhereing to object's feedback or error message, like other bits in this file.
            //TODO multiple deletion won't work in ajax
            if (!empty($_REQUEST['em_ajax'])) {
                if ($result) {
                    echo $feedback;
                } else {
                    echo '<span style="color:red">' . $feedback . '</span>';
                }
                die;
            }
        } elseif ($_REQUEST['action'] == 'booking_save') {
            em_verify_nonce('booking_save_' . $EM_Booking->booking_id);
            do_action('em_booking_save', $EM_Event, $EM_Booking);
            if ($EM_Booking->can_manage('manage_bookings', 'manage_others_bookings')) {
                if ($EM_Booking->get_post(true) && $EM_Booking->validate(true) && $EM_Booking->save(false)) {
                    $EM_Notices->add_confirm($EM_Booking->feedback_message, true);
                    $redirect = !empty($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : wp_get_referer();
                    wp_redirect($redirect);
                    exit;
                } else {
                    $result = false;
                    $EM_Notices->add_error($EM_Booking->get_errors());
                    $feedback = $EM_Booking->feedback_message;
                }
            }
        } elseif ($_REQUEST['action'] == 'booking_set_status') {
            em_verify_nonce('booking_set_status_' . $EM_Booking->booking_id);
            if ($EM_Booking->can_manage('manage_bookings', 'manage_others_bookings') && $_REQUEST['booking_status'] != $EM_Booking->booking_status) {
                if ($EM_Booking->set_status($_REQUEST['booking_status'], false, true)) {
                    if (!empty($_REQUEST['send_email'])) {
                        if ($EM_Booking->email(false)) {
                            $EM_Booking->feedback_message .= " " . __('Mail Sent.', 'dbem');
                        } else {
                            $EM_Booking->feedback_message .= ' <span style="color:red">' . __('ERROR : Mail Not Sent.', 'dbem') . '</span>';
                        }
                    }
                    $EM_Notices->add_confirm($EM_Booking->feedback_message, true);
                    $redirect = !empty($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : wp_get_referer();
                    wp_redirect($redirect);
                    exit;
                } else {
                    $result = false;
                    $EM_Notices->add_error($EM_Booking->get_errors());
                    $feedback = $EM_Booking->feedback_message;
                }
            }
        } elseif ($_REQUEST['action'] == 'booking_resend_email') {
            em_verify_nonce('booking_resend_email_' . $EM_Booking->booking_id);
            if ($EM_Booking->can_manage('manage_bookings', 'manage_others_bookings')) {
                if ($EM_Booking->email(false, true)) {
                    $EM_Notices->add_confirm(__('Mail Sent.', 'dbem'), true);
                    $redirect = !empty($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : wp_get_referer();
                    wp_redirect($redirect);
                    exit;
                } else {
                    $result = false;
                    $EM_Notices->add_error(__('ERROR : Mail Not Sent.', 'dbem'));
                    $feedback = $EM_Booking->feedback_message;
                }
            }
        } elseif ($_REQUEST['action'] == 'booking_modify_person') {
            em_verify_nonce('booking_modify_person_' . $EM_Booking->booking_id);
            if ($EM_Booking->can_manage('manage_bookings', 'manage_others_bookings')) {
                global $wpdb;
                $no_user = get_option('dbem_bookings_registration_disable') && $EM_Booking->get_person()->ID == get_option('dbem_bookings_registration_user');
                if ($no_user && $EM_Booking->get_person_post() && $wpdb->update(EM_BOOKINGS_TABLE, array('booking_meta' => serialize($EM_Booking->booking_meta)), array('booking_id' => $EM_Booking->booking_id))) {
                    $EM_Notices->add_confirm($EM_Booking->feedback_message, true);
                    $redirect = !empty($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : wp_get_referer();
                    wp_redirect($redirect);
                    exit;
                } else {
                    $result = false;
                    $EM_Notices->add_error($EM_Booking->get_errors());
                    $feedback = $EM_Booking->feedback_message;
                }
            }
            do_action('em_booking_modify_person', $EM_Event, $EM_Booking);
        }
        if ($result && defined('DOING_AJAX')) {
            $return = array('result' => true, 'message' => $feedback);
            echo EM_Object::json_encode(apply_filters('em_action_' . $_REQUEST['action'], $return, $EM_Booking));
            die;
        } elseif (!$result && defined('DOING_AJAX')) {
            $return = array('result' => false, 'message' => $feedback, 'errors' => $EM_Notices->get_errors());
            echo EM_Object::json_encode(apply_filters('em_action_' . $_REQUEST['action'], $return, $EM_Booking));
            die;
        }
    } elseif (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'booking_add' && !is_user_logged_in() && !get_option('dbem_bookings_anonymous')) {
        $EM_Notices->add_error(get_option('dbem_booking_feedback_log_in'));
        if (!$result && defined('DOING_AJAX')) {
            $return = array('result' => false, 'message' => $EM_Booking->feedback_message, 'errors' => $EM_Notices->get_errors());
            echo EM_Object::json_encode(apply_filters('em_action_' . $_REQUEST['action'], $return, $EM_Booking));
        }
        die;
    }
    //AJAX call for searches
    if (!empty($_REQUEST['action']) && substr($_REQUEST['action'], 0, 6) == 'search') {
        if ($_REQUEST['action'] == 'search_states') {
            $results = array();
            $conds = array();
            if (!empty($_REQUEST['country'])) {
                $conds[] = $wpdb->prepare("(location_country = '%s' OR location_country IS NULL )", $_REQUEST['country']);
            }
            if (!empty($_REQUEST['region'])) {
                $conds[] = $wpdb->prepare("( location_region = '%s' OR location_region IS NULL )", $_REQUEST['region']);
            }
            $cond = count($conds) > 0 ? "AND " . implode(' AND ', $conds) : '';
            $results = $wpdb->get_col("SELECT DISTINCT location_state FROM " . EM_LOCATIONS_TABLE . " WHERE location_state IS NOT NULL AND location_state != '' {$cond} ORDER BY location_state");
            if ($_REQUEST['return_html']) {
                //quick shortcut for quick html form manipulation
                ob_start();
                ?>
				<option value=''><?php 
                echo get_option('dbem_search_form_states_label');
                ?>
</option>
				<?php 
                foreach ($results as $result) {
                    echo "<option>{$result}</option>";
                }
                $return = ob_get_clean();
                echo apply_filters('em_ajax_search_states', $return);
                exit;
            } else {
                echo EM_Object::json_encode($results);
                exit;
            }
        }
        if ($_REQUEST['action'] == 'search_towns') {
            $results = array();
            $conds = array();
            if (!empty($_REQUEST['country'])) {
                $conds[] = $wpdb->prepare("(location_country = '%s' OR location_country IS NULL )", $_REQUEST['country']);
            }
            if (!empty($_REQUEST['region'])) {
                $conds[] = $wpdb->prepare("( location_region = '%s' OR location_region IS NULL )", $_REQUEST['region']);
            }
            if (!empty($_REQUEST['state'])) {
                $conds[] = $wpdb->prepare("(location_state = '%s' OR location_state IS NULL )", $_REQUEST['state']);
            }
            $cond = count($conds) > 0 ? "AND " . implode(' AND ', $conds) : '';
            $results = $wpdb->get_col("SELECT DISTINCT location_town FROM " . EM_LOCATIONS_TABLE . " WHERE location_town IS NOT NULL AND location_town != '' {$cond}  ORDER BY location_town");
            if ($_REQUEST['return_html']) {
                //quick shortcut for quick html form manipulation
                ob_start();
                ?>
				<option value=''><?php 
                echo get_option('dbem_search_form_towns_label');
                ?>
</option>
				<?php 
                foreach ($results as $result) {
                    echo "<option>{$result}</option>";
                }
                $return = ob_get_clean();
                echo apply_filters('em_ajax_search_towns', $return);
                exit;
            } else {
                echo EM_Object::json_encode($results);
                exit;
            }
        }
        if ($_REQUEST['action'] == 'search_regions') {
            if (!empty($_REQUEST['country'])) {
                $conds[] = $wpdb->prepare("(location_country = '%s' OR location_country IS NULL )", $_REQUEST['country']);
            }
            $cond = count($conds) > 0 ? "AND " . implode(' AND ', $conds) : '';
            $results = $wpdb->get_results("SELECT DISTINCT location_region AS value FROM " . EM_LOCATIONS_TABLE . " WHERE location_region IS NOT NULL AND location_region != '' {$cond}  ORDER BY location_region");
            if ($_REQUEST['return_html']) {
                //quick shortcut for quick html form manipulation
                ob_start();
                ?>
				<option value=''><?php 
                echo get_option('dbem_search_form_regions_label');
                ?>
</option>
				<?php 
                foreach ($results as $result) {
                    echo "<option>{$result->value}</option>";
                }
                $return = ob_get_clean();
                echo apply_filters('em_ajax_search_regions', $return);
                exit;
            } else {
                echo EM_Object::json_encode($results);
                exit;
            }
        } elseif ($_REQUEST['action'] == 'search_events' && get_option('dbem_events_page_search') && defined('DOING_AJAX')) {
            $args = EM_Events::get_post_search();
            $args['owner'] = false;
            ob_start();
            em_locate_template('templates/events-list.php', true, array('args' => $args));
            //if successful, this template overrides the settings and defaults, including search
            echo apply_filters('em_ajax_search_events', ob_get_clean(), $args);
            exit;
        }
    }
    //EM Ajax requests require this flag.
    if (is_user_logged_in()) {
        //Admin operations
        //Specific Oject Ajax
        if (!empty($_REQUEST['em_obj'])) {
            switch ($_REQUEST['em_obj']) {
                case 'em_bookings_events_table':
                case 'em_bookings_pending_table':
                case 'em_bookings_confirmed_table':
                    //add some admin files just in case
                    include_once 'admin/bookings/em-confirmed.php';
                    include_once 'admin/bookings/em-events.php';
                    include_once 'admin/bookings/em-pending.php';
                    call_user_func($_REQUEST['em_obj']);
                    exit;
                    break;
            }
        }
    }
    //Export CSV - WIP
    if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'export_bookings_csv' && wp_verify_nonce($_REQUEST['_wpnonce'], 'export_bookings_csv')) {
        if (!empty($_REQUEST['event_id'])) {
            $EM_Event = em_get_event($_REQUEST['event_id']);
        }
        //sort out cols
        if (!empty($_REQUEST['cols']) && is_array($_REQUEST['cols'])) {
            $cols = array();
            foreach ($_REQUEST['cols'] as $col => $active) {
                if ($active) {
                    $cols[] = $col;
                }
            }
            $_REQUEST['cols'] = $cols;
        }
        $_REQUEST['limit'] = 0;
        //generate bookings export according to search request
        $show_tickets = !empty($_REQUEST['show_tickets']);
        $EM_Bookings_Table = new EM_Bookings_Table($show_tickets);
        header("Content-Type: application/octet-stream; charset=utf-8");
        $file_name = !empty($EM_Event->event_slug) ? $EM_Event->event_slug : get_bloginfo();
        header("Content-Disposition: Attachment; filename=" . sanitize_title($file_name) . "-bookings-export.csv");
        do_action('em_csv_header_output');
        if (!defined('EM_CSV_DISABLE_HEADERS') || !EM_CSV_DISABLE_HEADERS) {
            if (!empty($_REQUEST['event_id'])) {
                echo __('Event', 'dbem') . ' : ' . $EM_Event->event_name . "\n";
                if ($EM_Event->location_id > 0) {
                    echo __('Where', 'dbem') . ' - ' . $EM_Event->get_location()->location_name . "\n";
                }
                echo __('When', 'dbem') . ' : ' . $EM_Event->output('#_EVENTDATES - #_EVENTTIMES') . "\n";
            }
            echo sprintf(__('Exported booking on %s', 'dbem'), date_i18n('D d M Y h:i', current_time('timestamp'))) . "\n";
        }
        echo '"' . implode('","', $EM_Bookings_Table->get_headers(true)) . '"' . "\n";
        //Rows
        $EM_Bookings_Table->limit = 150;
        //if you're having server memory issues, try messing with this number
        $EM_Bookings = $EM_Bookings_Table->get_bookings();
        $handle = fopen("php://output", "w");
        while (!empty($EM_Bookings->bookings)) {
            foreach ($EM_Bookings->bookings as $EM_Booking) {
                //Display all values
                /* @var $EM_Booking EM_Booking */
                /* @var $EM_Ticket_Booking EM_Ticket_Booking */
                if ($show_tickets) {
                    foreach ($EM_Booking->get_tickets_bookings()->tickets_bookings as $EM_Ticket_Booking) {
                        $row = $EM_Bookings_Table->get_row_csv($EM_Ticket_Booking);
                        fputcsv($handle, $row);
                    }
                } else {
                    $row = $EM_Bookings_Table->get_row_csv($EM_Booking);
                    fputcsv($handle, $row);
                }
            }
            //reiterate loop
            $EM_Bookings_Table->offset += $EM_Bookings_Table->limit;
            $EM_Bookings = $EM_Bookings_Table->get_bookings();
        }
        fclose($handle);
        exit;
    }
}
 /**
  * Deletes bookings pending payment that are more than x minutes old, defined by migs options. 
  */
 function em_gateway_migs_booking_timeout()
 {
     global $wpdb;
     //Get a time from when to delete
     $minutes_to_subtract = absint(get_option('em_migs_booking_timeout'));
     if ($minutes_to_subtract > 0) {
         //get booking IDs without pending transactions
         $cut_off_time = date('Y-m-d H:i:s', current_time('timestamp') - $minutes_to_subtract * 60);
         $booking_ids = $wpdb->get_col('SELECT b.booking_id FROM ' . EM_BOOKINGS_TABLE . ' b LEFT JOIN ' . EM_TRANSACTIONS_TABLE . " t ON t.booking_id=b.booking_id  WHERE booking_date < '{$cut_off_time}' AND booking_status=4 AND transaction_id IS NULL AND booking_meta LIKE '%s:7:\"gateway\";s:6:\"migs\";%'");
         if (count($booking_ids) > 0) {
             //first delete ticket_bookings with expired bookings
             foreach ($booking_ids as $booking_id) {
                 $EM_Booking = em_get_booking($booking_id);
                 $EM_Booking->manage_override = true;
                 $EM_Booking->delete();
             }
         }
     }
 }
Example #14
0
 /**
  * AJAX: Process Payment
  * @since 1.2
  * @version 1.0.1
  */
 public function process_payment()
 {
     // Security
     check_ajax_referer('mycred-pay-booking', 'token');
     // Requirements
     if (!isset($_POST['booking_id']) || !is_user_logged_in()) {
         die('ERROR_1');
     }
     // Get Booking
     $booking_id = $_POST['booking_id'];
     $booking = em_get_booking($booking_id);
     // User
     if ($this->core->exclude_user($booking->person->ID)) {
         die('ERROR_2');
     }
     // User can not pay for this
     if (!$this->can_pay($booking)) {
         $message = $this->prefs['messages']['error'];
         $status = 'ERROR';
         // Let others play
         do_action('mycred_em_booking_cantpay', $booking, $this);
     } elseif (!$this->has_paid($booking)) {
         // Price
         $price = $this->core->number($booking->booking_price);
         if (!$this->single_currency()) {
             $exchange_rate = $this->prefs['rate'];
             $price = $this->core->number($exchange_rate * $price);
         }
         // Charge
         $this->core->add_creds('ticket_purchase', $booking->person->ID, 0 - $price, $this->prefs['log']['purchase'], $booking->event->post_id, array('ref_type' => 'post', 'bid' => (int) $booking_id), $this->mycred_type);
         // Update Booking if approval is required (with option to disable this feature)
         if (get_option('dbem_bookings_approval') == 1 && apply_filters('mycred_em_approve_on_pay', true, $booking, $this)) {
             $booking->approve();
         }
         $message = $this->prefs['messages']['success'];
         $status = 'OK';
         // Let others play
         do_action('mycred_em_booking_paid', $booking, $this);
         // Profit sharing
         if ($this->prefs['share'] != 0) {
             $event_post = get_post((int) $booking->event->post_id);
             if ($event_post !== NULL) {
                 $share = $this->prefs['share'] / 100 * $price;
                 $this->core->add_creds('ticket_sale', $event_post->post_author, $share, $this->prefs['log']['purchase'], $event_post->ID, array('ref_type' => 'post', 'bid' => (int) $booking_id), $this->mycred_type);
             }
         }
     } else {
         $message = '';
         $status = '';
     }
     die(json_encode(array('status' => $status, 'message' => $message)));
 }
        function print_transactions($transactions, $columns = 7)
        {
            ob_start();
            if ($transactions) {
                foreach ($transactions as $key => $transaction) {
                    ?>
				<tr valign="middle" class="alternate">
					<td>
						<?php 
                    $EM_Booking = em_get_booking($transaction->booking_id);
                    if (get_class($EM_Booking) == 'EM_Multiple_Booking') {
                        $link = em_add_get_params($EM_Booking->get_admin_url(), array('booking_id' => $EM_Booking->booking_id, 'em_ajax' => null, 'em_obj' => null));
                        echo '<a href="' . $link . '">' . $EM_Booking->get_event()->event_name . '</a>';
                    } else {
                        echo '<a href="' . $EM_Booking->get_event()->get_bookings_url() . '">' . $EM_Booking->get_event()->event_name . '</a>';
                    }
                    ?>
					</td>
					<td>
						<?php 
                    echo '<a href="' . $EM_Booking->get_person()->get_bookings_url() . '">' . $EM_Booking->person->get_name() . '</a>';
                    ?>
					</td>
					<td class="column-date">
						<?php 
                    echo mysql2date(get_option('dbem_date_format'), $transaction->transaction_timestamp);
                    ?>
					</td>
					<td class="column-amount">
						<?php 
                    $amount = $transaction->transaction_total_amount;
                    echo $transaction->transaction_currency;
                    echo "&nbsp;" . number_format($amount, 2, '.', ',');
                    ?>
					</td>
					<td class="column-gateway-trans-id">
						<?php 
                    if (!empty($transaction->transaction_gateway_id)) {
                        echo $transaction->transaction_gateway_id;
                    } else {
                        echo __('None yet', 'em-pro');
                    }
                    ?>
					</td>
					<td class="column-gateway">
						<?php 
                    if (!empty($transaction->transaction_gateway)) {
                        echo $transaction->transaction_gateway;
                    } else {
                        echo __('None yet', 'em-pro');
                    }
                    ?>
					</td>
					<td class="column-trans-status">
						<?php 
                    if (!empty($transaction->transaction_status)) {
                        echo $transaction->transaction_status;
                    } else {
                        echo __('None yet', 'em-pro');
                    }
                    ?>
					</td>
					<td class="column-trans-note-id">
						<?php 
                    if (!empty($transaction->transaction_note)) {
                        echo esc_html($transaction->transaction_note);
                    } else {
                        echo __('None', 'em-pro');
                    }
                    ?>
					</td>
					<td class="column-trans-note-id">
						<?php 
                    if ($EM_Booking->can_manage()) {
                        ?>
						<span class="trash"><a class="em-transaction-delete" href="<?php 
                        echo em_add_get_params($_SERVER['REQUEST_URI'], array('action' => 'transaction_delete', 'txn_id' => $transaction->transaction_id, '_wpnonce' => wp_create_nonce('transaction_delete_' . $transaction->transaction_id . '_' . get_current_user_id())));
                        ?>
"><?php 
                        esc_html_e_emp('Delete', 'dbem');
                        ?>
</a></span>
						<?php 
                    }
                    ?>
					</td>
			    </tr>
				<?php 
                }
            } else {
                $columncount = count($columns);
                ?>
			<tr valign="middle" class="alternate" >
				<td colspan="<?php 
                echo $columncount;
                ?>
" scope="row"><?php 
                _e('No Transactions', 'em-pro');
                ?>
</td>
		    </tr>
			<?php 
            }
            return ob_get_clean();
        }