forked from woocommerce/woocommerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
woocommerce-functions.php
1264 lines (954 loc) · 42.2 KB
/
woocommerce-functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* WooCommerce Functions
*
* Hooked-in functions for WooCommerce related events on the front-end.
*
* @package WooCommerce
* @category Actions
* @author WooThemes
*/
/**
* Handle redirects before content is output - hooked into template_redirect so is_page works
**/
function woocommerce_redirects() {
global $woocommerce, $wp_query;
// When default permalinks are enabled, redirect shop page to post type archive url
if ( isset($_GET['page_id']) && $_GET['page_id'] > 0 && get_option( 'permalink_structure' )=="" && $_GET['page_id'] == woocommerce_get_page_id('shop') ) :
wp_safe_redirect( get_post_type_archive_link('product') );
exit;
endif;
// When on the checkout with an empty cart, redirect to cart page
if (is_page(woocommerce_get_page_id('checkout')) && sizeof($woocommerce->cart->get_cart())==0) :
wp_redirect(get_permalink(woocommerce_get_page_id('cart')));
exit;
endif;
// When on pay page with no query string, redirect to checkout
if (is_page(woocommerce_get_page_id('pay')) && !isset($_GET['order'])) :
wp_redirect(get_permalink(woocommerce_get_page_id('checkout')));
exit;
endif;
// My account page redirects (logged out)
if (!is_user_logged_in() && ( is_page(woocommerce_get_page_id('edit_address')) || is_page(woocommerce_get_page_id('view_order')) || is_page(woocommerce_get_page_id('change_password')) )) :
wp_redirect(get_permalink(woocommerce_get_page_id('myaccount')));
exit;
endif;
// Redirect to the product page if we have a single product
if (is_search() && is_post_type_archive('product') && get_option('woocommerce_redirect_on_single_search_result')=='yes') {
if ($wp_query->post_count==1) {
$product = new WC_Product($wp_query->post->ID);
if ($product->is_visible()) wp_safe_redirect( get_permalink($product->id), 302 );
exit;
}
}
}
/**
* Fix active class in nav for shop page
**/
function woocommerce_nav_menu_item_classes( $menu_items, $args ) {
if (!is_woocommerce()) return $menu_items;
$shop_page = (int) woocommerce_get_page_id('shop');
$page_for_posts = (int) get_option( 'page_for_posts' );
foreach ( (array) $menu_items as $key => $menu_item ) :
$classes = (array) $menu_item->classes;
// Unset active class for blog page
if ( $page_for_posts == $menu_item->object_id ) :
$menu_items[$key]->current = false;
unset( $classes[ array_search('current_page_parent', $classes) ] );
unset( $classes[ array_search('current-menu-item', $classes) ] );
// Set active state if this is the shop page link
elseif ( is_shop() && $shop_page == $menu_item->object_id ) :
$menu_items[$key]->current = true;
$classes[] = 'current-menu-item';
$classes[] = 'current_page_item';
endif;
$menu_items[$key]->classes = array_unique( $classes );
endforeach;
return $menu_items;
}
/**
* Detect frontpage shop and fix pagination on static front page
**/
function woocommerce_front_page_archive_paging_fix() {
if ( is_front_page() && is_page( woocommerce_get_page_id('shop') )) :
if (get_query_var('paged')) :
$paged = get_query_var('paged');
else :
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
endif;
global $wp_query;
$wp_query->query( array( 'page_id' => woocommerce_get_page_id('shop'), 'is_paged' => true, 'paged' => $paged ) );
define('SHOP_IS_ON_FRONT', true);
endif;
}
/**
* Front page archive/shop template applied to main loop
*/
function woocommerce_front_page_archive( $query ) {
global $paged, $woocommerce, $wp_query;
// Only apply to front_page
if ( defined('SHOP_IS_ON_FRONT') && is_main_query() ) :
if (get_query_var('paged')) :
$paged = get_query_var('paged');
else :
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
endif;
// Filter the query
add_filter( 'pre_get_posts', array( &$woocommerce->query, 'pre_get_posts') );
// Query the products
$wp_query->query( array( 'page_id' => '', 'p' => '', 'post_type' => 'product', 'paged' => $paged ) );
// get products in view (for use by widgets)
$woocommerce->query->get_products_in_view();
// Remove the query manipulation
remove_filter( 'pre_get_posts', array( &$woocommerce->query, 'pre_get_posts') );
remove_action( 'loop_start', 'woocommerce_front_page_archive', 1);
endif;
}
/**
* Fix active class in wp_list_pages for shop page
*
* Suggested by jessor - https://github.com/woothemes/woocommerce/issues/177
* Amended Dec '11, by Peter Sterling - http://www.sterling-adventures.co.uk/
**/
function woocommerce_list_pages($pages){
global $post;
if (is_woocommerce()) {
$pages = str_replace( 'current_page_parent', '', $pages); // remove current_page_parent class from any item
$shop_page = 'page-item-' . woocommerce_get_page_id('shop'); // find shop_page_id through woocommerce options
if (is_shop()) :
$pages = str_replace($shop_page, $shop_page . ' current_page_item', $pages); // add current_page_item class to shop page
else :
$pages = str_replace($shop_page, $shop_page . ' current_page_parent', $pages); // add current_page_parent class to shop page
endif;
}
return $pages;
}
/**
* Add logout link to my account menu
**/
function woocommerce_nav_menu_items( $items, $args ) {
if ( get_option('woocommerce_menu_logout_link')=='yes' && strstr($items, get_permalink(woocommerce_get_page_id('myaccount'))) && is_user_logged_in() ) :
$items .= '<li><a href="'. wp_logout_url(home_url()) .'">'.__('Logout', 'woocommerce').'</a></li>';
endif;
return $items;
}
/**
* Update catalog ordering if posted
*/
function woocommerce_update_catalog_ordering() {
if (isset($_REQUEST['sort']) && $_REQUEST['sort'] != '') $_SESSION['orderby'] = esc_attr($_REQUEST['sort']);
}
/**
* Increase coupon usage count
*/
function woocommerce_increase_coupon_counts() {
global $woocommerce;
if ($applied_coupons = $woocommerce->cart->get_applied_coupons()) foreach ($applied_coupons as $code) :
$coupon = new WC_Coupon( $code );
$coupon->inc_usage_count();
endforeach;
}
/**
* Remove from cart/update
**/
function woocommerce_update_cart_action() {
global $woocommerce;
// Remove from cart
if ( isset($_GET['remove_item']) && $_GET['remove_item'] && $woocommerce->verify_nonce('cart', '_GET')) :
$woocommerce->cart->set_quantity( $_GET['remove_item'], 0 );
$woocommerce->add_message( __('Cart updated.', 'woocommerce') );
$referer = ( wp_get_referer() ) ? wp_get_referer() : $woocommerce->cart->get_cart_url();
wp_safe_redirect( $referer );
exit;
// Update Cart
elseif (isset($_POST['update_cart']) && $_POST['update_cart'] && $woocommerce->verify_nonce('cart')) :
$cart_totals = $_POST['cart'];
if (sizeof($woocommerce->cart->get_cart())>0) :
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) :
$_product = $values['data'];
// Skip product if no updated quantity was posted
if ( ! isset( $cart_totals[$cart_item_key]['qty'] ) )
continue;
// Clean the quantity input
$quantity = absint( $cart_totals[$cart_item_key]['qty'] );
// Update cart validation
$passed_validation = apply_filters('woocommerce_update_cart_validation', true, $cart_item_key, $values, $quantity);
// Check downloadable items
if ( get_option('woocommerce_limit_downloadable_product_qty')=='yes' ) :
if ( $_product->is_downloadable() && $_product->is_virtual() && $quantity > 1 ) :
$woocommerce->add_error( sprintf(__('You can only have 1 %s in your cart.', 'woocommerce'), $_product->get_title()) );
$passed_validation = false;
endif;
endif;
if ($passed_validation) {
$woocommerce->cart->set_quantity( $cart_item_key, $quantity );
}
endforeach;
endif;
$woocommerce->add_message( __('Cart updated.', 'woocommerce') );
$referer = ( wp_get_referer() ) ? wp_get_referer() : $woocommerce->cart->get_cart_url();
wp_safe_redirect( $referer );
exit;
endif;
}
/**
* Add to cart action
*
* Checks for a valid request, does validation (via hooks) and then redirects if valid
**/
function woocommerce_add_to_cart_action( $url = false ) {
global $woocommerce;
if (empty($_REQUEST['add-to-cart']) || !$woocommerce->verify_nonce('add_to_cart', '_REQUEST')) return;
$added_to_cart = false;
switch ($_REQUEST['add-to-cart']) {
// Variable Products
case 'variation' :
// Only allow integer variation ID - if its not set, redirect to the product page
if (empty($_REQUEST['variation_id']) || !is_numeric($_REQUEST['variation_id']) || $_REQUEST['variation_id']<1) {
$woocommerce->add_error( __('Please choose product options…', 'woocommerce') );
wp_redirect(apply_filters('woocommerce_add_to_cart_product_id', get_permalink($_REQUEST['product_id'])));
exit;
}
// Get product ID to add and quantity
$product_id = (int) apply_filters('woocommerce_add_to_cart_product_id', $_REQUEST['product_id']);
$variation_id = (int) $_REQUEST['variation_id'];
$quantity = (isset($_REQUEST['quantity'])) ? (int) $_REQUEST['quantity'] : 1;
$attributes = (array) maybe_unserialize(get_post_meta($product_id, '_product_attributes', true));
$variations = array();
$all_variations_set = true;
// Verify all attributes for the variable product were set
foreach ($attributes as $attribute) {
if ( !$attribute['is_variation'] ) continue;
$taxonomy = 'attribute_' . sanitize_title($attribute['name']);
if (!empty($_REQUEST[$taxonomy])) {
// Get value from post data
$value = esc_attr(stripslashes($_REQUEST[$taxonomy]));
// Use name so it looks nicer in the cart widget/order page etc - instead of a sanitized string
$variations[esc_attr($attribute['name'])] = $value;
} else {
$all_variations_set = false;
}
}
if ($all_variations_set) {
// Add to cart validation
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
if ($passed_validation) {
if ($woocommerce->cart->add_to_cart($product_id, $quantity, $variation_id, $variations)) {
woocommerce_add_to_cart_message();
$added_to_cart = true;
}
}
} else {
$woocommerce->add_error( __('Please choose product options…', 'woocommerce') );
wp_redirect(apply_filters('woocommerce_add_to_cart_product_id', get_permalink($_REQUEST['product_id'])));
exit;
}
break;
// Grouped Products
case 'group' :
if (isset($_REQUEST['quantity']) && is_array($_REQUEST['quantity'])) {
$quantity_set = false;
foreach ($_REQUEST['quantity'] as $item => $quantity) {
if ($quantity<1) continue;
$quantity_set = true;
// Add to cart validation
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $item, $quantity);
if ($passed_validation) {
if ($woocommerce->cart->add_to_cart($item, $quantity)) {
woocommerce_add_to_cart_message();
$added_to_cart = true;
}
}
}
if (!$added_to_cart && !$quantity_set) {
$woocommerce->add_error( __('Please choose a quantity…', 'woocommerce') );
wp_redirect(apply_filters('woocommerce_add_to_cart_product_id', get_permalink($_REQUEST['product_id'])));
exit;
}
} elseif ($_REQUEST['product_id']) {
/* Link on product archives */
$woocommerce->add_error( __('Please choose a product…', 'woocommerce') );
wp_redirect( get_permalink( $_REQUEST['product_id'] ) );
exit;
}
break;
// Simple Products - add-to-cart contains product ID
default :
// Only allow integers
if (!is_numeric($_REQUEST['add-to-cart'])) break;
// Get product ID to add and quantity
$product_id = (int) $_REQUEST['add-to-cart'];
$quantity = (isset($_REQUEST['quantity'])) ? (int) $_REQUEST['quantity'] : 1;
// Add to cart validation
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
if ($passed_validation) {
// Add the product to the cart
if ($woocommerce->cart->add_to_cart($_REQUEST['add-to-cart'], $quantity)) {
woocommerce_add_to_cart_message();
$added_to_cart = true;
}
}
break;
}
// If we added the product to the cart we can now do a redirect, otherwise just continue loading the page to show errors
if ($added_to_cart) {
$url = apply_filters('add_to_cart_redirect', $url);
// If has custom URL redirect there
if ( $url ) {
wp_safe_redirect( $url );
exit;
}
// Redirect to cart option
elseif (get_option('woocommerce_cart_redirect_after_add')=='yes' && $woocommerce->error_count() == 0) {
wp_safe_redirect( $woocommerce->cart->get_cart_url() );
exit;
}
}
}
/**
* Add to cart messages
**/
function woocommerce_add_to_cart_message() {
global $woocommerce;
// Output success messages
if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
$return_to = (wp_get_referer()) ? wp_get_referer() : home_url();
$message = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
else :
$message = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
endif;
$woocommerce->add_message( apply_filters('woocommerce_add_to_cart_message', $message) );
}
/**
* Clear cart after payment
**/
function woocommerce_clear_cart_after_payment() {
global $woocommerce;
if (is_page(woocommerce_get_page_id('thanks'))) :
if (isset($_GET['order'])) $order_id = $_GET['order']; else $order_id = 0;
if (isset($_GET['key'])) $order_key = $_GET['key']; else $order_key = '';
if ($order_id > 0) :
$order = new WC_Order( $order_id );
if ($order->order_key == $order_key) :
$woocommerce->cart->empty_cart();
unset($_SESSION['order_awaiting_payment']);
endif;
endif;
endif;
if (isset($_SESSION['order_awaiting_payment']) && $_SESSION['order_awaiting_payment'] > 0) :
$order = new WC_Order($_SESSION['order_awaiting_payment']);
if ($order->id > 0 && $order->status!=='pending') :
$woocommerce->cart->empty_cart();
unset($_SESSION['order_awaiting_payment']);
endif;
endif;
}
/**
* Process the checkout form
**/
function woocommerce_checkout_action() {
global $woocommerce;
if (isset($_POST['woocommerce_checkout_place_order']) || isset($_POST['woocommerce_checkout_update_totals'])) :
if (sizeof($woocommerce->cart->get_cart())==0) :
wp_redirect(get_permalink(woocommerce_get_page_id('cart')));
exit;
endif;
if (!defined('WOOCOMMERCE_CHECKOUT')) define('WOOCOMMERCE_CHECKOUT', true);
$woocommerce_checkout = $woocommerce->checkout();
$woocommerce_checkout->process_checkout();
endif;
}
/**
* Process the pay form
**/
function woocommerce_pay_action() {
global $woocommerce;
if (isset($_POST['woocommerce_pay']) && $woocommerce->verify_nonce('pay')) :
ob_start();
// Pay for existing order
$order_key = urldecode( $_GET['order'] );
$order_id = (int) $_GET['order_id'];
$order = new WC_Order( $order_id );
if ($order->id == $order_id && $order->order_key == $order_key && in_array($order->status, array('pending', 'failed'))) :
// 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 );
// Update payment method
if ($order->order_total > 0 ) :
$payment_method = woocommerce_clean($_POST['payment_method']);
$available_gateways = $woocommerce->payment_gateways->get_available_payment_gateways();
// Update meta
update_post_meta( $order_id, '_payment_method', $payment_method);
if (isset($available_gateways) && isset($available_gateways[$payment_method])) :
$payment_method_title = $available_gateways[$payment_method]->title;
endif;
update_post_meta( $order_id, '_payment_method_title', $payment_method_title);
$result = $available_gateways[$payment_method]->process_payment( $order_id );
// Redirect to success/confirmation/payment page
if ($result['result']=='success') :
wp_redirect( $result['redirect'] );
exit;
endif;
else :
// No payment was required for order
$order->payment_complete();
wp_safe_redirect( get_permalink(woocommerce_get_page_id('thanks')) );
exit;
endif;
endif;
endif;
}
/**
* Process the login form
**/
function woocommerce_process_login() {
global $woocommerce;
if (isset($_POST['login']) && $_POST['login']) :
$woocommerce->verify_nonce('login');
if ( !isset($_POST['username']) || empty($_POST['username']) ) $woocommerce->add_error( __('Username is required.', 'woocommerce') );
if ( !isset($_POST['password']) || empty($_POST['password']) ) $woocommerce->add_error( __('Password is required.', 'woocommerce') );
if ($woocommerce->error_count()==0) :
$creds = array();
$creds['user_login'] = esc_attr($_POST['username']);
$creds['user_password'] = esc_attr($_POST['password']);
$creds['remember'] = true;
$secure_cookie = is_ssl() ? true : false;
$user = wp_signon( $creds, $secure_cookie );
if ( is_wp_error($user) ) :
$woocommerce->add_error( $user->get_error_message() );
else :
if (isset($_POST['redirect']) && $_POST['redirect']) :
wp_safe_redirect( esc_attr($_POST['redirect']) );
exit;
endif;
if ( wp_get_referer() ) :
wp_safe_redirect( wp_get_referer() );
exit;
endif;
wp_redirect(get_permalink(woocommerce_get_page_id('myaccount')));
exit;
endif;
endif;
endif;
}
/**
* Process the coupon form on the checkout and cart
**/
function woocommerce_process_coupon_form() {
global $woocommerce;
// Do nothing if coupons are globally disabled
if ( get_option( 'woocommerce_enable_coupons' ) == 'no' ) return;
if (isset($_POST['coupon_code']) && $_POST['coupon_code']) :
$coupon_code = stripslashes(trim($_POST['coupon_code']));
$woocommerce->cart->add_discount($coupon_code);
if ( wp_get_referer() ) :
wp_safe_redirect( remove_query_arg('remove_discounts', wp_get_referer()) );
exit;
endif;
endif;
}
/**
* Process the registration form
**/
function woocommerce_process_registration() {
global $woocommerce;
if (isset($_POST['register']) && $_POST['register']) :
$woocommerce->verify_nonce('register');
// Get fields
$username = (isset($_POST['username'])) ? esc_attr(trim($_POST['username'])) : '';
$sanitized_user_login = sanitize_user($username);
$user_email = (isset($_POST['email'])) ? esc_attr(trim($_POST['email'])) : '';
$password = (isset($_POST['password'])) ? esc_attr(trim($_POST['password'])) : '';
$password2 = (isset($_POST['password2'])) ? esc_attr(trim($_POST['password2'])) : '';
$user_email = apply_filters( 'user_registration_email', $user_email );
// Check the username
if ( $sanitized_user_login == '' ) {
$woocommerce->add_error( '<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __( 'Please enter a username.', 'woocommerce' ) );
} elseif ( ! validate_username( $username ) ) {
$woocommerce->add_error( '<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __( 'This username is invalid because it uses illegal characters. Please enter a valid username.', 'woocommerce' ) );
$sanitized_user_login = '';
} elseif ( username_exists( $sanitized_user_login ) ) {
$woocommerce->add_error( '<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __( 'This username is already registered, please choose another one.', 'woocommerce' ) );
}
// Check the e-mail address
if ( $user_email == '' ) {
$woocommerce->add_error( '<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __( 'Please type your e-mail address.', 'woocommerce' ) );
} elseif ( ! is_email( $user_email ) ) {
$woocommerce->add_error( '<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __( 'The email address isn’t correct.', 'woocommerce' ) );
$user_email = '';
} elseif ( email_exists( $user_email ) ) {
$woocommerce->add_error( '<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __( 'This email is already registered, please choose another one.', 'woocommerce' ) );
}
// Password
if ( !$password ) $woocommerce->add_error( __('Password is required.', 'woocommerce') );
if ( !$password2 ) $woocommerce->add_error( __('Re-enter your password.', 'woocommerce') );
if ( $password != $password2 ) $woocommerce->add_error( __('Passwords do not match.', 'woocommerce') );
// Spam trap
if (isset($_POST['email_2']) && $_POST['email_2']) $woocommerce->add_error( __('Anti-spam field was filled in.', 'woocommerce') );
if ($woocommerce->error_count()==0) :
$reg_errors = new WP_Error();
do_action('register_post', $sanitized_user_login, $user_email, $reg_errors);
$reg_errors = apply_filters( 'registration_errors', $reg_errors, $sanitized_user_login, $user_email );
// if there are no errors, let's create the user account
if ( !$reg_errors->get_error_code() ) :
$user_id = wp_create_user( $sanitized_user_login, $password, $user_email );
if ( !$user_id ) {
$woocommerce->add_error( '<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __('Couldn’t register you... please contact us if you continue to have problems.', 'woocommerce') );
return;
}
// Change role
wp_update_user( array ('ID' => $user_id, 'role' => 'customer') ) ;
// send the user a confirmation and their login details
$mailer = $woocommerce->mailer();
$mailer->customer_new_account( $user_id, $password );
// set the WP login cookie
$secure_cookie = is_ssl() ? true : false;
wp_set_auth_cookie($user_id, true, $secure_cookie);
// Redirect
if ( wp_get_referer() ) :
wp_safe_redirect( wp_get_referer() );
exit;
endif;
wp_redirect(get_permalink(woocommerce_get_page_id('myaccount')));
exit;
else :
$woocommerce->add_error( $reg_errors->get_error_message() );
return;
endif;
endif;
endif;
}
/**
* Place a previous order again
**/
function woocommerce_order_again() {
global $woocommerce;
// Nothing to do
if ( ! isset( $_GET['order_again'] ) || ! is_user_logged_in() || get_option('woocommerce_allow_customers_to_reorder') == 'no' ) return;
// Nonce security check
if ( ! $woocommerce->verify_nonce( 'order_again', '_GET' ) ) return;
// Load the previous order - Stop if the order does not exist
$order = new WC_Order( (int) $_GET['order_again'] );
if ( empty( $order->id ) ) return;
if ( $order->status!='completed' ) return;
// Make sure the previous order belongs to the current customer
if ( $order->user_id != get_current_user_id() ) return;
// Copy products from the order to the cart
foreach ( $order->get_items() as $item ) {
// Load all product info including variation data
$product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $item['id'] );
$quantity = (int) $item['qty'];
$variation_id = (int) $item['variation_id'];
$variations = array();
foreach ( $item['item_meta'] as $meta ) {
if ( ! substr( $meta['meta_name'], 0, 3) === 'pa_' ) continue;
$variations[$meta['meta_name']] = $meta['meta_value'];
}
// Add to cart validation
if ( ! apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity ) ) continue;
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations );
}
// Redirect to cart
$woocommerce->add_message( __('The cart has been filled with the items from your previous order.', 'woocommerce' ) );
wp_safe_redirect( $woocommerce->cart->get_cart_url() );
exit;
}
/**
* Cancel a pending order
**/
function woocommerce_cancel_order() {
global $woocommerce;
if ( isset($_GET['cancel_order']) && isset($_GET['order']) && isset($_GET['order_id']) ) :
$order_key = urldecode( $_GET['order'] );
$order_id = (int) $_GET['order_id'];
$order = new WC_Order( $order_id );
if ($order->id == $order_id && $order->order_key == $order_key && in_array($order->status, array('pending', 'failed')) && $woocommerce->verify_nonce('cancel_order', '_GET')) :
// Cancel the order + restore stock
$order->cancel_order( __('Order cancelled by customer.', 'woocommerce') );
// Message
$woocommerce->add_message( __('Your order was cancelled.', 'woocommerce') );
elseif ($order->status!='pending') :
$woocommerce->add_error( __('Your order is no longer pending and could not be cancelled. Please contact us if you need assistance.', 'woocommerce') );
else :
$woocommerce->add_error( __('Invalid order.', 'woocommerce') );
endif;
wp_safe_redirect($woocommerce->cart->get_cart_url());
exit;
endif;
}
/**
* Download a file - hook into init function
**/
function woocommerce_download_product() {
if ( isset($_GET['download_file']) && isset($_GET['order']) && isset($_GET['email']) ) :
global $wpdb;
$download_file = (int) urldecode($_GET['download_file']);
$order_key = urldecode( $_GET['order'] );
$email = urldecode( $_GET['email'] );
if (!is_email($email)) :
wp_die( __('Invalid email address.', 'woocommerce') . ' <a href="'.home_url().'">' . __('Go to homepage →', 'woocommerce') . '</a>' );
endif;
$download_result = $wpdb->get_row( $wpdb->prepare("
SELECT order_id, downloads_remaining,user_id,download_count,access_expires
FROM ".$wpdb->prefix."woocommerce_downloadable_product_permissions
WHERE user_email = %s
AND order_key = %s
AND product_id = %s
;", $email, $order_key, $download_file ) );
if (!$download_result) :
wp_die( __('Invalid download.', 'woocommerce') . ' <a href="'.home_url().'">' . __('Go to homepage →', 'woocommerce') . '</a>' );
exit;
endif;
$order_id = $download_result->order_id;
$downloads_remaining = $download_result->downloads_remaining;
$download_count = $download_result->download_count;
$user_id = $download_result->user_id;
$access_expires = $download_result->access_expires;
if ($user_id && get_option('woocommerce_downloads_require_login')=='yes'):
if (!is_user_logged_in()):
wp_die( __('You must be logged in to download files.', 'woocommerce') . ' <a href="'.wp_login_url(get_permalink(woocommerce_get_page_id('myaccount'))).'">' . __('Login →', 'woocommerce') . '</a>' );
exit;
else:
$current_user = wp_get_current_user();
if($user_id != $current_user->ID):
wp_die( __('This is not your download link.', 'woocommerce'));
exit;
endif;
endif;
endif;
if ($order_id) :
$order = new WC_Order( $order_id );
if ($order->status!='completed' && $order->status!='processing' && $order->status!='publish') :
wp_die( __('Invalid order.', 'woocommerce') . ' <a href="'.home_url().'">' . __('Go to homepage →', 'woocommerce') . '</a>' );
exit;
endif;
endif;
if ($downloads_remaining=='0') :
wp_die( __('Sorry, you have reached your download limit for this file', 'woocommerce') . ' <a href="'.home_url().'">' . __('Go to homepage →', 'woocommerce') . '</a>' );
exit;
endif;
if ($access_expires > 0 && strtotime($access_expires) < current_time('timestamp')) :
wp_die( __('Sorry, this download has expired', 'woocommerce') . ' <a href="'.home_url().'">' . __('Go to homepage →', 'woocommerce') . '</a>' );
exit;
endif;
if ($downloads_remaining>0) :
$wpdb->update( $wpdb->prefix . "woocommerce_downloadable_product_permissions", array(
'downloads_remaining' => $downloads_remaining - 1,
), array(
'user_email' => $email,
'order_key' => $order_key,
'product_id' => $download_file
), array( '%d' ), array( '%s', '%s', '%d' ) );
endif;
// Count the download
$wpdb->update( $wpdb->prefix . "woocommerce_downloadable_product_permissions", array(
'download_count' => $download_count + 1,
), array(
'user_email' => $email,
'order_key' => $order_key,
'product_id' => $download_file
), array( '%d' ), array( '%s', '%s', '%d' ) );
// Get the downloads URL and try to replace the url with a path
$file_path = apply_filters('woocommerce_file_download_path', get_post_meta($download_file, '_file_path', true), $download_file);
if (!$file_path) exit;
$file_download_method = apply_filters('woocommerce_file_download_method', get_option('woocommerce_file_download_method'), $download_file);
if ($file_download_method=='redirect') :
header('Location: '.$file_path);
exit;
endif;
// Get URLS with https
$site_url = site_url();
$network_url = network_admin_url();
if (is_ssl()) :
$site_url = str_replace('https:', 'http:', $site_url);
$network_url = str_replace('https:', 'http:', $network_url);
endif;
if (!is_multisite()) :
$file_path = str_replace(trailingslashit($site_url), ABSPATH, $file_path);
else :
$upload_dir = wp_upload_dir();
// Try to replace network url
$file_path = str_replace(trailingslashit($network_url), ABSPATH, $file_path);
// Now try to replace upload URL
$file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $file_path);
endif;
// See if its local or remote
if (strstr($file_path, 'http:') || strstr($file_path, 'https:') || strstr($file_path, 'ftp:')) :
$remote_file = true;
else :
$remote_file = false;
$file_path = realpath($file_path);
endif;
// Download the file
$file_extension = strtolower(substr(strrchr($file_path,"."),1));
$ctype = "application/force-download";
foreach (get_allowed_mime_types() as $mime => $type) :
$mimes = explode('|', $mime);
if (in_array($file_extension, $mimes)) :
$ctype = $type;
break;
endif;
endforeach;
if ($file_download_method=='xsendfile') :
if (getcwd()) :
// Path fix - kudos to Jason Judge
$file_path = trim(preg_replace( '`^' . getcwd() . '`' , '', $file_path ), '/');
endif;
header("Content-Disposition: attachment; filename=\"".basename($file_path)."\";");
if (function_exists('apache_get_modules') && in_array( 'mod_xsendfile', apache_get_modules()) ) :
header("X-Sendfile: $file_path");
exit;
elseif (stristr(getenv('SERVER_SOFTWARE'), 'lighttpd') ) :
header("X-Lighttpd-Sendfile: $file_path");
exit;
elseif (stristr(getenv('SERVER_SOFTWARE'), 'nginx') || stristr(getenv('SERVER_SOFTWARE'), 'cherokee')) :
header("X-Accel-Redirect: $file_path");
exit;
endif;
endif;
/**
* readfile_chunked
*
* Reads file in chunks so big downloads are possible without changing PHP.INI - http://codeigniter.com/wiki/Download_helper_for_large_files/
*
* @access public
* @param string file
* @param boolean return bytes of file
* @return void
*/
if ( ! function_exists('readfile_chunked')) {
function readfile_chunked($file, $retbytes=TRUE) {
$chunksize = 1 * (1024 * 1024);
$buffer = '';
$cnt = 0;
$handle = fopen($file, 'r');
if ($handle === FALSE) return FALSE;
while (!feof($handle)) :
$buffer = fread($handle, $chunksize);
echo $buffer;
ob_flush();
flush();
if ($retbytes) $cnt += strlen($buffer);
endwhile;
$status = fclose($handle);
if ($retbytes AND $status) return $cnt;
return $status;
}
}
@session_write_close();
if (function_exists('apache_setenv')) @apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 'Off');