/**
 * Prints messages and errors which are stored in the session, then clears them.
 *
 * @since 2.1
 */
function wc_print_notices()
{
    $all_notices = WC()->session->get('wc_notices', array());
    $notice_types = apply_filters('woocommerce_notice_types', array('error', 'success', 'notice'));
    foreach ($notice_types as $notice_type) {
        if (wc_notice_count($notice_type) > 0) {
            wc_get_template("notices/{$notice_type}.php", array('messages' => $all_notices[$notice_type]));
        }
    }
    wc_clear_notices();
}
 /**
  * @since 1.1.0 of SA_WC_Compatibility
  */
 public static function wc_notice_count($notice_type = '')
 {
     if (self::is_wc_21()) {
         return wc_notice_count($notice_type);
     } else {
         global $woocommerce;
         if ('error' == $notice_type) {
             return $woocommerce->error_count();
         } else {
             return $woocommerce->message_count();
         }
     }
 }
 /**
  * Test wc_notice_count().
  *
  * @since 2.2
  */
 function test_wc_notice_count()
 {
     // no error notices
     $this->assertEquals(0, wc_notice_count('error'));
     // single notice
     wc_add_notice('Bogus Notice', 'success');
     $this->assertEquals(1, wc_notice_count());
     // specific notice
     wc_add_notice('Bogus Error Notice', 'error');
     $this->assertEquals(1, wc_notice_count('error'));
     // multiple notices of different types
     wc_add_notice('Bogus Notice 2', 'success');
     wc_add_notice('Bogus Error Notice 2', 'error');
     $this->assertEquals(4, wc_notice_count());
 }
 /**
  * Process the payment and return the result
  *
  * @access      public
  * @param       int $order_id
  * @return      array
  */
 public function process_payment($order_id)
 {
     if (WC_Subscriptions_Order::order_contains_subscription($order_id)) {
         if ($this->send_to_stripe($order_id)) {
             $this->order_complete();
             WC_Subscriptions_Manager::activate_subscriptions_for_order($this->order);
             $result = array('result' => 'success', 'redirect' => $this->get_return_url($this->order));
             return $result;
         } else {
             $this->payment_failed();
             // Add a generic error message if we don't currently have any others
             if (wc_notice_count('error') == 0) {
                 wc_add_notice(__('Transaction Error: Could not complete your subscription payment.', 'stripe-for-woocommerce'), 'error');
             }
         }
     } else {
         return parent::process_payment($order_id);
     }
 }
 /**
  * Handles the unsubscribe form
  *
  * @since   1.0.0
  * @return  void
  * @author  Alberto Ruggiero
  */
 public function unsubscribe_review_request()
 {
     if ('POST' !== strtoupper($_SERVER['REQUEST_METHOD'])) {
         return;
     }
     if (empty($_POST['action']) || 'unsubscribe_review_request' !== $_POST['action'] || empty($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'unsubscribe_review_request')) {
         return;
     }
     $customer_email = !empty($_POST['account_email']) ? sanitize_email($_POST['account_email']) : '';
     if (empty($customer_email) || !is_email($customer_email)) {
         wc_add_notice(__('Please provide a valid email address.', 'yith-woocommerce-review-reminder'), 'error');
     } elseif ($customer_email !== urldecode(base64_decode($_GET['email']))) {
         wc_add_notice(__('Please retype the email address as provided.', 'yith-woocommerce-review-reminder'), 'error');
     }
     if (wc_notice_count('error') === 0) {
         $wc_email = WC_Emails::instance();
         $email = $wc_email->emails['YWRR_Unsubscribe_Mail'];
         $email->trigger($customer_email);
         wc_add_notice(__('An email has been sent with your request', 'yith-woocommerce-review-reminder'));
         wp_safe_redirect(get_permalink(get_option('ywrr_unsubscribe_page_id')));
         exit;
     }
 }
/**
 * Your bid is winning message
 *
 * @access public
 * @return void
 * 
 */
function woocommerce__simple_auctions_winning_bid_message($product_id)
{
    global $product, $woocommerce;
    if ($product->product_type != 'auction') {
        return FALSE;
    }
    if ($product->is_closed()) {
        return FALSE;
    }
    $current_user = wp_get_current_user();
    if (!$current_user->ID) {
        return FALSE;
    }
    $message = __('No need to bid. Your bid is winning! ', 'wc_simple_auctions');
    if (version_compare($woocommerce->version, '2.1', ">=")) {
        if ($current_user->ID == $product->auction_current_bider && wc_notice_count() == 0) {
            wc_add_notice(apply_filters('woocommerce_simple_auctions_winning_bid_message', $message));
        }
    } else {
        if ($current_user->ID == $product->auction_current_bider && $woocommerce->message_count() == 0) {
            $woocommerce->add_message(apply_filters('woocommerce_simple_auctions_winning_bid_message', $message));
        }
    }
}
 /**
  * Process the checkout after the confirm order button is pressed.
  */
 public function process_checkout()
 {
     try {
         if (empty($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'woocommerce-process_checkout')) {
             WC()->session->set('refresh_totals', true);
             throw new Exception(__('We were unable to process your order, please try again.', 'woocommerce'));
         }
         wc_maybe_define_constant('WOOCOMMERCE_CHECKOUT', true);
         wc_set_time_limit(0);
         do_action('woocommerce_before_checkout_process');
         if (WC()->cart->is_empty()) {
             throw new Exception(sprintf(__('Sorry, your session has expired. <a href="%s" class="wc-backward">Return to shop</a>', 'woocommerce'), esc_url(wc_get_page_permalink('shop'))));
         }
         do_action('woocommerce_checkout_process');
         $errors = new WP_Error();
         $posted_data = $this->get_posted_data();
         $this->validate_posted_data($posted_data, $errors);
         $this->validate_checkout($posted_data, $errors);
         $this->update_session($posted_data);
         $this->check_cart_items();
         do_action('woocommerce_after_checkout_validation', $posted_data, $errors);
         foreach ($errors->get_error_messages() as $message) {
             wc_add_notice($message, 'error');
         }
         if (empty($posted_data['woocommerce_checkout_update_totals']) && 0 === wc_notice_count('error')) {
             $this->process_customer($posted_data);
             $order = $this->create_order($posted_data);
             if (is_wp_error($order)) {
                 throw new Exception($order->get_error_message());
             }
             do_action('woocommerce_checkout_order_processed', $order, $posted_data);
             if (WC()->cart->needs_payment()) {
                 $this->process_order_payment($order, $posted_data['payment_method']);
             } else {
                 $this->process_order_without_payment($order);
             }
         }
     } catch (Exception $e) {
         wc_add_notice($e->getMessage(), 'error');
     }
     $this->send_ajax_failure_response();
 }
