· 8 years ago · Aug 06, 2018, 08:54 AM
1<?php
2/*
3Plugin Name: Golfstar
4Description: WordPress plugin for golfstar.
5Version: 1.0
6Author: Miracle Mill
7*/
8
9
10defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
11
12
13function load_general_scripts()
14{
15 // Register the script like this for a plugin:
16 if(!is_user_logged_in()) {
17 wp_enqueue_script( 'logout-if-needed.js', plugins_url( 'logout-if-needed.js', __FILE__ ) );
18 }
19}
20add_action( 'wp_enqueue_scripts', 'load_general_scripts' );
21
22/* Configuration page starts */
23add_action('admin_menu', 'add_configuration_page');
24add_action( 'admin_init', 'page_init');
25
26$options;
27
28
29function add_configuration_page() {
30 add_menu_page(
31 'Configuration: General settings',
32 'Configuration',
33 'manage_options',
34 'configuration_environments',
35 'create_configuration_page'
36 );
37}
38
39function create_configuration_page(){
40 // Set class property
41 $options = get_option( 'my_option_name' );
42 echo('<div class="wrap"> <h1>Configuration Page</h1><form method="post" action="options.php">');
43 // This prints out all hidden setting fields
44 settings_fields( 'my_option_group' );
45 do_settings_sections( 'configuration_environments' );
46 settings_errors();
47 submit_button();
48 echo(' </form></div>');
49}
50
51function page_init(){
52 register_setting(
53 'my_option_group',
54 'my_option_name',
55 'sanitize'
56 );
57
58 add_settings_section(
59 'setting_section_id', // ID
60 'Configuration Settings', // Title
61 'print_section_info', // Callback
62 'configuration_environments' // Page
63 );
64
65 add_settings_field(
66 'product_id',
67 'Product ID',
68 'id_product_callback',
69 'configuration_environments',
70 'setting_section_id'
71 );
72
73 add_settings_field(
74 'api_key',
75 'API Key',
76 'api_key_callback',
77 'configuration_environments',
78 'setting_section_id'
79 );
80
81 add_settings_field(
82 'base_url',
83 'Base URL',
84 'base_url_callback',
85 'configuration_environments',
86 'setting_section_id'
87 );
88}
89
90
91function sanitize( $input ){
92 $new_input = array();
93 if( isset( $input['product_id'] ) )
94 $new_input['product_id'] = absint( $input['product_id'] );
95
96 if( isset( $input['api_key'] ) )
97 $new_input['api_key'] = sanitize_text_field( $input['api_key'] );
98
99 if( isset( $input['base_url'] ) )
100 $new_input['base_url'] = sanitize_text_field( $input['base_url'] );
101
102 return $new_input;
103}
104
105function print_section_info(){
106 echo 'Enter the settings below:';
107}
108
109function id_product_callback(){
110 $product_id = get_option( 'my_option_name' )['product_id'];
111 printf(
112 '<input type="text" id="product_id" name="my_option_name[product_id]" value="%s" />',
113 $product_id ? $product_id : ''
114 );
115}
116
117function api_key_callback(){
118 $api_key = get_option( 'my_option_name' )['api_key'];
119 printf(
120 '<input type="text" id="api_key" name="my_option_name[api_key]" value="%s" />',
121 $api_key ? $api_key : ''
122 );
123}
124
125function base_url_callback(){
126 $base_url = get_option( 'my_option_name' )['base_url'];
127 printf(
128 '<input type="text" id="base_url" name="my_option_name[base_url]" value="%s" />',
129 $base_url ? $base_url : ''
130 );
131}
132
133
134/* Configuration page ends */
135
136function initAngular(){
137 wp_enqueue_script( 'inline.bundle.js', plugins_url( '/ng/inline.bundle.js', __FILE__ ) );
138 wp_enqueue_script( 'polyfills.bundle.js', plugins_url( '/ng/polyfills.bundle.js', __FILE__ ) );
139 // wp_enqueue_script( 'styles.bundle.js', plugins_url( '/ng/styles.bundle.js', __FILE__ ) );
140 //wp_enqueue_script( 'vendor.bundle.js', plugins_url( '/ng/vendor.bundle.js', __FILE__ ) );
141
142 wp_enqueue_style( 'styles.bundle.css', plugins_url( '/ng/styles.bundle.css', __FILE__ ) );
143
144 $query = new WP_Query(array(
145 'post_type' => 'avada_portfolio',
146 'posts_per_page' => -1,
147 'post_status' => 'publish',
148 'meta_query' => array(
149 array(
150 'key' => 'gs_locationid',
151 'compare' => 'EXISTS'
152 ),
153 )
154 ));
155
156
157 $posts = $query->posts;
158
159 $postsArray = array();
160
161 foreach($posts as &$post) {
162
163 $tags = wp_get_post_terms($post->ID, 'portfolio_tags');
164
165 $short_tags = array();
166 foreach ($tags as $tag) {
167 $short_tags[] = $tag->name;
168 }
169
170 foreach(get_post_meta($post->ID, 'gs_locationid', false) as $locationid) {
171
172 $terms = wp_get_post_terms($post->ID, 'portfolio_category');
173
174
175
176
177 $postsArray[$locationid] = array(
178 'postID' => $post->ID,
179 'title' => $post->post_title,
180 'tags' => $short_tags,
181 'weather_snippet' => get_post_meta($post->ID, 'gs_weather_snippet', true),
182 'map_address' => get_post_meta($post->ID, 'gs_address', true),
183 'content' => get_post_field('post_content', $post->ID),
184 'content_short' => get_the_excerpt($post->ID),
185 'designer' => get_post_meta($post->ID, 'gs_designer', true),
186 'opening_year' => get_post_meta($post->ID, 'gs_opening_year', true),
187 'course_layout' => get_post_meta($post->ID, 'gs_course_layout', true),
188 'image' => wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' )[0]
189 );
190
191 $course_site_post = get_post_meta($post->ID, 'gs_more_info_link', true);
192
193 if (!empty($course_site_post)) {
194 $postsArray[$locationid]['link'] = get_permalink(intval($course_site_post));
195 }
196
197
198 }
199 }
200
201 wp_register_script( 'main.bundle.js', plugins_url( '/ng/main.bundle.js', __FILE__ ));
202 wp_localize_script( 'main.bundle.js', 'gs_wpApiSettings', array('token' => $_SESSION['token'], 'courses' => $postsArray, 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
203 wp_enqueue_script( 'main.bundle.js');
204
205}
206
207
208function golfstar_show_booking_in_svea() {
209
210 $cart = WC()->cart->get_cart();
211
212 $first_cart_item = reset($cart);
213
214 $product_id = get_option( 'my_option_name' )['product_id'];
215
216 if($product_id && $first_cart_item['product_id'] == $product_id){
217
218// if ($first_cart_item['product_id'] == 30298) {
219
220
221 $date = DateTime::createFromFormat('Y-m-d\TH:i:s.u+', $first_cart_item['date']);
222
223
224 // set to user's timezone
225 $date -> setTimeZone(new DateTimeZone('Europe/Stockholm'));
226
227 echo '<tr class="course_details_row"><td class="course_details_cell">'. $first_cart_item['courseName']. '<br /> ' . $date-> format('Y-m-d') . '<br /> ' . $date-> format('H:i') .'</td>
228 <td class="course_details_cell"></td>
229 </tr>';
230 }
231}
232add_action( 'woocommerce_review_order_before_cart_contents', 'golfstar_show_booking_in_svea', 10, 0 );
233
234function filter_woocommerce_checkout_cart_item_quantity( $strong_class_product_quantity_sprintf_times_s_cart_item_quantity_strong, $cart_item, $cart_item_key ) {
235 // make filter magic happen here...
236 $product_id = get_option( 'my_option_name' )['product_id'];
237 if($product_id && $cart_item['product_id'] == $product_id){
238// if ($cart_item['product_id'] == 30298) {
239 return '';
240 }
241
242 return $cart_item['product_id'];
243// return $strong_class_product_quantity_sprintf_times_s_cart_item_quantity_strong;
244
245};
246add_filter( 'woocommerce_checkout_cart_item_quantity', 'filter_woocommerce_checkout_cart_item_quantity', 10, 3 );
247
248
249
250add_shortcode('login', function($atts = [], $content = null, $tag = ''){
251 initAngular();
252
253 $login_atts = shortcode_atts([
254 'redirecturl' => '/loggedin/',
255 ], $atts, $tag);
256
257 return '<login redirecturl="'. $login_atts['redirecturl'] . '"></login><app-root></app-root>';
258});
259
260add_shortcode('booking', function($atts = [], $content = null, $tag = ''){
261 initAngular();
262
263 $booking_atts = shortcode_atts([
264 'redirecturl' => '/summary/',
265 ], $atts, $tag);
266
267 return '<booking redirecturl="'. $booking_atts['redirecturl'] .'"></booking><app-root></app-root>';
268});
269
270add_shortcode('logbooking', function($atts = [], $content = null, $tag = ''){
271 initAngular();
272
273 $logbook_atts = shortcode_atts([
274 'redirecturl' => '/booking/',
275 'fallbackurl' => '/search/'
276 ], $atts, $tag);
277
278 return '<logbooking fallbackurl="'. $logbook_atts['fallbackurl'] . '" redirecturl="'. $logbook_atts['redirecturl'] . '"></logbooking><app-root></app-root>';
279});
280
281add_shortcode('myevents',function($atts = [], $content = null, $tag = ''){
282 initAngular();
283 $myevents_atts = shortcode_atts([
284 'fallbackurl' => '/search/',
285 ], $atts, $tag);
286 return '<myevents fallbackurl="'. $myevents_atts['fallbackurl'] . '"></myevents><app-root></app-root>';
287});
288
289add_shortcode('mygolffriends',function($atts = [], $content = null, $tag = ''){
290 initAngular();
291 $mygolffriends_atts = shortcode_atts([
292 'fallbackurl' => '/search/',
293 ], $atts, $tag);
294 return '<mygolffriends fallbackurl="'. $mygolffriends_atts['fallbackurl'] . '"></mygolffriends><app-root></app-root>';
295});
296
297
298add_shortcode('about',function(){
299 initAngular();
300 return "<about></about><app-root></app-root>";
301});
302
303add_shortcode('courseinfo',function($atts = [], $content = null, $tag = ''){
304 initAngular();
305 $courseinfo_atts = shortcode_atts([
306 'fallbackurl' => '/search/',
307 ], $atts, $tag);
308 return '<courseinfo fallbackurl="'. $courseinfo_atts['fallbackurl'] . '"></courseinfo><app-root></app-root>';
309});
310
311add_shortcode('weather',function($atts = [], $content = null, $tag = ''){
312 initAngular();
313 $weather_atts = shortcode_atts([
314 'fallbackurl' => '/search/',
315 ], $atts, $tag);
316 return '<weather fallbackurl="'. $weather_atts['fallbackurl'] . '"></weather><app-root></app-root>';
317});
318
319add_shortcode('map',function($atts = [], $content = null, $tag = ''){
320 initAngular();
321 $map_atts = shortcode_atts([
322 'fallbackurl' => '/search/',
323 ], $atts, $tag);
324 return '<map fallbackurl="'. $map_atts['fallbackurl'] . '"></map><app-root></app-root>';
325});
326
327//add_shortcode('booking-step2',function($atts = [], $content = null, $tag = ''){
328// initAngular();
329// $step2_atts = shortcode_atts([
330// 'redirecturl' => '/booking/',
331// ], $atts, $tag);
332// return '<booking-step2 redirecturl="'. $step2_atts['redirecturl'] . '"></booking-step2><app-root></app-root>';
333//});
334
335add_shortcode('search',function($atts = [], $content = null, $tag = ''){
336 initAngular();
337 $search_atts = shortcode_atts([
338 'redirecturl' => '/booking/',
339 ], $atts, $tag);
340 return '<search redirecturl="'. $search_atts['redirecturl'] . '"></search><app-root></app-root>';
341});
342
343add_shortcode('summary',function($atts = [], $content = null, $tag = ''){
344 initAngular();
345 $summary_atts = shortcode_atts([
346 'fallbackurl' => '/search/',
347 ], $atts, $tag);
348 return '<summary fallbackurl="'. $summary_atts['fallbackurl'] . '"></summary><app-root></app-root>';
349
350});
351
352add_shortcode('summaryinfo',function($atts = [], $content = null, $tag = ''){
353 initAngular();
354 $suminfo_atts = shortcode_atts([
355 'fallbackurl' => '/search/',
356 ], $atts, $tag);
357 return '<summaryinfo fallbackurl="'. $suminfo_atts['fallbackurl'] . '"></summaryinfo><app-root></app-root>';
358});
359
360
361add_shortcode('myaccount',function($atts = [], $content = null, $tag = ''){
362 initAngular();
363 $myaccount_atts = shortcode_atts([
364 'fallbackurl' => '/search/',
365 ], $atts, $tag);
366 return '<myaccount fallbackurl="'. $myaccount_atts['fallbackurl'] . '"></myaccount><app-root></app-root>';
367});
368
369add_shortcode('book-course',function($atts = [], $content = null, $tag = ''){
370 initAngular();
371 $bookCourse_atts = shortcode_atts([
372 'redirecturl' => '/booking/',
373 ], $atts, $tag);
374 return '<book-course redirecturl="'. $bookCourse_atts['redirecturl'] . '"></book-course><app-root></app-root>';
375});
376
377
378add_shortcode('search-options',function(){
379 initAngular();
380 return "<search-options></search-options><app-root></app-root>";
381});
382
383
384/* Custom API Functionality */
385add_action('rest_api_init', function () {
386 register_rest_route('wp/v2/portfolio-items', 'courses' , array(
387 'methods' => 'GET',
388 'callback' => 'getPortfolioItems'
389 ));
390});
391
392function getPortfolioItems()
393{
394 global $wpdb;
395 $posts = $wpdb->get_results("SELECT post_name FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='avada_portfolio' AND post_name LIKE 'course-%'");
396
397 if (empty($posts)) {
398 return new WP_Error(
399 'no posts from category avada_portfolio',
400 array(
401 'status' => 404
402 )
403 );
404 }
405
406 return $posts;
407}
408
409add_action('rest_api_init', function () {
410 register_rest_route('wp/v2/portfolio-category', 'courseinfo', array(
411 'methods' => 'GET',
412 'callback' => 'getCourseInfoItems',
413 'permission_callback' => function (WP_REST_Request $request) {
414 return true;
415 }
416 ));
417});
418
419function getCourseInfoItems()
420{
421 global $wpdb;
422 $posts = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='avada_portfolio' ANd post_title LIKE 'category%'");
423 $permalinks_portfolio_category_posts = [];
424 $post_permalink = [];
425 foreach ( $posts as $post ) {
426 $permalink_post = get_permalink( $post->ID );
427 $exploded_permalink_array = explode("/", $permalink_post);
428 $check_string = "category-";
429 foreach($exploded_permalink_array as $e_permalink) {
430 if($e_permalink != null) {
431 if (strpos($e_permalink, 'category') !== false) {
432 $post_title = get_the_title($post->ID);
433 $post_permalink[] = array("name" => $post_title, "slug" => $e_permalink);
434 //print_r($e_permalink);
435 }
436 }
437 }
438 }
439 return $post_permalink;
440}
441
442add_action('rest_api_init', function () {
443 register_rest_route('wp/v2/users/', 'logout', array(
444 'methods' => 'GET',
445 'callback' => 'logoutWordpressUserViaAngular'
446 ));
447});
448
449function logoutWordpressUserViaAngular() {
450 if(is_user_logged_in()) {
451 unset($_COOKIE['wp_woocommerce_session_cdcb695886249152431abff9e7a2ab3e']);
452 }
453}
454
455add_action('rest_api_init', function() {
456 register_rest_route('wc/v2/cart_meta_data', 'cartmeta', array(
457 'methods' => 'POST',
458 'callback' => 'addMetadataCartAndOrder'
459 ));
460});
461
462
463add_action( 'woocommerce_payment_complete', 'golfstar_payment_complete' );
464function golfstar_payment_complete( $order_id ){
465 $order = wc_get_order( $order_id );
466 $user = $order->get_user();
467 if( $user ){
468 // do something with the user
469 }
470
471foreach ($order->get_items() as $item_id => $item_data) {
472
473 // Get an instance of corresponding the WC_Product object
474 $product = $item_data->get_product();
475 $product_name = $product->get_name(); // Get the product name
476
477 $item_quantity = $item_data->get_quantity(); // Get the item quantity
478
479 $item_total = $item_data->get_total(); // Get the item line total
480
481 $custom_field = wc_get_order_item_meta( $item_id, 'firstName', true );
482
483 // Displaying this data (to check)
484 error_log( 'Product name: '.$custom_field.' | Quantity: '.$item_quantity.' | Item total: '. number_format( $item_total, 2 ));
485}
486
487
488
489}
490
491
492function addMetadataCartOrderLine($golfId, $timeslot, $date, $locationid, $paymethod, $firstPlayer) {
493 $base_url = get_option( 'my_option_name' )['base_url'];
494
495 $url = $base_url . "/golf/location/". $locationid ."/timeslots/".$timeslot['SlotId']."/prices/" . $golfId;
496
497 $response = wp_remote_get($url);
498 if (is_wp_error($response)) {
499
500 }
501 $course_result = json_decode($response['body'], true);
502
503 $product_id = get_option( 'my_option_name' )['product_id'];
504// $product = get_product( 30298 );
505 $product = get_product( $product_id );
506
507
508 $price = $course_result['Price'];
509
510 if ($paymethod == 'pay by play') {
511 $price = $timeslot['Greenfee'];
512 }
513
514 WC()->cart->add_to_cart( $product->get_id(), 1, 0, array(), array('unique_key' => md5( microtime().rand() ), 'price' => $price, 'firstName' => $course_result['Firstname'],
515 'lastName' => $course_result['Lastname'], 'golfId' => $golfId, 'courseName' => $course_result['Club'], 'date' => $date, 'timeSlot' => $timeslot['SlotId'], 'locationId' => $locationid, 'firstPlayer' => $firstPlayer));
516
517 return $price;
518}
519
520function getTimeSlotData($locationid, $timeslot, $date) {
521 $base_url = get_option( 'my_option_name' )['base_url'];
522
523 $response = wp_remote_post($base_url . "/golf/location/timeslots",
524 array(
525 'method' => 'POST',
526 'Locale' => "en-US",
527 'timeout' => 45,
528 'redirection' => 5,
529 'httpversion' => '1.0',
530 'blocking' => true,
531 'headers' => array(
532 'Content-Type' => 'application/json',
533 'Expect' => '',
534 ),
535 'body' => '{"locationid":'. $locationid .',"from":"'.$date-> format('Y-m-d').'","to":"2028-07-28","players":1,"playPeriod":null}', // array('from' => $date-> format('Y-m-d') , 'locationIds' => array($locationid), 'players' => 1, 'to' => "2028-5-28"),
536 'cookies' => array()
537 )
538 );
539
540 if (is_wp_error($response)) {
541 return $response;
542 }
543
544
545 $timeslot_result = json_decode($response['body'], true);
546
547 $current_timeslot = null;
548
549 foreach ($timeslot_result as $ts) {
550 if ($ts["SlotId"] == $timeslot) {
551 $current_timeslot = $ts;
552 }
553 }
554 return $current_timeslot;
555}
556
557function addMetadataCartAndOrder($data) {
558 if ($data != null) {
559 $body = $data->get_body();
560 if (empty($body)) {
561 return true;
562 }
563 }
564
565 $params = json_decode($body, true);
566
567 $timeslot = $params['slotId'];
568 $locationid = $params['locationId'];
569
570 $date = DateTime::createFromFormat('Y-m-d\TH:i:s.u+', $params['date']);
571
572 if (!$date) {
573 // return '{error:"Date not parsed"}';
574 return array('error' => 'Date not parsed');
575 }
576
577 // set to user's timezone
578 $date -> setTimeZone(new DateTimeZone('Europe/Stockholm'));
579
580 $user = wp_get_current_user();
581 if (!$user->ID) {
582 // exit if user not logged in
583 return array('error' => 'User not found');
584// header("HTTP/1.1 404 User not found");
585// exit(0);
586 }
587
588 $current_timeslot = getTimeSlotData($locationid, $timeslot, $date);
589
590 if (is_wp_error($current_timeslot)) {
591// header("HTTP/1.1 404 Timeslot not found");
592// exit(0);
593 return array('error' => 'Timeslot not found');
594
595 }
596
597 //there are more players than available places
598 if(!isTimeslotAvailable($params, $current_timeslot)){
599// header("HTTP/1.1 404 Timeslot is not available");
600// exit(0);
601 return array('error' => 'Timeslot is not available');
602 }
603
604 //user has already booked there
605 if(userAlreadyBooked($params, $current_timeslot)){
606// header("HTTP/1.1 404 You or some of your friends have already booked this tee-time.");
607// exit;
608 return array('error' => 'You or some of your friends have already booked this tee-time.');
609 }
610
611 WC()->cart->empty_cart();
612
613 $totalPrice = 0;
614
615 $totalPrice += addMetadataCartOrderLine($params['golfId1'], $current_timeslot, $params['date'], $locationid, $params['paymethod1'], $params['golfId1']);
616
617 if (array_key_exists('golfId2', $params) && strlen($params['golfId2']) > 0) {
618 $totalPrice += addMetadataCartOrderLine($params['golfId2'], $current_timeslot, $params['date'], $locationid, $params['paymethod2'], $params['golfId1']);
619 }
620 if (array_key_exists('golfId3', $params) && strlen($params['golfId3']) > 0) {
621 $totalPrice += addMetadataCartOrderLine($params['golfId3'], $current_timeslot, $params['date'], $locationid, $params['paymethod3'], $params['golfId1']);
622 }
623 if (array_key_exists('golfId4', $params) && strlen($params['golfId4']) > 0) {
624 $totalPrice += addMetadataCartOrderLine($params['golfId4'], $current_timeslot, $params['date'], $locationid, $params['paymethod4'], $params['golfId1']);
625 }
626
627 if ($totalPrice == 0) {
628
629 $cart = WC()->cart;
630 $checkout = WC()->checkout();
631 $order_id = $checkout->create_order();
632 $order = wc_get_order( $order_id );
633 update_post_meta($order_id, '_customer_user', get_current_user_id());
634 $order->calculate_totals();
635 $order->payment_complete();
636 $cart->empty_cart();
637
638 return array('status' => 'ok', 'order' => $order_id, 'redirect_to' => $order->get_checkout_order_received_url());
639 } else {
640 return array('status' => 'ok', 'order' => $order->id, 'redirect_to' => WC()->cart->get_checkout_url());
641 }
642
643}
644
645
646function isTimeslotAvailable($params, $current_timeslot){
647 $placesAvailable = $current_timeslot['PlayerCount'];
648 $newPlayers = 0;
649 for ($i=1; $i<=4; $i++) {
650 if(array_key_exists('golfId' . $i, $params) && strlen($params['golfId' . $i]) > 0){
651 $newPlayers++;
652 }
653 }
654 if($placesAvailable >= $newPlayers) {return true;}
655 return false;
656}
657
658function userAlreadyBooked($params, $current_timeslot){
659 $existingPlayers = [];
660 foreach ($current_timeslot['Players'] as $player) {
661 array_push($existingPlayers, $player['GolfId']);
662 }
663 if(!empty($existingPlayers)){
664 for ($i=1; $i<=4; $i++) {
665 if(array_key_exists('golfId' . $i, $params) && strlen($params['golfId' . $i]) > 0){
666 if (in_array($params['golfId' . $i], $existingPlayers)) {return true;}
667 }
668 }
669 }
670 return false;
671}
672
673
674add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals' );
675function before_calculate_totals( $cart_object ){
676 $product_id = get_option( 'my_option_name' )['product_id'];
677
678 foreach ( $cart_object->cart_contents as $key => $value ) {
679 if ( $product_id && $value['product_id'] == $product_id ){
680 $value['data']->set_price($value['price']);
681 }
682 }
683}
684
685
686// define the woocommerce_cart_item_name callback
687function filter_woocommerce_cart_item_name( $product_get_name, $cart_item, $cart_item_key ) {
688 $product_id = get_option( 'my_option_name' )['product_id'];
689
690 if ( $product_id && $cart_item['product_id'] == $product_id ){
691 return $cart_item['firstName'] . " " . $cart_item['lastName'] . " (" . $cart_item['golfId'] . ")";
692 }
693
694 return $product_get_name;
695};
696
697
698
699## --- New way --- ##
700add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
701function custom_checkout_create_order_line_item( $item, $cart_item_key, $cart_item, $order ) {
702 // Get a product custom field value
703 error_log( 'custom_checkout_create_order_line_item triggered: ' + $item->get_product_id());
704 $product_id = get_option( 'my_option_name' )['product_id'];
705
706 if ($product_id && $item->get_product_id() == $product_id) {
707 if($cart_item['golfId'] == $cart_item['firstPlayer']){
708 $dt = new DateTime($cart_item['date']);
709 $dt->setTimeZone(new DateTimeZone('Europe/Stockholm'));
710 $item->update_meta_data( 'Plats', $cart_item['courseName']);
711 $item->update_meta_data( 'Datum', $dt->format('Y-m-d'));
712 $item->update_meta_data( 'Klockslag', $dt->format('H:i'));
713 }
714 $item->update_meta_data( 'Namn', $cart_item['firstName'] . " " . $cart_item['lastName'] );
715 $item->update_meta_data( '_firstName', $cart_item['firstName']);
716 $item->update_meta_data( '_lastName', $cart_item['lastName']);
717 $item->update_meta_data( 'Golf-ID', $cart_item['golfId']);
718 $order->update_meta_data( '_timeSlot', $cart_item['timeSlot'] );
719 $order->update_meta_data( '_locationId', $cart_item['locationId'] );
720 $order->update_meta_data( '_date', $cart_item['date'] );
721 }
722}
723
724
725function golfstar_woocommerce_order_status_processing( $order_id, $order ) {
726
727 $timeSlot = $order->get_meta('_timeSlot');
728
729 if (strlen($timeSlot) > 0) {
730 $locationId= $order->get_meta('_locationId');
731 $date = DateTime::createFromFormat('Y-m-d\TH:i:s.u+', $order->get_meta('_date'));
732 $fullTimeSlot = getTimeSlotData($locationId, $timeSlot, $date);
733
734
735
736 error_log( "Order processing for order $order_id", 0 );
737 error_log( "Order processing for slot " . $order->get_meta('_timeSlot'), 0);
738
739
740 $locationId = $order->get_meta('_locationId');
741
742 $players = array();
743
744 $lines = $order->get_items();
745 $firstLine;
746
747 foreach ($lines as $line_item) {
748 if($line_item->get_meta('Plats')){
749 $firstLine = $line_item;
750 }
751 array_push($players, array('GolfID' => $line_item->get_meta('Golf-ID'), 'FirstName' => $line_item->get_meta('_firstName'), 'LastName' => $line_item->get_meta('_lastName')));
752 }
753
754 $base_url = get_option( 'my_option_name' )['base_url'];
755 $url = $base_url . "/golf/location/externalbook";
756 $api_key = get_option( 'my_option_name' )['api_key']; //LKAsfijisefj234234
757 $response = wp_remote_post($url, array(
758 'method' => 'POST',
759 'Locale' => "en-US",
760 'timeout' => 45,
761 'redirection' => 5,
762 'httpversion' => '1.0',
763 'blocking' => true,
764 'headers' => array(),
765 'body' => array("APIkey" => $api_key, 'TimeSlot' => $fullTimeSlot, 'LocationID' => $locationId, 'Players' => $players),
766 'cookies' => array()
767 )
768 );
769
770 if (is_wp_error($response)) {
771 error_log( "Order failed for slot " . $order->get_meta('_timeSlot') . " " . print_r( $response , true), 0);
772 } else {
773
774 $booking_result = json_decode($response['body'], true);
775
776 error_log( "Order success for slot " . $order->get_meta('_timeSlot') . " " . print_r( $booking_result , true), 0);
777 error_log( "Order completed for slot " . $order->get_meta('_timeSlot') . " " . " booking: " . $booking_result['bookingNumber'], 0);
778 if (array_key_exists('BookingNumber', $booking_result)) {
779 $order->update_meta_data( '_bookingNumber', $booking_result['BookingNumber'] );
780 $firstLine->update_meta_data( 'Bokningsnummer', $booking_result['BookingNumber'] );
781 $firstLine->save();
782 $order->update_status( 'completed' );
783 } else {
784 $firstLine->update_meta_data( '_errorMessage', $booking_result['message'] );
785 $firstLine->save();
786 }
787 }
788 }
789}
790add_action( 'woocommerce_order_status_processing', 'golfstar_woocommerce_order_status_processing', 10, 2 );
791
792
793
794// add the filter
795add_filter( 'woocommerce_cart_item_name', 'filter_woocommerce_cart_item_name', 1000, 3 );
796
797
798/* User logged in - matching values in database, if user not exists with the same email create new */
799add_action('rest_api_init', function () {
800 angular_login_js();
801 register_rest_route('wp/v2/users/', 'login', array(
802 'methods' => 'POST',
803 'callback' => 'sendUserInfoDataLoginViaAngular'
804
805 ));
806});
807
808function sendUserInfoDataLoginViaAngular($data) {
809 global $wpdb;
810 if ($data != null) {
811 $body = $data->get_body();
812 if (empty($body)) {
813 return true;
814 }
815 }
816 $params = json_decode($body, true);
817
818 $creds = array();
819 $creds['user_login'] = $params['GolfID'];
820 $creds['user_password'] = $params['Password'];
821 $creds['remember'] = true;
822 $user = wp_signon( $creds, false );
823 if ( is_wp_error($user) ) {
824 echo $user->get_error_message();
825 }
826
827
828// $userInfo = explode("@", $user_email);
829 //wp_setcookie( $userInfo[0], "", false, "", "", true );
830 //print_r("Userinfo:". $userInfo[0] );
831// wp_set_auth_cookie( 1074, "", false, "", "", true );
832// wp_redirect($_SERVER['HTTP_REFERER']);
833
834}
835
836function demo_auth($user, $username, $password)
837{
838 $regexUserChecking= '/^[0-9]{6}-[0-9]{3}$/';
839 $base_url = get_option( 'my_option_name' )['base_url'];
840 if (preg_match($regexUserChecking,
841 $username) != 0 && $base_url)
842 {
843 // email and golf id login
844 // Make sure a username and password are present for us to work with
845 if ($username == '' || $password == '') return;
846
847 $url = $base_url . "/user/git/authenticate";
848 //?GolfID=$username&Password=$password
849 $response = wp_remote_post($url, array(
850 'method' => 'POST',
851 'Locale' => "en-US",
852 'timeout' => 45,
853 'redirection' => 5,
854 'httpversion' => '1.0',
855 'blocking' => true,
856 'headers' => array(),
857 'body' => array('GolfID' => $username, 'Password' => $password),
858 'cookies' => array()
859 )
860 );
861
862 if (is_wp_error($response)) {
863 //$error_message = $response->get_error_message();
864 //new WP_Error( 'denied', __("ERROR: Server Error") );
865
866 //
867
868 }
869
870 //print_r($user_email);
871 //die();
872 global $wpdb;
873 $ext_auth = json_decode($response['body'], true);
874
875 if (!array_key_exists('Email', $ext_auth)) {
876 return new WP_Error( 'denied', __("ERROR: User/pass bad") );
877 }
878
879
880 $user_email = $ext_auth['Email'];
881 $user_golfId = $ext_auth['GolfID'];
882 $auth_token = $ext_auth['AuthToken'];
883 $userLog = $_POST['log'];
884 $userCheckingEmail = $wpdb->get_results("SELECT * FROM wp_users WHERE user_email = '" . $user_email . "'");
885 //$userLogin = $wpdb->get_results("SELECT * FROM wp_users WHERE user_login = '" . $userLog . "'");
886 //print_r($userCheckingEmail);
887 //die();
888 //die(var_dump($userCheckingEmail[0]));
889 //die(print_r($wpdb->num_rows));
890 if ($wpdb->num_rows == 0) {
891 $userInfo = explode("@", $user_email);
892 $date = date('Y-m-d H:i:s');
893 $userdata = array(
894 'user_login' => $userInfo[0],
895 'user_nicename' => $userInfo[0],
896 'user_email' => $user_email,
897 'user_url' => '',
898 'user_registered' => $date,
899 'user_activation_key' => '',
900 'user_status' => 0,
901 'display_name' => $userInfo[0],
902 'spam' => 0,
903 'deleted' => 0,
904 'golfId' => $user_golfId);
905 $new_user_id = wp_insert_user($userdata); // A new user has been created
906 // Load the new user info
907 $user = new WP_User ($new_user_id);
908
909 } else if ($wpdb->num_rows == 1) {
910 //die("ddd");
911 // External user exists, try to load the user info from the WordPress user table
912 $user = get_userdata($userCheckingEmail[0]->ID);
913
914 }
915
916 // Comment this line if you wish to fall back on WordPress authentication
917 // Useful for times when the external service is offline
918 //print_r($auth_token);
919 //die();
920 //print_r($userCheckingEmail[0]);
921 //die();
922 $user_token = "<script>document.write(localStorage.getItem('token'));</script>";
923 @session_start();
924 //set($auth_token);
925 //add_inline_script($auth_token);
926 //die($auth_token);
927 //add_inline_script($data);
928 //print_r($user_token);
929 //die();
930 $_SESSION['token'] = $auth_token;
931 remove_action('authenticate', 'wp_authenticate_username_password', 20);
932 //print_r($auth_token);
933 //die();
934 return $user;
935 }
936
937}
938
939add_filter('authenticate', 'demo_auth', 10, 3);
940
941function add_inline_script() {
942 @session_start();
943 if(isset($_SESSION['token']))
944 {
945 echo "<script>localStorage.setItem('token','".$_SESSION['token']."'); </script>\n";
946 }
947}
948
949// checking portofolio_category url
950function displayBookingWidgetPortolioCategory()
951{
952 $url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
953 if (strpos($url,'portfolio_category') !== false) {
954 //echo "<script>$( '.content' ).after( '<p>Test</p>' ); ";
955 echo do_shortcode("[booking]");
956 //echo "</script>";
957 }
958}
959
960//add_action( 'wp_head', 'add_inline_script', 0);
961add_action( 'init', 'displayBookingWidgetPortolioCategory');
962add_filter( 'category_description', 'booking' );
963add_filter( 'category_description', 'do_shortcode' );
964add_filter( 'term_description', 'shortcode_unautop' );
965add_filter( 'term_description', 'do_shortcode' );
966remove_filter( 'pre_term_description', 'wp_filter_kses' );
967
968
969function clear_token_golfa() {
970
971 echo "<script>console.log('head script'); </script>\n";
972
973 if(!is_user_logged_in() && isset($_SESSION['token'])){
974 unset($_SESSION['token']);
975 echo "<script>localStorage.setItem('token',''); </script>\n";
976 echo "<script>localStorage.removeItem('token'); </script>";
977 echo "<script>$(window).unload(function(){ localStorage.clear();});</script>";
978 wp_clear_auth_cookie();
979 }
980}
981add_action('wp_head', 'clear_token_golfa');
982
983//add_action('init', 'example_function');
984//add_action('wp_head','angular_login_js');
985
986
987function angular_login_js()
988{
989 //setcookie( 'wordpress_logged_in_cdcb695886249152431abff9e7a2ab3e', '', time() - 3600, '/', '.golfstar.staging.wpengine.com' );
990 if(isset($_COOKIE['wordpress_logged_in_cdcb695886249152431abff9e7a2ab3e'])){
991 unset($_COOKIE['wordpress_logged_in_cdcb695886249152431abff9e7a2ab3e']);
992 setcookie( 'wordpress_logged_in_cdcb695886249152431abff9e7a2ab3e', '', time() - 3600, '/', '.golfstar.se' );
993 }
994
995 global $wp;
996 $current_url = home_url(add_query_arg(array(),$wp->request));
997
998 if($current_url == get_site_url() . "/boka") {
999 $user_id = get_current_user_id();
1000 global $wpdb;
1001 //WHERE user_email = '" . $user_email . "'");
1002 $user_goldId = $wpdb->get_results("SELECT golfId FROM $wpdb->users WHERE id = '" . $user_id . "'");
1003 if($user_goldId[0]->golfId != "") {
1004 // print_r('empty');
1005 }else{
1006 // setcookie( 'wordpress_logged_in_cdcb695886249152431abff9e7a2ab3e', '', time() - 3600, '/', '.golfstar.se' );
1007
1008 }
1009 //print_r("test");
1010 //die();
1011
1012 }
1013 //wp_redirect("/boka");
1014}