-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPadOpt.module
More file actions
1066 lines (848 loc) · 39.6 KB
/
PadOpt.module
File metadata and controls
1066 lines (848 loc) · 39.6 KB
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
/* PadOpt for PadLoper
* Add custom client options feature to PadLoper (ProcessWire module)
*
* Copyright (C) 2018 Julien Vaubourg <julien@vaubourg.com>
* Contribute at https://github.com/jvaubourg/processwire-module-padopt
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class PadOpt extends WireData implements Module {
// MySQL table name used by PadCart for storing carts
protected $db_padcart = 'padcart';
// MySQL table colunm name added by PadOpt in <db_padcart> to store product
// options when they are added to the cart, before ordering
protected $db_optcolumn = 'padopt_options';
// Name of the field added by PadOpt in PadLoper product pages (admin-side)
// to store product options, when the cart (MySQL) is transform into an order
// (PW Page)
protected $field_options_name = 'padopt_options';
// Name of the field used in PadOpt product page, to ask the admin to choose
// a template id on which the option input fields set will be built
protected $field_tpl_name = 'padopt_tpl_id';
// HTML forms for choosing options have to integrate an hidden input field
// with this name (value=1)
protected $input_padopt_enabled = 'padopt';
// General prefix of PadOpt (eg. for field names)
protected $general_prefix = 'padopt_';
// Prefix part used in the name of general fields used to build option forms
protected $input_prefix = 'input_';
// Prefix part used in the name of fields used to describe a separator
// (ie. title) in option forms
protected $separator_prefix = 'sep_';
// Fields and templates created in PW with a name beginning with
// <general_prefix> will be automatically associated to this tag name
protected $tag_name = 'padopt';
// Errors will be logged under this category in PW and in JS console
protected $log_name = 'padopt';
// Keywords used in the text of the default choice for select fields
protected $select_prompt_keywords = array();
protected $session_id;
protected $stored_options = array();
protected $registered_submodules = array();
public static function getModuleInfo() {
return array(
'title' => 'PadOpt - PadLoper Client Options',
'version' => 1,
'summary' => 'Add custom client options to products for PadLoper',
'icon' => 'cart-plus',
'href' => 'https://github.com/jvaubourg/processwire-module-padopt',
'author' => 'Julien Vaubourg',
'singular' => true,
'autoload' => true,
'requires' => 'PadLoper',
);
}
public function init() {
$this->session_id = session_id();
$this->addHookBefore('ProcessField::executeSave', $this, 'automaticTagging');
$this->addHookBefore('ProcessTemplate::executeSave', $this, 'automaticTagging');
$this->addHookAfter('ProcessPageEdit::buildForm', $this, 'addTemplateSelect');
$this->addHookBefore('PadLoper::add', $this, 'storeProductOptions');
$this->addHookAfter('PadCart::addProduct', $this, 'addProductOptionsToCart');
$this->addHookAfter('PadOrder::parseCart', $this, 'convertCartWithOptionsToOrder');
$this->addHookAfter('PadCart::getProductPrice', $this, 'customizePriceWithOptions');
$this->addHookAfter('Page::render', $this, 'addScriptsAndStyles');
$this->addHookAfter('PadProcess::executeViewOrder', $this, 'addOptionsToViewOrder');
}
/***********/
/** HOOKS **/
/***********/
/**
* Automatically add a <tag_name> tag to every new field and template created
* with a name beginning by <general_prefix>. Also works after name updating
* Act before ProcessField::executeSave and ProcessTemplate::executeSave
*/
public function automaticTagging($event) {
$post_values = $event->object->input->post;
if((($post_values['name'] && strpos($post_values['name'], $this->general_prefix) === 0)
|| ($post_values['rename'] && strpos($post_values['rename'], $this->general_prefix) === 0))
&& strpos($post_values['tags'], $this->tag_name) === false) {
$post_values['tags'] .= " {$this->tag_name}";
}
}
/**
* When an admin page is edited, replace the field named <field_tpl_name>
* (simple input text for integers) by a select proposing to chose one of
* the template available in PW. This is used when a PadOpt product page
* is edited
* Act after ProcessPageEdit::buildForm
*/
public function addTemplateSelect($event) {
$form = $event->return;
$inputfield_int_id = $form->getChildByName($this->field_tpl_name);
// Only pages proposing the target field (ie. PadOpt product pages)
if($inputfield_int_id != null) {
$inputfield_select_tpl = $this->modules->get('InputfieldSelect');
$inputfield_select_tpl->name = $inputfield_int_id->name;
$inputfield_select_tpl->label = __("PadOpt Form");
$inputfield_select_tpl->description = __("Choose the template you have created for defining the form with options to display on this page.");
// Build a select with all available non-system templates in PW
foreach($this->templates->getAll() as $key => $template) {
if(!($template->flags & Template::flagSystem)) {
$inputfield_select_tpl->addOption($key, $template);
}
}
// The input text version of the field is removed
$inputfield_select_tpl->value = $inputfield_int_id->value;
$form->remove($inputfield_int_id);
// ... and replaced by the new version with values to select
$field_title = $form->getChildByName('title');
$form->insertAfter($inputfield_select_tpl, $field_title);
$event->return = $form;
}
}
/**
* Catch the value of every input field with a name beginning by
* <general_prefix>, among the values transmitted by a page to PadLoper,
* when an "Add to Cart" button is pushed. These values (describing product
* options) are temporarily stored in an array, to be used later by
* addProductOptionsToCart
* Act before PadLoper::add
*/
public function storeProductOptions($event) {
$product_id = (int) $event->arguments('id');
$variation_id = (int) $event->arguments('variation_id');
if(!empty($product_id) && !empty($variation_id)) {
$product_page = $event->object->pages->get($product_id);
// Only for PadOpt product pages containing an input field named <input_padopt_enabled>
// (have one condition respected but not the other one should neved happen)
if($this->isPadoptProductPage($product_page) && ($event->object->input->post($this->input_padopt_enabled) == 1)) {
if(!array_key_exists($this->session_id, $this->stored_options)) {
$this->stored_options[$this->session_id] = array();
}
if(!array_key_exists($product_id, $this->stored_options[$this->session_id])) {
$this->stored_options[$this->session_id][$product_id] = array();
}
if(!array_key_exists($variation_id, $this->stored_options[$this->session_id][$product_id])) {
$this->stored_options[$this->session_id][$product_id][$variation_id] = array();
}
$options = &$this->stored_options[$this->session_id][$product_id][$variation_id];
// Input values are stored only when the name begins with
// <general_prefix>, corresponding to input fields generated
// by PadOpt
foreach($event->object->input->post as $name => $value) {
if(strpos($name, $this->general_prefix) === 0) {
$tpl_page = new Page();
$tpl_page->template = $product_page->get($this->field_tpl_name);
// Is the input field corresponding to a PW field for this PadOpt product page
if($tpl_page->fields->get($name)) {
// Pipes are special chars for us
$value = str_replace('|', '', $value);
// Values composed of multiple values (eg. checkboxes) are concatenated
// into a single value (eg. 1|2|3)
if(is_array($value)) {
$value = implode('|', $value);
}
// sanitizer->text() allows 255 chars max and avoid db over filling
if(strlen($value) > 0) {
$value = substr($value, 0, 255);
if(substr($value, -1) == '|') {
$value = substr($value, 0, 254);
}
}
$options[$this->sanitizer->fieldName($name)] = $this->sanitizer->text($value);
}
}
}
}
}
}
/**
* Store in db the options associated to the product to add to the cart. The
* values are serialized and saved in the <db_optcolumn> MySQL column of the
* tuple, created for the current cart by PadLoper in the hooked function
* Act after PadCart::addProduct
*/
public function addProductOptionsToCart($event) {
$product_id = (int) $event->arguments('product_id');
$variation_id = (int) $event->arguments('variation_id');
$qty = (int) $event->arguments('qty');
// Only if the hooked function worked well (ie. the cart was well created in the db)
if($event->return === true && $qty > 0) {
// If storeProductOptions found earlier some options values to store for this product
if(array_key_exists($this->session_id, $this->stored_options)
&& array_key_exists($product_id, $this->stored_options[$this->session_id])
&& array_key_exists($variation_id, $this->stored_options[$this->session_id][$product_id])) {
// Get the id of the cart-product tuple in the db
$cart_row_id = $event->object->checkIfProductInCart($product_id, $variation_id);
if($cart_row_id) {
$options = $this->stored_options[$this->session_id][$product_id][$variation_id];
$options['product_id'] = $product_id;
$serialized_options = serialize($options);
// Fill the <db_optcolumn> with all the option values associated to
// this product when added in the cart by the client
$sql = "UPDATE {$this->db_padcart} SET {$this->db_optcolumn} = :options WHERE sess_id = :sess_id AND id = :id";
$sth = $this->database->prepare($sql);
$sth->bindParam(":options", $serialized_options);
$sth->bindParam(":sess_id", $this->session_id);
$sth->bindParam(":id", $cart_row_id);
$sth->execute();
// Free the temporary memory allocated for jumping from storeProductOptions
// (values catching) to addProductOptionsToCart (values injecting)
unset($this->stored_options[$this->session_id][$product_id][$variation_id]);
}
}
}
}
/**
* Move the product options stored into a db column when added to a cart, to
* a PW field, when the cart is converted to an order (the order pad_product
* page is created during the hooked function, and the db tuple is deleted
* just after)
* Act after PadOrder::parseCart
*/
public function convertCartWithOptionsToOrder($event) {
if($event->object->pad_products->count > 0) {
// Get the options associated to this product and stored by addProductOptionsToCart
$sql = "SELECT product_id, variation_id, {$this->db_optcolumn} FROM {$this->db_padcart} WHERE sess_id = :sess_id";
$sth = $this->database->prepare($sql);
$sth->bindParam(":sess_id", $this->session_id);
$sth->execute();
$cart_products = $sth->fetchAll(\PDO::FETCH_CLASS);
foreach($cart_products as $cart_product) {
// Only if this product was added with PadOpt options
if(!empty($cart_product->{$this->db_optcolumn})) {
$product_id = $cart_product->product_id;
$variation_id = $cart_product->variation_id;
// Get the pad_product page created for this product in the hooked function
$order_product = $event->object->pad_products->get("pad_product_id={$product_id}, pad_variation_id={$variation_id}");
if(!($order_product instanceof NullPage)) {
$order_product->{$this->field_options_name} = $cart_product->{$this->db_optcolumn};
$order_product->save();
} else {
$this->logError("No product corresponding to {$product_id}/{$variation_id} in the order");
}
}
}
}
}
/**
* Add the price of the chosen paid options to the the initial price of the
* product. Used when displaying the cart, for the client-side order
* summaries, invoices, and to definitely store the final prices in the orders
* Act after PadCart::getProductPrice
*/
public function customizePriceWithOptions($event) {
$product = $event->arguments('product');
$product_id = $product->id;
$variation_id = $event->arguments('variation_id');
$pricefield = $event->object->pricefield;
$price = (float) $product->$pricefield;
$options = $this->getCartProductOptions($product_id, $variation_id);
$options_price = (float) $this->getProductOptionsPrice($options);
$event->return = $price + $options_price;
}
/**
* Add some JS and css in the header of every PadOpt product page and page
* of the PadLoper admin
* Act before Page::render
*/
public function addScriptsAndStyles($event) {
$page = $event->object;
$module_url = $this->config->urls->siteModules . basename(__DIR__);
$root_url = $_SERVER['DOCUMENT_ROOT'];
$log_script = <<<EOT
<script>
const padopt_logname = '{$this->log_name}';
</script>
EOT;
$scripts = '';
$styles = '';
// Admin pages
if($page->template->name == 'admin') {
// Only for PadLoper admin pages
if($page->name == 'padloper') {
$scripts .= "{$log_script}<script type='text/javascript' src='{$module_url}/templates/scripts/padopt_admin.js'></script>";
$styles .= "<link type='text/css' href='{$module_url}/templates/styles/padopt_admin.css' rel='stylesheet' />";
}
// Public pages
} else {
// Only for PadOpt product pages
if($this->isPadoptProductPage($page)) {
// Load JS/CSS modules
$this->modules->get('JqueryCore');
// Integrate JS scripts from the previous modules
foreach($this->config->scripts as $script) {
if(preg_match('/JqueryCore/', $script)) {
$scripts .= "<script type='text/javascript' src='{$script}'></script>";
}
}
// Input fields style from PW
$scripts .= "<script type='text/javascript' src='{$config->urls->root}/wire/templates-admin/scripts/inputfields.js'></script>";
//$styles .= "<link rel='stylesheet' type='text/css' href='{$config->urls->root}/wire/templates-admin/styles/inputfields.css' />";
// Default script/style for PadOpt products
$scripts .= "{$log_script}<script type='text/javascript' src='{$module_url}/templates/scripts/padopt_product.js'></script>";
$styles .= "<link rel='stylesheet' type='text/css' href='{$module_url}/templates/styles/padopt_product.css' />";
// Add user defined scripts for PadOpt products
if(is_file("{$root_url}{$this->config->urls->templates}/scripts/padopt/padopt_product.js")) {
$scripts .= "<script type='text/javascript' src='{$this->config->urls->templates}/scripts/padopt/padopt_product.js'></script>";
}
// Add user defined styles
if(is_file("{$root_url}{$this->config->urls->templates}/styles/padopt/padopt_product.css")) {
$styles .= "<link type='text/css' href='{$this->config->urls->templates}/styles/padopt/padopt_product.css' rel='stylesheet' />";
}
}
// Add user defined scripts for every page (useful for templates with PadOpt infos included)
if(is_file("{$root_url}{$this->config->urls->templates}/scripts/padopt/padopt.js")) {
$scripts .= "<script type='text/javascript' src='{$this->config->urls->templates}/scripts/padopt/padopt.js'></script>";
}
// Add user defined styles
if(is_file("{$root_url}{$this->config->urls->templates}/styles/padopt/padopt.css")) {
$styles .= "<link type='text/css' href='{$this->config->urls->templates}/styles/padopt/padopt.css' rel='stylesheet' />";
}
}
if(!empty($styles.$scripts)) {
$event->return = str_replace('</head>', "{$styles}{$scripts}</head>", $event->return);
}
}
/**
* Change the admin-side order summary views, by injecting new HTML table
* columns describing the options associated by clients to the products durant
* their shoppings.
* Act after PadProcess::executeViewOrder
*/
public function addOptionsToViewOrder($event) {
$id = (int) $this->input->get->id;
$order = $event->object->pages->get($id);
$page = $event->return;
preg_match('/<thead>.*<\\/thead>/Us', $page, $thead);
preg_match('/<tbody>.*<\\/tbody>/Us', $page, $tbody);
preg_match_all('/<tr>.*<\\/tr>/Us', $tbody[0], $bodyrows);
$bodyrows = $bodyrows[0];
// The HTML table of the current view should has as many lines as there are
// products associated to the order (+ 1 at the end)
if($order->pad_products->count == count($bodyrows) - 1) {
$headcols = explode('</th>', $thead[0]);
$headcols[0] .= '</th><th>' . __("Included Options");
$thead = implode('</th>', $headcols);
for($i = 0; $i < count($bodyrows); $i++) {
$bodycols = explode('</td>', $bodyrows[$i]);
$bodycols[0] .= '</td><td>';
// The last line corresponds to the total price of the order
if($i < count($bodyrows) - 1) {
$serialized_options = $order->pad_products[$i]->{$this->field_options_name};
if(!empty($serialized_options)) {
$options = unserialize($serialized_options);
$options_list = $this->renderOptionsHtml($options);
$product_id = $options['product_id'];
$options_price = $this->getProductOptionsPrice($options);
$json_options = json_encode($options);
$url_options = base64_encode($json_options);
$view_url = "{$this->pages->get($product_id)->url}#{$url_options}";
$render = "<ul class='{$this->general_prefix}included_options'>";
if($options_price === false) {
$render .= '<li class="padopt_deleted_field">' . __("Some fields or options have be deleted since this order") . '</li>';
} else {
$render .= '<li>' . ($options_price > 0 ? $this->modules->get('PadCart')->renderPriceAndCurrency($options_price) : __("Free")) . '</li>';
}
$render .= "<li><a href='javascript:;' class='{$this->general_prefix}show_options'>" . __("Show list") . "</a>{$options_list}</li>";
$render .= "<li><a href='{$view_url}' target='_blank'>" . __("View online") . '</a></li>';
$render .= '</ul>';
$bodycols[0] .= $render;
}
}
$bodyrows[$i] = implode('</td>', $bodycols);
}
$tbody = '<tbody>' . implode($bodyrows) . '</tbody>';
$page = preg_replace('/<thead>.*<\\/thead>/Us', $thead, $page, 1);
$page = preg_replace('/<tbody>.*<\\/tbody>/Us', $tbody, $page, 1);
$event->return = $page;
} else {
$this->logError("Cannot show products options");
}
}
/***********************/
/** PRIVATE FUNCTIONS **/
/***********************/
/**
* Return information about the options of a product, from the cart or an order
*
* @param Page $product
* @param bool from_cart Is the product currently stored in the cart
* @return array 0=Options URL, 1=HTML options list, 2=Total options price
*/
private function getProductOptionsInfos($product, $from_cart) {
$options = '';
$product_id = '';
// Options have to be fetched from the MySQL db
if($from_cart) {
$options = $this->getCartProductOptions($product->product_id, $product->variation_id);
$product_id = $product->product_id;
// Options were already integrated before to the page with convertCartWithOptionsToOrder
} elseif(isset($product->{$this->field_options_name})) {
$serialized_options = $product->{$this->field_options_name};
$unserialized_options = unserialize($serialized_options);
if($unserialized_options) {
$options = $unserialized_options;
$product_id = $options['product_id'];
} else {
$this->logError("Product options are not unserializable");
}
}
$view_url = '';
$options_list = '';
$options_price = '';
if(!empty($options)) {
$json_options = json_encode($options);
$url_options = base64_encode($json_options);
$view_url = "{$this->pages->get($product_id)->httpUrl}#{$url_options}";
$options_list = $this->renderOptionsHtml($options);
$options_price = $this->getProductOptionsPrice($options);
}
$infos = array($view_url, $options_list, $options_price);
return $infos;
}
/**
* Produce the HTML code corresponding to the options list
*
* @param array $options Option values associated to a product
* @return string HTML code
*/
private function renderOptionsHtml($options) {
$options_list = "<ul class='{$this->general_prefix}options_list'>";
foreach($options as $name => $value) {
if($name != 'product_id') {
$field = $this->fields->get($name);
if(!empty($field)) {
$field_label = $field->label;
$field_txt = '';
// Only for filled fields (may be optional)
if($value != '') {
// Field with predefined options (eg. select, checkboxes, radios)
if($field->type instanceof FieldtypeOptions) {
$field_options = $field->type->getOptions($this->fields->get($name));
// Values composed of multiple values (eg. checkboxes)
if(strpos($value, '|') !== false) {
$subvalues = explode('|', $value);
$field_txt = '<ul>';
foreach($subvalues as $subvalue) {
if(is_numeric($subvalue)) {
$field_option = $field_options->get($subvalue);
if(empty(!$field_option)) {
$field_txt .= "<li><span class='padopt_option_value'>{$field_option->data['title']}</span></li>";
} else {
$this->logError("Option value {$subvalue} of the field {$name} does not exist");
$field_txt .= "<li><span class='padopt_option_value padopt_deleted_field'>". __("Value") . "#{$subvalue}</span></li>";
}
} else {
$this->logError("Subvalue {$subvalue} of the field {$name} must be a number");
}
}
$field_txt .= '</ul>';
// Atomic value (eg. select with one choice)
} else {
$field_option = $field_options->get($value);
if(empty(!$field_option)) {
$field_txt = "<span class='padopt_option_value'>{$field_option->data['title']}</span>";
} else {
$this->logError("Option value {$value} of the field {$name} does not exist");
$field_txt = "<span class='padopt_option_value padopt_deleted_field'>". __("Value") . "#{$value}</span>";
}
}
// Free field (eg. text, textarea)
} else {
$field_txt = "<span class='padopt_option_value'>{$value}</span>";
}
}
$options_list .= "<li><span class='padopt_option_label'>{$field_label}:</span> <span class='padopt_option_value'>{$field_txt}</span></li>";
} else {
$this->logError("Select field {$name} does not have options");
$options_list .= "<li class='padopt_deleted_field'><span class='padopt_option_label'>{$name}:</span> <span class='padopt_option_value'>". __("Value") . "<{$value}></span></li>";
}
}
}
$options_list .= '</ul>';
return $options_list;
}
/**
* Return the chosen options for a product added in the current cart
*
* @param int $product_id
* @param in $variation_id
* @return
*/
private function getCartProductOptions($product_id, $variation_id) {
$sql = "SELECT {$this->db_optcolumn} FROM {$this->db_padcart} WHERE product_id = :product_id AND variation_id = :variation_id AND sess_id = :sess_id LIMIT 1";
$sth = $this->database->prepare($sql);
$sth->bindParam(":product_id", $product_id);
$sth->bindParam(":variation_id", $variation_id);
$sth->bindParam(":sess_id", $this->session_id);
$sth->execute();
$options = array();
$serialized_options = $sth->fetchAll(\PDO::FETCH_CLASS);
if(count($serialized_options) > 0) {
$serialized_options = $serialized_options[0];
$serialized_options = $serialized_options->{$this->db_optcolumn};
// Product with PadOpt options
if(!empty($serialized_options)) {
$unserialized_options = unserialize($serialized_options);
if($unserialized_options) {
$options = $unserialized_options;
} else {
$this->logError("Product {$product_id}/{$variation_id} options are not unserializable");
}
}
} else {
$this->logError("Product {$product_id}/{$variation_id} does not exist in the db for this session");
}
return $options;
}
/**
* Extract the price of an option directly from its title
*
* @param string $title
* @return float Extracted price or zero
*/
private function extractOptionPriceFromTitle($title) {
$option_price = 0;
// eg. "With a golden shell (+ 499.99 €)"
preg_match('/\s*\(\s*\+\s*([0-9]+(?:[.,][0-9]+)?)\s*.+\s*\)/', $title, $matches);
if(count($matches) > 1) {
$option_price = $matches[1];
}
return $option_price;
}
/**
* Return the total price of the chosen paid options
*
* @param array $options Option values associated to a product
* @return float
*/
private function getProductOptionsPrice($options) {
$options_price = 0;
foreach($options as $name => $value) {
if($name != 'product_id') {
// Only for filled fields (may be optional)
if($value != '') {
$field = $this->fields->get($name);
if(!empty($field)) {
// Field with predefined options (eg. select, checkboxes, radios)
if($field->type instanceof FieldtypeOptions) {
$field_options = $field->type->getOptions($this->fields->get($name));
if(!empty($field_options)) {
// Value composed of multiple values (eg. checkboxes)
if(strpos($value, '|') !== false) {
$subvalues = explode('|', $value);
foreach($subvalues as $subvalue) {
if(is_numeric($subvalue)) {
$field_option = $field_options->get($subvalue);
if(empty(!$field_option)) {
$options_price += $this->extractOptionPriceFromTitle($field_option->data['title']);
} else {
$this->logError("Option value {$subvalue} of the field {$name} does not exist: this cancels calculating of the options price");
return false;
}
} else {
$this->logError("Subvalue {$subvalue} of the field {$name} must be a number: this cancels calculating of the options price");
return false;
}
}
// Atomic value (eg. select with one choice)
} else {
$field_option = $field_options->get($value);
if(empty(!$field_option)) {
$options_price += $this->extractOptionPriceFromTitle($field_option->data['title']);
} else {
$this->logError("Option value {$value} of the field {$name} does not exist: this cancels calculating of the options price");
return false;
}
}
} else {
$this->logError("Select field {$name} does not have options: this cancels calculating of the options price");
return false;
}
// Free field (eg. text, textarea)
} else {
$options_price += $this->extractOptionPriceFromTitle($field->label);
}
} else {
$this->logError("Field {$name} does not exist: this cancels calculating of the options price");
return false;
}
}
}
}
return $options_price;
}
/**
* Error logging
*
* @param string $msg
*/
private function logError($msg) {
$this->error($msg);
$this->log->save($this->log_name, $msg);
}
/**********************/
/** PUBLIC FUNCTIONS **/
/**********************/
/**
* A submodule is just another PW module but designed to add functionnalities
* to PadOpt. Registred submodules are used in renderFieldset
*
* @param PadOptSubmodule $submodule
*/
public function registerSubmodule($submodule) {
$input_prefix = $submodule->getInputPrefix();
$this->registered_submodules["{$this->general_prefix}{$input_prefix}"] = $submodule;
}
/**
* Set the keywords used in the text of the default choice for select fields
*
* @param array $keywords
*/
public function setSelectPromptKeywords($keywords) {
$this->select_prompt_keywords = $keywords;
}
/**
* Return the HTML code of the error panel when required fields are not filled
* and the client has submitted the form
*
* @param string $text Message to show
* @return string HTML code
*/
public function getRequiredFieldsErrorPanel($text) {
return "<div id='padopt_error'>{$text} ☺</div>";
}
/**
* Return the HTML code of the panel where the total price of the options
* will be dynamically updated, based on the user's choices
*
* @param string $text Message to show
* @return string HTML code
*/
public function getOptionsTotalPricePanel($text) {
$currency = $this->modules->get('PadCart')->renderPriceAndCurrency(0);
$currency = preg_replace('/0[.,](?:00)?/', "<span>0</span>", $currency);
return "<div class='padopt_optionsprice'>{$text} <span class='padopt_optionsprice_value'>{$currency}</span></div>";
}
/**
* Return the HTML code of the panel where the final price with options of the
* product will be dynamically updated, based on the user's choices
*
* @param string $text Message to show
* @return string HTML code
*/
public function getFinalPriceWithOptionsPanel($text) {
$currency = $this->modules->get('PadCart')->renderPriceAndCurrency(0);
$currency = preg_replace('/0[.,](?:00)?/', "<span></span>", $currency);
return "<div class='padopt_finalprice'>{$text} <span class='padopt_finalprice_value'>{$currency}</span></div>";
}
/**
* Return the HTML code of the input fields to add to the PadLoper form, in
* which there is the "Add to cart" button. This function should be called
* from a PadOpt product template, with a <field_tpl_name> field defined
*
* @return string HTML code
*/
public function renderFieldset() {
// The template to use to build the fieldset is defined from the
// <field_tpl_name> field of the current page
$template = $this->templates->get($this->page->get($this->field_tpl_name));
// Creation of a temporary page, just to associate it with the template and
// to transform the template fields into input fields
$page = new Page();
$page->template = $template;
$inputfields = $page->getInputfields();
$inputfield_groups = array();
$inputfield_groups_id = 0;
// Step 1: Group together all fields that follow each other with an identical prefix in their name
foreach($inputfields as $inputfield) {
// Extracts the prefix (format <general-prefix>_<type-prefix>_)
preg_match("/^{$this->general_prefix}[^_]+_/", $inputfield->name, $prefix);
if(!empty($prefix)) {
$prefix = $prefix[0];
if(empty($inputfield_groups)) {
$inputfield_groups[] = array(
'prefix' => $prefix,
'inputfields' => array($inputfield),
);
} else {
if($inputfield_groups[$inputfield_groups_id]['prefix'] == $prefix) {
$inputfield_groups[$inputfield_groups_id]['inputfields'][] = $inputfield;
} else {
$inputfield_groups_id++;
$inputfield_groups[$inputfield_groups_id]['prefix'] = $prefix;
$inputfield_groups[$inputfield_groups_id]['inputfields'][] = $inputfield;
}
}
}
}
$product_id = $this->page->id;
$variation_id = -1;
// The variation_id is always different because the chosen options are (potentially) always different
$i = 0;
do {
$variation_id = rand(100000, 10000000);
if($i++ > 1000) {
$this->logError("Variation ID cannot be generated");
exit();
}
} while(!($this->pages->get("pad_product_id={$product_id}, pad_variation_id={$variation_id}") instanceof NullPage));
// This hidden input is required to ask the other processes to take the options into account
$render = "<input type='hidden' name='{$this->input_padopt_enabled}' value='1' />";
$render .= "<input type='hidden' name='product_id' value='{$product_id}' />";
$render .= "<input type='hidden' name='variation_id' value='{$variation_id}' />";
$first_separator = true;
// Step 2: Produce HTML output from each group of fields
foreach($inputfield_groups as $inputfield_group) {
// Group of separators (ie. titles with optional description/notes)
if($inputfield_group['prefix'] == "{$this->general_prefix}{$this->separator_prefix}") {
$separators = '';
foreach($inputfield_group['inputfields'] as $inputfield) {
$separators .= "<h2 id='{$inputfield->name}'>{$inputfield->label}</h2>";
if($first_separator) {
$separators .= '<span class="padopt_required_note">* : ' . __("Choice required") . '</span>';
$first_separator = false;
}
if(!empty($inputfield->description)) {
$separators .= "<div class='{$this->general_prefix}{$this->separator_prefix}description'>{$inputfield->description}</div>";
}
if(!empty($inputfield->notes)) {
$separators .= "<div class='{$this->general_prefix}{$this->separator_prefix}notes'>{$inputfield->notes}</div>";
}
}
$render .= $separators;
// Group of core input fields (ie. field types available in PW)
} elseif($inputfield_group['prefix'] == "{$this->general_prefix}{$this->input_prefix}") {
$form = $this->modules->get('InputfieldForm');
foreach($inputfield_group['inputfields'] as $inputfield) {
$form->add($inputfield);
}
// PW produces the HTML code by itself
$form_render = $form->render();
// <form> tags are not necessary because it is supposed to be a form part
$render .= preg_replace('/<\/?form[^>]*>/', '', $form_render);
// Group of fields defined for a registred submodule
} elseif(isset($this->registered_submodules[$inputfield_group['prefix']])) {
$render .= $this->registered_submodules[$inputfield_group['prefix']]->render($inputfield_group['inputfields']);
}
}
// Mark every first option of select fields when its text contains one of the select_prompt_keywords
if(!empty($this->select_prompt_keywords)) {
if(preg_match_all('/<select[^>]*>\s*<option[^>]*>[^<]*(?:' . implode('|', $this->select_prompt_keywords) . ')[^<]*<\/option>/i', $render, $select_prompts)) {
foreach($select_prompts[0] as $select_prompt) {
$select_prompt_tagged = str_replace('<option', '<option data-isprompt="1"', $select_prompt);
$render = str_replace($select_prompt, $select_prompt_tagged, $render);
}
}
}
return $render;
}
/**
* Return information about the options of a product currently available in the cart
*
* @param Page $product
* @return array 0=Options URL, 1=HTML options list, 2=Total options price
*/
public function getCartProductOptionsInfos($product) {
return $this->getProductOptionsInfos($product, true);
}
/**
* Return information about the options of a product which is a part of an order
*
* @param Page $product
* @return array 0=Options URL, 1=HTML options list, 2=Total options price
*/
public function getOrderProductOptionsInfos($product) {
return $this->getProductOptionsInfos($product, false);
}
/**
* Return true if the page seems to be a PadOpt product page (ie. a PadLoper
* product page but with PadOpt options)
*
* @param Page $page
* @return bool
*/
public function isPadoptProductPage($page) {
return !empty($page->get($this->field_tpl_name));
}
/**
* Module installation
*/
public function install() {
// Add a column for product options to the table used for storing carts, before ordering
// Options are PHP-serialized