Beispiel #8
0
 /**
  * @deprecated 2.1.0
  * @return int
  */
 public function message_count()
 {
     _deprecated_function('Woocommerce->message_count', '2.1', 'wc_notice_count');
     return wc_notice_count('message');
 }
 /**
  * Remove contribution type prefix from posted keys
  *
  * @since 1.0.0
  */
 public function process_posted_comment_data()
 {
     $type = isset($_POST['comment_type']) ? $_POST['comment_type'] : null;
     // Bail out if not contribution type is set. This probably means
     // that this wasn't a contribution form anyway.
     if (!$type) {
         return;
     }
     // Loop over POST data and remove type prefix
     foreach ($_POST as $key => $value) {
         // Check if the key is prefixed with type
         if (strpos($key, $type . '_') === 0) {
             // Add posted value under cleaned (unprefixed) key
             $clean_key = substr($key, strlen($type) + 1);
             $_POST[$clean_key] = $value;
         }
     }
     // Process fields
     $contribution_type = wc_product_reviews_pro_get_contribution_type($type);
     foreach ($contribution_type->get_fields() as $key => $field) {
         // Get Value
         switch ($field['type']) {
             case "checkbox":
                 $_POST[$key] = isset($_POST[$key]) ? 1 : 0;
                 break;
             default:
                 $_POST[$key] = isset($_POST[$key]) ? wc_clean($_POST[$key]) : '';
                 break;
         }
         /**
          * Filter the POST value for $key.
          *
          * @since 1.0.0
          * @param mixed $value The POST value for $key.
          */
         $_POST[$key] = apply_filters('wc_product_reviews_pro_process_contribution_form_field_' . $key, $_POST[$key]);
         // Validation: Required fields
         if (!empty($field['required']) && empty($_POST[$key])) {
             wc_add_notice(sprintf(__('%s is a required field.', WC_Product_Reviews_Pro::TEXT_DOMAIN), $field['label']), 'error');
         }
         // Validation rules
         if (!empty($field['validate']) && is_array($field['validate'])) {
             foreach ($field['validate'] as $rule) {
                 switch ($rule) {
                     case 'email':
                         $_POST[$key] = strtolower($_POST[$key]);
                         if (!is_email($_POST[$key])) {
                             wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not a valid email address.', WC_Product_Reviews_Pro::TEXT_DOMAIN), 'error');
                         }
                         break;
                 }
             }
         }
     }
     // Check if rating is required
     if ('review' == $type && get_option('woocommerce_review_rating_required') === 'yes' && isset($_POST[$type . '_rating']) && empty($_POST[$type . '_rating'])) {
         wc_add_notice(__('Please rate the product.', WC_Product_Reviews_Pro::TEXT_DOMAIN), 'error');
     }
     // Save/handle attachments (photos, videos)
     $attachment_type = isset($_POST['attachment_type']) ? $_POST['attachment_type'] : null;
     if ($attachment_type) {
         $key = $type . '_attachment_file';
         if (isset($_FILES[$key]) && $_FILES[$key]['size'] > 0) {
             // Only photo uploads are supported at the moment
             if ('photo' == $attachment_type) {
                 // These files need to be included as dependencies when on the front end.
                 require_once ABSPATH . 'wp-admin/includes/image.php';
                 require_once ABSPATH . 'wp-admin/includes/file.php';
                 require_once ABSPATH . 'wp-admin/includes/media.php';
                 $attachment_id = media_handle_upload($key, 0, array(), array('test_form' => false, 'mimes' => array('jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'bmp' => 'image/bmp', 'tif|tiff' => 'image/tiff')));
                 // Bail out if file upload did not succeed
                 if (is_wp_error($attachment_id)) {
                     wc_add_notice(sprintf(__('Unable to upload file: %s', WC_Product_Reviews_Pro::TEXT_DOMAIN), $attachment_id->get_error_message()), 'error');
                 } else {
                     // Keep a reference to attachment_id and type
                     $this->_uploaded_attachment_id = $attachment_id;
                     $this->_uploaded_attachment_type = $attachment_type;
                 }
             } else {
                 wc_add_notice(__('Only photo uploads are supprted at the moment', WC_Product_Reviews_Pro::TEXT_DOMAIN), 'error');
             }
         }
         // Make sure that at least one of file or url is submitted
         if ('photo' == $type && !(isset($_FILES[$key]) && $_FILES[$key]['size'] > 0) && !(isset($_POST[$type . '_attachment_url']) && $_POST[$type . '_attachment_url'])) {
             wc_add_notice(__('Please attach a photo.', WC_Product_Reviews_Pro::TEXT_DOMAIN), 'error');
         }
     }
     // Redirect back to product page if there are errors
     if (wc_notice_count('error') > 0) {
         WC()->session->wc_product_reviews_pro_posted_data = $_POST;
         // Provide a hash so that page scrolls to form on load
         $hash = 'contribution_comment' == $type ? '#comment-' . $_POST['comment_parent'] : '#reviews';
         wp_safe_redirect(wp_get_referer() . $hash);
         exit;
     }
 }
 /**
  * Handles sending password retrieval email to customer.
  *
  * @access public
  * @uses $wpdb WordPress Database object
  * @return bool True: when finish. False: on error
  */
 public static function retrieve_password()
 {
     global $woocommerce, $wpdb;
     if (empty($_POST['user_login'])) {
         wc_add_notice(__('Enter a username or e-mail address.', 'woocommerce'), 'error');
     } elseif (strpos($_POST['user_login'], '@') && apply_filters('woocommerce_get_username_from_email', true)) {
         $user_data = get_user_by('email', trim($_POST['user_login']));
         if (empty($user_data)) {
             wc_add_notice(__('There is no user registered with that email address.', 'woocommerce'), 'error');
         }
     } else {
         $login = trim($_POST['user_login']);
         $user_data = get_user_by('login', $login);
     }
     do_action('lostpassword_post');
     if (wc_notice_count('error') > 0) {
         return false;
     }
     if (!$user_data) {
         wc_add_notice(__('Invalid username or e-mail.', 'woocommerce'), 'error');
         return false;
     }
     // redefining user_login ensures we return the right case in the email
     $user_login = $user_data->user_login;
     $user_email = $user_data->user_email;
     do_action('retrieve_password', $user_login);
     $allow = apply_filters('allow_password_reset', true, $user_data->ID);
     if (!$allow) {
         wc_add_notice(__('Password reset is not allowed for this user', 'woocommerce'), 'error');
         return false;
     } elseif (is_wp_error($allow)) {
         wc_add_notice($allow->get_error_message, 'error');
         return false;
     }
     $key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM {$wpdb->users} WHERE user_login = %s", $user_login));
     if (empty($key)) {
         // Generate something random for a key...
         $key = wp_generate_password(20, false);
         do_action('retrieve_password_key', $user_login, $key);
         // Now insert the new md5 key into the db
         $wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login));
     }
     // Send email notification
     $mailer = WC()->mailer();
     do_action('woocommerce_reset_password_notification', $user_login, $key);
     wc_add_notice(__('Check your e-mail for the confirmation link.', 'woocommerce'));
     return true;
 }
 /**
  * Process the change payment form.
  *
  * Based on the @see woocommerce_pay_action() function.
  *
  * @access public
  * @return void
  * @since 1.4
  */
 public static function change_payment_method_via_pay_shortcode()
 {
     global $woocommerce;
     if (isset($_POST['woocommerce_change_payment']) && wp_verify_nonce($_POST['_wpnonce'], 'woocommerce-change_payment')) {
         $subscription_key = $_POST['woocommerce_change_payment'];
         // Pay for existing order
         $order_key = isset($_GET['key']) ? $_GET['key'] : $_GET['order'];
         $order_id = absint($_GET['order_id']);
         $order = new WC_Order($order_id);
         do_action('woocommerce_subscriptions_change_payment_method_via_pay_shortcode', $subscription_key, $order);
         ob_start();
         if ($order->id == $order_id && $order->order_key == $order_key) {
             // Set customer location to order location
             if ($order->billing_country) {
                 $woocommerce->customer->set_country($order->billing_country);
             }
             if ($order->billing_state) {
                 $woocommerce->customer->set_state($order->billing_state);
             }
             if ($order->billing_postcode) {
                 $woocommerce->customer->set_postcode($order->billing_postcode);
             }
             if ($order->billing_city) {
                 $woocommerce->customer->set_city($order->billing_city);
             }
             // Update payment method
             $new_payment_method = woocommerce_clean($_POST['payment_method']);
             self::update_recurring_payment_method($subscription_key, $order, $new_payment_method);
             $available_gateways = $woocommerce->payment_gateways->get_available_payment_gateways();
             // Validate
             $available_gateways[$new_payment_method]->validate_fields();
             // Process payment for the new method (with a $0 order total)
             if (function_exists('wc_notice_count')) {
                 // WC 2.1
                 if (wc_notice_count('error') == 0) {
                     $result = $available_gateways[$new_payment_method]->process_payment($order_id);
                     // Redirect to success/confirmation/payment page
                     if ($result['result'] == 'success') {
                         WC_Subscriptions::add_notice(__('Payment method updated.', 'woocommerce-subscriptions'), 'success');
                         wp_redirect($result['redirect']);
                         exit;
                     }
                 }
             } else {
                 if ($woocommerce->error_count() == 0) {
                     $result = $available_gateways[$new_payment_method]->process_payment($order_id);
                     // Redirect to success/confirmation/payment page
                     if ($result['result'] == 'success') {
                         WC_Subscriptions::add_notice(__('Payment method updated.', 'woocommerce-subscriptions'), 'success');
                         wp_redirect($result['redirect']);
                         exit;
                     }
                 }
             }
         }
     }
 }
 /**
  * Process the change payment form.
  *
  * Based on the @see woocommerce_pay_action() function.
  *
  * @access public
  * @return void
  * @since 1.4
  */
 public static function change_payment_method_via_pay_shortcode()
 {
     if (isset($_POST['_wcsnonce']) && wp_verify_nonce($_POST['_wcsnonce'], 'wcs_change_payment_method')) {
         $subscription = wcs_get_subscription(absint($_POST['woocommerce_change_payment']));
         do_action('woocommerce_subscription_change_payment_method_via_pay_shortcode', $subscription);
         ob_start();
         if ($subscription->order_key == $_GET['key']) {
             // Set customer location to order location
             if ($subscription->billing_country) {
                 WC()->customer->set_country($subscription->billing_country);
             }
             if ($subscription->billing_state) {
                 WC()->customer->set_state($subscription->billing_state);
             }
             if ($subscription->billing_postcode) {
                 WC()->customer->set_postcode($subscription->billing_postcode);
             }
             if ($subscription->billing_city) {
                 WC()->customer->set_city($subscription->billing_city);
             }
             // Update payment method
             $new_payment_method = woocommerce_clean($_POST['payment_method']);
             // Allow some payment gateways which can't process the payment immediately, like PayPal, to do it later after the payment/sign-up is confirmed
             if (apply_filters('woocommerce_subscriptions_update_payment_via_pay_shortcode', true, $new_payment_method, $subscription)) {
                 self::update_payment_method($subscription, $new_payment_method);
             }
             $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
             // Validate
             $available_gateways[$new_payment_method]->validate_fields();
             // Process payment for the new method (with a $0 order total)
             if (wc_notice_count('error') == 0) {
                 $result = $available_gateways[$new_payment_method]->process_payment($subscription->id);
                 $result = apply_filters('woocommerce_subscriptions_process_payment_for_change_method_via_pay_shortcode', $result, $subscription);
                 // Redirect to success/confirmation/payment page
                 if ('success' == $result['result']) {
                     WC_Subscriptions::add_notice(__('Payment method updated.', 'woocommerce-subscriptions'), 'success');
                     wp_redirect($result['redirect']);
                     exit;
                 }
             }
         }
     }
 }
/**
 * Prints messages and errors which are stored in the session, then clears them.
 *
 * @since 2.1
 */
function wc_print_notices()
{
    if (!did_action('woocommerce_init')) {
        _doing_it_wrong(__FUNCTION__, __('This function should not be called before woocommerce_init.', 'woocommerce'), '2.3');
        return;
    }
    $all_notices = WC()->session->get('wc_notices', array());
    $notice_types = apply_filters('woocommerce_notice_types', array('error', 'success', 'notice'));
    foreach ($notice_types as $notice_type) {
        if (wc_notice_count($notice_type) > 0) {
            wc_get_template("notices/{$notice_type}.php", array('messages' => array_filter($all_notices[$notice_type])));
        }
    }
    wc_clear_notices();
}
 /**
  * Handle reset password form
  */
 public function process_reset_password()
 {
     if (!isset($_POST['wc_reset_password'])) {
         return;
     }
     // process lost password form
     if (isset($_POST['user_login']) && isset($_POST['_wpnonce'])) {
         wp_verify_nonce($_POST['_wpnonce'], 'woocommerce-lost_password');
         WC_Shortcode_My_Account::retrieve_password();
     }
     // process reset password form
     if (isset($_POST['password_1']) && isset($_POST['password_2']) && isset($_POST['reset_key']) && isset($_POST['reset_login']) && isset($_POST['_wpnonce'])) {
         // verify reset key again
         $user = WC_Shortcode_My_Account::check_password_reset_key($_POST['reset_key'], $_POST['reset_login']);
         if (is_object($user)) {
             // save these values into the form again in case of errors
             $args['key'] = wc_clean($_POST['reset_key']);
             $args['login'] = wc_clean($_POST['reset_login']);
             wp_verify_nonce($_POST['_wpnonce'], 'woocommerce-reset_password');
             if (empty($_POST['password_1']) || empty($_POST['password_2'])) {
                 wc_add_notice(__('Please enter your password.', 'woocommerce'), 'error');
                 $args['form'] = 'reset_password';
             }
             if ($_POST['password_1'] !== $_POST['password_2']) {
                 wc_add_notice(__('Passwords do not match.', 'woocommerce'), 'error');
                 $args['form'] = 'reset_password';
             }
             $errors = new WP_Error();
             do_action('validate_password_reset', $errors, $user);
             if ($errors->get_error_messages()) {
                 foreach ($errors->get_error_messages() as $error) {
                     wc_add_notice($error, 'error');
                 }
             }
             if (0 == wc_notice_count('error')) {
                 WC_Shortcode_My_Account::reset_password($user, $_POST['password_1']);
                 do_action('woocommerce_customer_reset_password', $user);
                 wp_redirect(add_query_arg('reset', 'true', remove_query_arg(array('key', 'login'))));
                 exit;
             }
         }
     }
 }
    /**
     * Edit subscription shipping address
     * 
     * @access public
     * @param int $subscription_id
     * @return void
     */
    public static function subscription_address($subscription_id)
    {
        if ($subscription = self::get_subscription($subscription_id)) {
            if (!$subscription->needs_shipping() || !apply_filters('subscriptio_allow_shipping_address_edit', true)) {
                self::redirect_to_subscription($subscription);
                return;
            }

            // Form submitted?
            if (isset($_POST['action']) && $_POST['action'] == 'subscriptio_edit_address') {

                // Validate address WooCommerce-style
                $address = WC()->countries->get_address_fields(esc_attr($_POST['shipping_country' ]), 'shipping_');

                foreach ($address as $key => $field) {

                    // Make sure we have field type before proceeding
                    $field['type'] = isset($field['type']) ? $field['type'] : 'text';

                    // Sanitize values
                    if ($field['type'] == 'checkbox') {
                        $_POST[$key] = isset($_POST[$key]) ? 1 : 0;
                    }
                    else {
                        $_POST[$key] = isset($_POST[$key]) ? wc_clean($_POST[$key]) : '';
                    }

                    // Required field empty?
                    if (!empty($field['required']) && empty($_POST[$key])) {
                        wc_add_notice($field['label'] . ' ' . __('is a required field.', 'subscriptio'), 'error');
                    }

                    // Validate field according to rules
                    if (!empty($field['validate']) && is_array($field['validate'])) {
                        foreach ($field['validate'] as $rule) {
                            if ($rule == 'postcode') {
                                $_POST[$key] = strtoupper(str_replace(' ', '', $_POST[$key]));

                                if (WC_Validation::is_postcode($_POST[$key], $_POST['shipping_country'])) {
                                    $_POST[$key] = wc_format_postcode($_POST[$key], $_POST['shipping_country']);
                                } else {
                                    wc_add_notice(__('Please enter a valid postcode/ZIP.', 'subscriptio'), 'error');
                                }
                            }
                            else if ($rule == 'phone') {
                                $_POST[$key] = wc_format_phone_number($_POST[$key]);

                                if (!WC_Validation::is_phone($_POST[$key])) {
                                    wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not a valid phone number.', 'subscriptio'), 'error');
                                }
                            }
                            else if ($rule == 'email') {
                                $_POST[$key] = strtolower($_POST[$key]);

                                if (!is_email($_POST[$key])) {
                                    wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not a valid email address.', 'woocommerce'), 'error');
                                }
                            }
                        }
                    }
                }

                // No errors in form?
                if (wc_notice_count('error') == 0) {

                    // Try to save address
                    if ($subscription->update_shipping_address($_POST, true, true)) {
                        wc_add_notice(__('Shipping address has been updated.', 'subscriptio'));
                    }

                    // Something went really wrong...
                    else {
                        wc_add_notice(__('Something went wrong...', 'subscriptio'), 'error');
                    }

                    // Redirect to subscription page
                    self::redirect_to_subscription($subscription);
                }
                else {
                    self::display_address_form($subscription);
                }
            }

            // Display form
            else {
                self::display_address_form($subscription);
            }
        }
    }
Beispiel #16
0
function get_notices()
{
    if (!did_action('woocommerce_init')) {
        _doing_it_wrong(__FUNCTION__, __('This function should not be called before woocommerce_init.', 'woocommerce'), '2.3');
        return;
    }
    $all_notices = WC()->session->get('wc_notices', array());
    $notice_types = apply_filters('woocommerce_notice_types', array('error', 'success', 'notice'));
    $notice_arr = array();
    foreach ($notice_types as $notice_type) {
        if (wc_notice_count($notice_type) > 0) {
            $notice_arr[$notice_type] = $all_notices[$notice_type];
        }
    }
    wc_clear_notices();
    return json_encode($notice_arr);
}
Beispiel #17
0
 /**
  * Custom add to cart handler for variable products
  *
  * Based on function add_to_cart_handler_variable( $product_id ) from
  * <install_dir>/wp-content/plugins/woocommerce/includes/class-wc-form-handler.php
  * but using $url as argument.Therefore we use the initial bits from
  * add_to_cart_action( $url ).
  *
  * @param string    $url   Add to cart url (e.g. https://www.yourdomain.com/?add-to-cart=123&quantity=1&variation_id=117&attribute_size=Small&attribute_color=Black )
  */
 public function add_to_cart_handler_variable($url)
 {
     // From add_to_cart_action( $url )
     if (empty($_REQUEST['add-to-cart']) || !is_numeric($_REQUEST['add-to-cart'])) {
         return;
     }
     $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_REQUEST['add-to-cart']));
     $was_added_to_cart = false;
     $adding_to_cart = wc_get_product($product_id);
     if (!$adding_to_cart) {
         return;
     }
     // End: From add_to_cart_action( $url )
     // From add_to_cart_handler_variable( $product_id )
     $variation_id = empty($_REQUEST['variation_id']) ? '' : absint($_REQUEST['variation_id']);
     $quantity = empty($_REQUEST['quantity']) ? 1 : wc_stock_amount($_REQUEST['quantity']);
     $missing_attributes = array();
     $variations = array();
     $attributes = $adding_to_cart->get_attributes();
     // If no variation ID is set, attempt to get a variation ID from posted attributes.
     if (empty($variation_id)) {
         $variation_id = $adding_to_cart->get_matching_variation(wp_unslash($_POST));
     }
     /**
      * Custom code to check if a translation of the product is already in the
      * cart,* and in that case, replace the variation being added to the cart
      * by the respective translation in the language of the product already
      * in the cart.
      * NOTE: The product_id is filtered by $this->add_to_cart() and holds the
      * id of the product translation, if one exists in the cart.
      */
     if ($product_id != absint($_REQUEST['add-to-cart'])) {
         // There is a translation of the product already in the cart:
         // Get the language of the product in the cart
         $lang = pll_get_post_language($product_id);
         // Get the respective variation in the language of the product in the cart
         $variation = $this->get_variation_translation($variation_id, $lang);
         $variation_id = $variation->variation_id;
     } else {
         $variation = wc_get_product($variation_id);
     }
     /**
      * End of custom code.
      */
     //$variation = wc_get_product( $variation_id );
     // Verify all attributes
     foreach ($attributes as $attribute) {
         if (!$attribute['is_variation']) {
             continue;
         }
         $taxonomy = 'attribute_' . sanitize_title($attribute['name']);
         if (isset($_REQUEST[$taxonomy])) {
             // Get value from post data
             if ($attribute['is_taxonomy']) {
                 // Don't use wc_clean as it destroys sanitized characters
                 $value = sanitize_title(stripslashes($_REQUEST[$taxonomy]));
                 /**
                  * Custom code to check if a translation of the product is already in the cart,
                  * and in that case, replace the variation attribute being added to the cart by
                  * the respective translation in the language of the product already in the cart
                  * NOTE: The product_id is filtered by $this->add_to_cart() and holds the id of
                  * the product translation, if one exists in the cart.
                  */
                 if ($product_id != absint($_REQUEST['add-to-cart'])) {
                     // Get the translation of the term
                     $term = get_term_by('slug', $value, $attribute['name']);
                     $_term = get_term_by('id', pll_get_term(absint($term->term_id), $lang), $attribute['name']);
                     if ($_term) {
                         $value = $_term->slug;
                     }
                 }
                 /**
                  * End of custom code.
                  */
             } else {
                 $value = wc_clean(stripslashes($_REQUEST[$taxonomy]));
             }
             // Get valid value from variation
             $valid_value = isset($variation->variation_data[$taxonomy]) ? $variation->variation_data[$taxonomy] : '';
             // Allow if valid
             if ('' === $valid_value || $valid_value === $value) {
                 $variations[$taxonomy] = $value;
                 continue;
             }
         } else {
             $missing_attributes[] = wc_attribute_label($attribute['name']);
         }
     }
     if (!empty($missing_attributes)) {
         wc_add_notice(sprintf(_n('%s is a required field', '%s are required fields', sizeof($missing_attributes), 'woocommerce'), wc_format_list_of_items($missing_attributes)), 'error');
     } elseif (empty($variation_id)) {
         wc_add_notice(__('Please choose product options&hellip;', 'woocommerce'), 'error');
     } else {
         // Add to cart validation
         $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations);
         if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variations) !== false) {
             wc_add_to_cart_message(array($product_id => $quantity), true);
             //return true; Doing an action, no return needed but we need to set $was_added_to_cart to trigger the redirect
             $was_added_to_cart = true;
         } else {
             $was_added_to_cart = false;
         }
     }
     //return false; Doing an action, no return needed but we need to set $was_added_to_cart to trigger the redirect
     // End: From add_to_cart_handler_variable( $product_id )
     /**
      * Because this is a custom handler we need to take care of the rediret
      * to the cart. Again we use the code from add_to_cart_action( $url )
      */
     // From add_to_cart_action( $url )
     // If we added the product to the cart we can now optionally do a redirect.
     if ($was_added_to_cart && wc_notice_count('error') === 0) {
         // If has custom URL redirect there
         if ($url = apply_filters('woocommerce_add_to_cart_redirect', $url)) {
             wp_safe_redirect($url);
             exit;
         } elseif (get_option('woocommerce_cart_redirect_after_add') === 'yes') {
             wp_safe_redirect(wc_get_cart_url());
             exit;
         }
     }
     // End: From add_to_cart_action( $url )
 }
 public function after_checkout_validation()
 {
     WC()->session->set('checkout_posted', WC()->checkout()->posted);
     if (wc_notice_count('error') != 0) {
         return;
     }
     echo '<!--WC_START-->' . json_encode(array('result' => 'step', 'refresh' => 'true', 'messages' => ' ')) . '<!--WC_END-->';
     exit;
 }
 /**
  * Regular checkout process
  */
 function regular_checkout($posted)
 {
     if ($posted['payment_method'] == 'paypal_express' && wc_notice_count('error') == 0) {
         $this->paypal_express_checkout($posted);
     }
     return;
 }
 /**
  * Regular checkout process
  */
 function regular_checkout($posted)
 {
     if ($posted['payment_method'] == 'paypal_express' && wc_notice_count('error') == 0) {
         if (!is_user_logged_in() && (get_option('woocommerce_enable_guest_checkout') != 'yes' || isset($posted['createaccount']) && $posted['createaccount'] == 1)) {
             $this->customer_id = apply_filters('woocommerce_checkout_customer_id', get_current_user_id());
             $username = !empty($posted['account_username']) ? $posted['account_username'] : '';
             $password = !empty($posted['account_password']) ? $posted['account_password'] : '';
             $new_customer = wc_create_new_customer($posted['billing_email'], $username, $password);
             if (is_wp_error($new_customer)) {
                 throw new Exception($new_customer->get_error_message());
             }
             $this->customer_id = $new_customer;
             wc_set_customer_auth_cookie($this->customer_id);
             // As we are now logged in, checkout will need to refresh to show logged in data
             WC()->session->set('reload_checkout', true);
             // Also, recalculate cart totals to reveal any role-based discounts that were unavailable before registering
             WC()->cart->calculate_totals();
             // Add customer info from other billing fields
             if ($posted['billing_first_name'] && apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                 $userdata = array('ID' => $this->customer_id, 'first_name' => $posted['billing_first_name'] ? $posted['billing_first_name'] : '', 'last_name' => $posted['billing_last_name'] ? $posted['billing_last_name'] : '', 'display_name' => $posted['billing_first_name'] ? $posted['billing_first_name'] : '');
                 wp_update_user(apply_filters('woocommerce_checkout_customer_userdata', $userdata, $this));
             }
         }
         $this->set_session('checkout_form', serialize($posted));
         $this->paypal_express_checkout($posted);
         return;
     }
 }
 public function save_vendor_settings()
 {
     global $woocommerce;
     $user_id = get_current_user_id();
     if (!empty($_GET['wc_pv_mark_shipped'])) {
         $shop_name = WCV_Vendors::get_vendor_shop_name($user_id);
         $order_id = $_GET['wc_pv_mark_shipped'];
         $shippers = (array) get_post_meta($order_id, 'wc_pv_shipped', true);
         $order = new WC_Order($order_id);
         // If not in the shippers array mark as shipped otherwise do nothing.
         if (!in_array($user_id, $shippers)) {
             $shippers[] = $user_id;
             $mails = $woocommerce->mailer()->get_emails();
             if (!empty($mails)) {
                 $mails['WC_Email_Notify_Shipped']->trigger($order_id, $user_id);
             }
             do_action('wcvendors_vendor_ship', $order_id, $user_id);
             wc_add_notice(__('Order marked shipped.', 'wcvendors'), 'success');
             $order->add_order_note(apply_filters('wcvendors_vendor_shipped_note', __($shop_name . ' has marked as shipped. ', 'wcvendors')), $user_id);
         } elseif (false != ($key = array_search($user_id, $shippers))) {
             unset($shippers[$key]);
             // Remove user from the shippers array
         }
         update_post_meta($order_id, 'wc_pv_shipped', $shippers);
         return;
     }
     if (isset($_POST['update_tracking'])) {
         $order_id = (int) $_POST['order_id'];
         $product_id = (int) $_POST['product_id'];
         $tracking_provider = woocommerce_clean($_POST['tracking_provider']);
         $custom_tracking_provider = woocommerce_clean($_POST['custom_tracking_provider_name']);
         $custom_tracking_link = woocommerce_clean($_POST['custom_tracking_url']);
         $tracking_number = woocommerce_clean($_POST['tracking_number']);
         $date_shipped = woocommerce_clean(strtotime($_POST['date_shipped']));
         $order = new WC_Order($order_id);
         $products = $order->get_items();
         foreach ($products as $key => $value) {
             if ($value['product_id'] == $product_id || $value['variation_id'] == $product_id) {
                 $order_item_id = $key;
                 break;
             }
         }
         if ($order_item_id) {
             woocommerce_delete_order_item_meta($order_item_id, __('Tracking number', 'wcvendors'));
             woocommerce_add_order_item_meta($order_item_id, __('Tracking number', 'wcvendors'), $tracking_number);
             $message = __('Success. Your tracking number has been updated.', 'wcvendors');
             wc_add_notice($message, 'success');
             // Update order data
             update_post_meta($order_id, '_tracking_provider', $tracking_provider);
             update_post_meta($order_id, '_custom_tracking_provider', $custom_tracking_provider);
             update_post_meta($order_id, '_tracking_number', $tracking_number);
             update_post_meta($order_id, '_custom_tracking_link', $custom_tracking_link);
             update_post_meta($order_id, '_date_shipped', $date_shipped);
         }
     }
     if (empty($_POST['vendor_application_submit'])) {
         return false;
     }
     if (isset($_POST['wc-product-vendor-nonce'])) {
         if (!wp_verify_nonce($_POST['wc-product-vendor-nonce'], 'save-shop-settings')) {
             return false;
         }
         if (isset($_POST['pv_paypal'])) {
             if (!is_email($_POST['pv_paypal'])) {
                 wc_add_notice(__('Your PayPal address is not a valid email address.', 'wcvendors'), 'error');
             } else {
                 update_user_meta($user_id, 'pv_paypal', $_POST['pv_paypal']);
             }
         }
         if (!empty($_POST['pv_shop_name'])) {
             $users = get_users(array('meta_key' => 'pv_shop_slug', 'meta_value' => sanitize_title($_POST['pv_shop_name'])));
             if (!empty($users) && $users[0]->ID != $user_id) {
                 wc_add_notice(__('That shop name is already taken. Your shop name must be unique.', 'wcvendors'), 'error');
             } else {
                 update_user_meta($user_id, 'pv_shop_name', $_POST['pv_shop_name']);
                 update_user_meta($user_id, 'pv_shop_slug', sanitize_title($_POST['pv_shop_name']));
             }
         }
         if (isset($_POST['pv_shop_description'])) {
             update_user_meta($user_id, 'pv_shop_description', $_POST['pv_shop_description']);
         }
         if (isset($_POST['pv_seller_info'])) {
             update_user_meta($user_id, 'pv_seller_info', $_POST['pv_seller_info']);
         }
         do_action('wcvendors_shop_settings_saved', $user_id);
         if (!wc_notice_count()) {
             wc_add_notice(__('Settings saved.', 'wcvendors'), 'success');
         }
     }
 }
 /**
  * Handles the unsubscribe form
  *
  * @since   1.0.0
  * @return  void
  * @author  Alberto Ruggiero
  */
 public function unsubscribe_review_request()
 {
     if ('POST' !== strtoupper($_SERVER['REQUEST_METHOD'])) {
         return;
     }
     if (empty($_POST['action']) || 'unsubscribe_review_request' !== $_POST['action'] || empty($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'unsubscribe_review_request')) {
         return;
     }
     $customer_id = !empty($_POST['account_id']) ? $_POST['account_id'] : 0;
     $customer_email = !empty($_POST['account_email']) ? sanitize_email($_POST['account_email']) : '';
     if (empty($customer_email) || !is_email($customer_email)) {
         wc_add_notice(__('Please provide a valid email address.', 'yith-woocommerce-review-reminder'), 'error');
     } elseif ($customer_email !== urldecode(base64_decode($_GET['email']))) {
         wc_add_notice(__('Please retype the email address as provided.', 'yith-woocommerce-review-reminder'), 'error');
     }
     if (wc_notice_count('error') === 0) {
         if (true == YWRR_Blocklist()->check_blocklist($customer_id, $customer_email)) {
             try {
                 YWRR_Blocklist()->add_to_blocklist($customer_id, $customer_email);
                 wc_add_notice(__('Unsubscribe was successful.', 'yith-woocommerce-review-reminder'));
                 wp_safe_redirect(get_permalink(get_option('ywrr_unsubscribe_page_id')));
                 exit;
             } catch (Exception $e) {
                 wc_add_notice(__('An error has occurred', 'yith-woocommerce-review-reminder'), 'error');
             }
         } else {
             wc_add_notice(__('You have already unsubscribed', 'yith-woocommerce-review-reminder'), 'error');
         }
     }
 }
 /**
  * Process the checkout after the confirm order button is pressed
  *
  * @access public
  * @return void
  */
 public function process_checkout()
 {
     global $wpdb, $current_user;
     wp_verify_nonce($_POST['_wpnonce'], 'woocommerce-process_checkout');
     if (!defined('WOOCOMMERCE_CHECKOUT')) {
         define('WOOCOMMERCE_CHECKOUT', true);
     }
     // Prevent timeout
     @set_time_limit(0);
     do_action('woocommerce_before_checkout_process');
     if (sizeof(WC()->cart->get_cart()) == 0) {
         wc_add_notice(sprintf(__('Sorry, your session has expired. <a href="%s" class="wc-backward">Return to homepage</a>', 'woocommerce'), home_url()), 'error');
     }
     do_action('woocommerce_checkout_process');
     // Checkout fields (not defined in checkout_fields)
     $this->posted['terms'] = isset($_POST['terms']) ? 1 : 0;
     $this->posted['createaccount'] = isset($_POST['createaccount']) ? 1 : 0;
     $this->posted['payment_method'] = isset($_POST['payment_method']) ? stripslashes($_POST['payment_method']) : '';
     $this->posted['shipping_method'] = isset($_POST['shipping_method']) ? $_POST['shipping_method'] : '';
     $this->posted['ship_to_different_address'] = isset($_POST['ship_to_different_address']) ? true : false;
     if (isset($_POST['shiptobilling'])) {
         _deprecated_argument('WC_Checkout::process_checkout()', '2.1', 'The "shiptobilling" field is deprecated. THe template files are out of date');
         $this->posted['ship_to_different_address'] = $_POST['shiptobilling'] ? false : true;
     }
     // Ship to billing only option
     if (WC()->cart->ship_to_billing_address_only()) {
         $this->posted['ship_to_different_address'] = false;
     }
     // Update customer shipping and payment method to posted method
     $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
     if (isset($this->posted['shipping_method']) && is_array($this->posted['shipping_method'])) {
         foreach ($this->posted['shipping_method'] as $i => $value) {
             $chosen_shipping_methods[$i] = wc_clean($value);
         }
     }
     WC()->session->set('chosen_shipping_methods', $chosen_shipping_methods);
     WC()->session->set('chosen_payment_method', $this->posted['payment_method']);
     // Note if we skip shipping
     $skipped_shipping = false;
     // Get posted checkout_fields and do validation
     foreach ($this->checkout_fields as $fieldset_key => $fieldset) {
         // Skip shipping if not needed
         if ($fieldset_key == 'shipping' && ($this->posted['ship_to_different_address'] == false || !WC()->cart->needs_shipping())) {
             $skipped_shipping = true;
             continue;
         }
         // Ship account if not needed
         if ($fieldset_key == 'account' && (is_user_logged_in() || $this->must_create_account == false && empty($this->posted['createaccount']))) {
             continue;
         }
         foreach ($fieldset as $key => $field) {
             if (!isset($field['type'])) {
                 $field['type'] = 'text';
             }
             // Get Value
             switch ($field['type']) {
                 case "checkbox":
                     $this->posted[$key] = isset($_POST[$key]) ? 1 : 0;
                     break;
                 case "multiselect":
                     $this->posted[$key] = isset($_POST[$key]) ? implode(', ', array_map('wc_clean', $_POST[$key])) : '';
                     break;
                 case "textarea":
                     $this->posted[$key] = isset($_POST[$key]) ? wp_strip_all_tags(wp_check_invalid_utf8(stripslashes($_POST[$key]))) : '';
                     break;
                 default:
                     $this->posted[$key] = isset($_POST[$key]) ? wc_clean($_POST[$key]) : '';
                     break;
             }
             // Hooks to allow modification of value
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_' . sanitize_title($field['type']) . '_field', $this->posted[$key]);
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_field_' . $key, $this->posted[$key]);
             // Validation: Required fields
             if (isset($field['required']) && $field['required'] && empty($this->posted[$key])) {
                 wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is a required field.', 'woocommerce'), 'error');
             }
             if (!empty($this->posted[$key])) {
                 // Validation rules
                 if (!empty($field['validate']) && is_array($field['validate'])) {
                     foreach ($field['validate'] as $rule) {
                         switch ($rule) {
                             case 'postcode':
                                 $this->posted[$key] = strtoupper(str_replace(' ', '', $this->posted[$key]));
                                 if (!WC_Validation::is_postcode($this->posted[$key], $_POST[$fieldset_key . '_country'])) {
                                     wc_add_notice(__('Please enter a valid postcode/ZIP.', 'woocommerce'), 'error');
                                 } else {
                                     $this->posted[$key] = wc_format_postcode($this->posted[$key], $_POST[$fieldset_key . '_country']);
                                 }
                                 break;
                             case 'phone':
                                 $this->posted[$key] = wc_format_phone_number($this->posted[$key]);
                                 if (!WC_Validation::is_phone($this->posted[$key])) {
                                     wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not a valid phone number.', 'woocommerce'), 'error');
                                 }
                                 break;
                             case 'email':
                                 $this->posted[$key] = strtolower($this->posted[$key]);
                                 if (!is_email($this->posted[$key])) {
                                     wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not a valid email address.', 'woocommerce'), 'error');
                                 }
                                 break;
                             case 'state':
                                 // Get valid states
                                 $valid_states = WC()->countries->get_states($_POST[$fieldset_key . '_country']);
                                 if ($valid_states) {
                                     $valid_state_values = array_flip(array_map('strtolower', $valid_states));
                                 }
                                 // Convert value to key if set
                                 if (isset($valid_state_values[strtolower($this->posted[$key])])) {
                                     $this->posted[$key] = $valid_state_values[strtolower($this->posted[$key])];
                                 }
                                 // Only validate if the country has specific state options
                                 if ($valid_states && sizeof($valid_states) > 0) {
                                     if (!in_array($this->posted[$key], array_keys($valid_states))) {
                                         wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not valid. Please enter one of the following:', 'woocommerce') . ' ' . implode(', ', $valid_states), 'error');
                                     }
                                 }
                                 break;
                         }
                     }
                 }
             }
         }
     }
     // Update customer location to posted location so we can correctly check available shipping methods
     if (isset($this->posted['billing_country'])) {
         WC()->customer->set_country($this->posted['billing_country']);
     }
     if (isset($this->posted['billing_state'])) {
         WC()->customer->set_state($this->posted['billing_state']);
     }
     if (isset($this->posted['billing_postcode'])) {
         WC()->customer->set_postcode($this->posted['billing_postcode']);
     }
     // Shipping Information
     if (!$skipped_shipping) {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['shipping_country'])) {
             WC()->customer->set_shipping_country($this->posted['shipping_country']);
         }
         if (isset($this->posted['shipping_state'])) {
             WC()->customer->set_shipping_state($this->posted['shipping_state']);
         }
         if (isset($this->posted['shipping_postcode'])) {
             WC()->customer->set_shipping_postcode($this->posted['shipping_postcode']);
         }
     } else {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['billing_country'])) {
             WC()->customer->set_shipping_country($this->posted['billing_country']);
         }
         if (isset($this->posted['billing_state'])) {
             WC()->customer->set_shipping_state($this->posted['billing_state']);
         }
         if (isset($this->posted['billing_postcode'])) {
             WC()->customer->set_shipping_postcode($this->posted['billing_postcode']);
         }
     }
     // Update cart totals now we have customer address
     WC()->cart->calculate_totals();
     // Terms
     if (!isset($_POST['woocommerce_checkout_update_totals']) && empty($this->posted['terms']) && wc_get_page_id('terms') > 0) {
         wc_add_notice(__('You must accept our Terms &amp; Conditions.', 'woocommerce'), 'error');
     }
     if (WC()->cart->needs_shipping()) {
         if (!in_array(WC()->customer->get_shipping_country(), array_keys(WC()->countries->get_shipping_countries()))) {
             wc_add_notice(sprintf(__('Unfortunately <strong>we do not ship to %s</strong>. Please enter an alternative shipping address.', 'woocommerce'), WC()->countries->shipping_to_prefix() . ' ' . WC()->customer->get_shipping_country()), 'error');
         }
         // Validate Shipping Methods
         $packages = WC()->shipping->get_packages();
         $this->shipping_methods = WC()->session->get('chosen_shipping_methods');
         foreach ($packages as $i => $package) {
             if (!isset($package['rates'][$this->shipping_methods[$i]])) {
                 wc_add_notice(__('Invalid shipping method.', 'woocommerce'), 'error');
                 $this->shipping_methods[$i] = '';
             }
         }
     }
     if (WC()->cart->needs_payment()) {
         // Payment Method
         $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
         if (!isset($available_gateways[$this->posted['payment_method']])) {
             $this->payment_method = '';
             wc_add_notice(__('Invalid payment method.', 'woocommerce'), 'error');
         } else {
             $this->payment_method = $available_gateways[$this->posted['payment_method']];
             $this->payment_method->validate_fields();
         }
     }
     // Action after validation
     do_action('woocommerce_after_checkout_validation', $this->posted);
     if (!isset($_POST['woocommerce_checkout_update_totals']) && wc_notice_count('error') == 0) {
         try {
             // Customer accounts
             $this->customer_id = apply_filters('woocommerce_checkout_customer_id', get_current_user_id());
             if (!is_user_logged_in() && ($this->must_create_account || !empty($this->posted['createaccount']))) {
                 $username = !empty($this->posted['account_username']) ? $this->posted['account_username'] : '';
                 $password = !empty($this->posted['account_password']) ? $this->posted['account_password'] : '';
                 $new_customer = wc_create_new_customer($this->posted['billing_email'], $username, $password);
                 if (is_wp_error($new_customer)) {
                     throw new Exception($new_customer->get_error_message());
                 }
                 $this->customer_id = $new_customer;
                 wc_set_customer_auth_cookie($this->customer_id);
                 // As we are now logged in, checkout will need to refresh to show logged in data
                 WC()->session->set('reload_checkout', true);
                 // Add customer info from other billing fields
                 if ($this->posted['billing_first_name'] && apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                     $userdata = array('ID' => $this->customer_id, 'first_name' => $this->posted['billing_first_name'] ? $this->posted['billing_first_name'] : '', 'last_name' => $this->posted['billing_last_name'] ? $this->posted['billing_last_name'] : '', 'display_name' => $this->posted['billing_first_name'] ? $this->posted['billing_first_name'] : '');
                     wp_update_user(apply_filters('woocommerce_checkout_customer_userdata', $userdata, $this));
                 }
             }
             // Do a final stock check at this point
             $this->check_cart_items();
             // Abort if errors are present
             if (wc_notice_count('error') > 0) {
                 throw new Exception();
             }
             $order_id = $this->create_order();
             do_action('woocommerce_checkout_order_processed', $order_id, $this->posted);
             // Process payment
             if (WC()->cart->needs_payment()) {
                 // Store Order ID in session so it can be re-used after payment failure
                 WC()->session->order_awaiting_payment = $order_id;
                 // Process Payment
                 $result = $available_gateways[$this->posted['payment_method']]->process_payment($order_id);
                 // Redirect to success/confirmation/payment page
                 if ($result['result'] == 'success') {
                     $result = apply_filters('woocommerce_payment_successful_result', $result, $order_id);
                     if (is_ajax()) {
                         echo '<!--WC_START-->' . json_encode($result) . '<!--WC_END-->';
                         exit;
                     } else {
                         wp_redirect($result['redirect']);
                         exit;
                     }
                 }
             } else {
                 if (empty($order)) {
                     $order = new WC_Order($order_id);
                 }
                 // No payment was required for order
                 $order->payment_complete();
                 // Empty the Cart
                 WC()->cart->empty_cart();
                 // Get redirect
                 $return_url = $order->get_checkout_order_received_url();
                 // Redirect to success/confirmation/payment page
                 if (is_ajax()) {
                     echo '<!--WC_START-->' . json_encode(array('result' => 'success', 'redirect' => apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order))) . '<!--WC_END-->';
                     exit;
                 } else {
                     wp_safe_redirect(apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order));
                     exit;
                 }
             }
         } catch (Exception $e) {
             if (!empty($e)) {
                 wc_add_notice($e->getMessage(), 'error');
             }
         }
     }
     // endif
     // If we reached this point then there were errors
     if (is_ajax()) {
         ob_start();
         wc_print_notices();
         $messages = ob_get_clean();
         echo '<!--WC_START-->' . json_encode(array('result' => 'failure', 'messages' => $messages, 'refresh' => isset(WC()->session->refresh_totals) ? 'true' : 'false', 'reload' => isset(WC()->session->reload_checkout) ? 'true' : 'false')) . '<!--WC_END-->';
         unset(WC()->session->refresh_totals, WC()->session->reload_checkout);
         exit;
     }
 }
 /**
  * Validate payment fields
  */
 public function validate_fields()
 {
     if ($this->is_single_order() && $this->installments > 1) {
         if (!isset($_POST['vindi_cc_installments']) || empty($_POST['vindi_cc_installments'])) {
             wc_add_notice(__('Quantidade de Parcelas requerido.', VINDI_IDENTIFIER), 'error');
         }
         $total = $this->container->woocommerce->cart->total;
         if ($_POST['vindi_cc_installments'] > $this->get_order_max_installments($total)) {
             wc_add_notice(__('A Quantidade de Parcelas escolhidas é inválida.', VINDI_IDENTIFIER), 'error');
         }
     }
     if ($this->verify_user_payment_profile()) {
         $this->validated = !wc_notice_count();
         return;
     }
     $fields = array('vindi_cc_fullname' => __('Nome do Portador do Cartão de Crédito requerido.', VINDI_IDENTIFIER), 'vindi_cc_number' => __('Número do Cartão de Crédito requerido.', VINDI_IDENTIFIER), 'vindi_cc_cvc' => __('Código de Segurança do Cartão requerido.', VINDI_IDENTIFIER), 'vindi_cc_monthexpiry' => __('Mês de Validade do Cartão requerido.', VINDI_IDENTIFIER), 'vindi_cc_yearexpiry' => __('Ano de Validade do Cartão requerido.', VINDI_IDENTIFIER));
     foreach ($fields as $field => $message) {
         if (!isset($_POST[$field]) || empty($_POST[$field])) {
             wc_add_notice($message, 'error');
         }
     }
     /* Validate expiry date */
     $now = time();
     $ccExpiry = mktime(0, 0, 0, (int) $_POST['vindi_cc_monthexpiry'], 1, (int) $_POST['vindi_cc_yearexpiry']);
     if ($now > $ccExpiry) {
         wc_add_notice(__('Este cartão de crédito já expirou. Tente novamente com outro cartão de crédito dentro do prazo de validade.', VINDI_IDENTIFIER), 'error');
     }
     $this->validated = !wc_notice_count();
 }
Beispiel #25
0
 /**
  * Get the count of notices added, either for all notices (default) or for one
  * particular notice type specified by $notice_type.
  *
  * WC notice funtions are not available in the admin
  *
  * @since 3.0.2
  * @param string $notice_type The name of the notice type - either error, success or notice. [optional]
  * @return int
  */
 public static function wc_notice_count($notice_type = '')
 {
     if (function_exists('wc_notice_count')) {
         return wc_notice_count($notice_type);
     }
     return 0;
 }
Beispiel #26
0
 /**
  * Checks revocation form and sends Email to customer and Admin
  */
 public static function gzd_revocation()
 {
     check_ajax_referer('woocommerce-revocation', 'security');
     wp_verify_nonce($_POST['_wpnonce'], 'woocommerce-revocation');
     $data = array();
     $fields = WC_GZD_Revocation::get_fields();
     if (!empty($fields)) {
         foreach ($fields as $key => $field) {
             if ($key != 'sep') {
                 if ($key == 'address_mail') {
                     if (!is_email($_POST[$key])) {
                         wc_add_notice('<strong>' . $field['label'] . '</strong> ' . _x('is not a valid email address.', 'revocation-form', 'woocommerce-germanized'), 'error');
                     }
                 } elseif ($key == 'address_postal') {
                     if (!WC_Validation::is_postcode($_POST[$key], $_POST['address_country']) || empty($_POST[$key])) {
                         wc_add_notice(_x('Please enter a valid postcode/ZIP', 'revocation-form', 'woocommerce-germanized'), 'error');
                     }
                 } else {
                     if (isset($field['required']) && empty($_POST[$key])) {
                         wc_add_notice('<strong>' . $field['label'] . '</strong> ' . _x('is not valid.', 'revocation-form', 'woocommerce-germanized'), 'error');
                     }
                 }
                 if (!empty($_POST[$key])) {
                     if ($field['type'] == 'country') {
                         $countries = WC()->countries->get_countries();
                         $data[$key] = $countries[sanitize_text_field($_POST[$key])];
                     } else {
                         $data[$key] = sanitize_text_field($_POST[$key]);
                     }
                 }
             }
         }
     }
     $error = false;
     if (wc_notice_count('error') == 0) {
         wc_add_notice(_x('Thank you. We have received your Revocation Request. You will receive a conformation email within a few minutes.', 'revocation-form', 'woocommerce-germanized'), 'success');
         // Send Mail
         $mails = WC()->mailer()->get_emails();
         if (!empty($mails)) {
             foreach ($mails as $mail) {
                 if ($mail->id == 'customer_revocation') {
                     $mail->trigger($data);
                     // Send to Admin
                     $data['mail'] = get_bloginfo('admin_email');
                     $mail->trigger($data);
                 }
             }
         }
     } else {
         $error = true;
     }
     ob_start();
     wc_print_notices();
     $messages = ob_get_clean();
     if ($error) {
         echo '<!--WC_START-->' . json_encode(array('result' => 'failure', 'messages' => isset($messages) ? $messages : '')) . '<!--WC_END-->';
     } else {
         if (is_ajax()) {
             echo '<!--WC_START-->' . json_encode(array('result' => 'success', 'messages' => isset($messages) ? $messages : '')) . '<!--WC_END-->';
         }
     }
     exit;
 }
 /**
  * Show the checkout
  */
 private static function checkout()
 {
     // Show non-cart errors
     wc_print_notices();
     // Check cart has contents
     if (sizeof(WC()->cart->get_cart()) == 0) {
         return;
     }
     // Check cart contents for errors
     do_action('woocommerce_check_cart_items');
     // Calc totals
     WC()->cart->calculate_totals();
     // Get checkout object
     $checkout = WC()->checkout();
     if (empty($_POST) && wc_notice_count('error') > 0) {
         wc_get_template('checkout/cart-errors.php', array('checkout' => $checkout));
     } else {
         $non_js_checkout = !empty($_POST['woocommerce_checkout_update_totals']) ? true : false;
         if (wc_notice_count('error') == 0 && $non_js_checkout) {
             wc_add_notice(__('The order totals have been updated. Please confirm your order by pressing the Place Order button at the bottom of the page.', 'woocommerce'));
         }
         wc_get_template('checkout/form-checkout.php', array('checkout' => $checkout));
     }
 }
 /**
  * Handle reset password form.
  */
 public static function process_reset_password()
 {
     $posted_fields = array('wc_reset_password', 'password_1', 'password_2', 'reset_key', 'reset_login', '_wpnonce');
     foreach ($posted_fields as $field) {
         if (!isset($_POST[$field])) {
             return;
         }
         $posted_fields[$field] = $_POST[$field];
     }
     if (!wp_verify_nonce($posted_fields['_wpnonce'], 'reset_password')) {
         return;
     }
     $user = WC_Shortcode_My_Account::check_password_reset_key($posted_fields['reset_key'], $posted_fields['reset_login']);
     if ($user instanceof WP_User) {
         if (empty($posted_fields['password_1'])) {
             wc_add_notice(__('Please enter your password.', 'woocommerce'), 'error');
         }
         if ($posted_fields['password_1'] !== $posted_fields['password_2']) {
             wc_add_notice(__('Passwords do not match.', 'woocommerce'), 'error');
         }
         $errors = new WP_Error();
         do_action('validate_password_reset', $errors, $user);
         wc_add_wp_error_notices($errors);
         if (0 === wc_notice_count('error')) {
             WC_Shortcode_My_Account::reset_password($user, $posted_fields['password_1']);
             do_action('woocommerce_customer_reset_password', $user);
             wp_redirect(add_query_arg('password-reset', 'true', wc_get_page_permalink('myaccount')));
             exit;
         }
     }
 }
Beispiel #29
0
 public static function wc_error_count()
 {
     if (self::is_wc_version_gt('2.0')) {
         return wc_notice_count('error');
     } else {
         global $woocommerce;
         return $woocommerce->error_count();
     }
 }
 /**
  * When a subscriber's billing or shipping address is successfully updated, check if the subscriber
  * has also requested to update the addresses on existing subscriptions and if so, go ahead and update
  * the addresses on the initial order for each subscription.
  *
  * @param int $user_id The ID of a user who own's the subscription (and address)
  * @since 1.3
  */
 public static function maybe_update_subscription_addresses($user_id, $address_type)
 {
     if (!wcs_user_has_subscription($user_id) || wc_notice_count('error') > 0 || empty($_POST['_wcsnonce']) || !wp_verify_nonce($_POST['_wcsnonce'], 'wcs_edit_address')) {
         return;
     }
     $address_type = 'billing' == $address_type || 'shipping' == $address_type ? $address_type : '';
     $address_fields = WC()->countries->get_address_fields(esc_attr($_POST[$address_type . '_country']), $address_type . '_');
     $address = array();
     foreach ($address_fields as $key => $field) {
         if (isset($_POST[$key])) {
             $address[str_replace($address_type . '_', '', $key)] = woocommerce_clean($_POST[$key]);
         }
     }
     if (isset($_POST['update_all_subscriptions_addresses'])) {
         $users_subscriptions = wcs_get_users_subscriptions($user_id);
         foreach ($users_subscriptions as $subscription) {
             if ($subscription->has_status(array('active', 'on-hold'))) {
                 $subscription->set_address($address, $address_type);
             }
         }
     } elseif (isset($_POST['update_subscription_address'])) {
         $subscription = wcs_get_subscription(intval($_POST['update_subscription_address']));
         // Update the address only if the user actually owns the subscription
         if (!empty($subscription)) {
             $subscription->set_address($address, $address_type);
         }
         wp_safe_redirect($subscription->get_view_order_url());
         exit;
     }
 }