-
Notifications
You must be signed in to change notification settings - Fork 5
/
commerce.module
1467 lines (1316 loc) · 50.2 KB
/
commerce.module
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
/**
* @file
* Defines features and functions common to the Commerce modules.
*/
// Define our own rounding constants since we can't depend on PHP 5.3.
define('COMMERCE_ROUND_NONE', 0);
define('COMMERCE_ROUND_HALF_UP', 1);
define('COMMERCE_ROUND_HALF_DOWN', 2);
define('COMMERCE_ROUND_HALF_EVEN', 3);
define('COMMERCE_ROUND_HALF_ODD', 4);
/**
* Implements hook_permission().
*/
function commerce_permission() {
$permissions = array(
'configure store' => array(
'title' => t('Configure store settings'),
'description' => t('Allows users to update store currency and contact settings.'),
'restrict access' => TRUE,
),
);
return $permissions;
}
/**
* Implements hook_hook_info().
*/
function commerce_hook_info() {
$hooks = array(
'commerce_currency_info' => array(
'group' => 'commerce',
),
'commerce_currency_info_alter' => array(
'group' => 'commerce',
),
'commerce_entity_access' => array(
'group' => 'commerce',
),
'commerce_entity_access_condition_alter' => array(
'group' => 'commerce',
),
'commerce_entity_create_alter' => array(
'group' => 'commerce',
),
);
return $hooks;
}
/**
* Implements hook_system_info_alter().
*
* Drupal's Field module doesn't allow field type providing modules to be
* disabled while fields and instances of those types exist in the system.
* See http://drupal.org/node/943772 for further explanation.
*
* That approach doesn't work for Commerce, creating circular dependencies
* and making uninstall impossible. This function removes the requirement,
* allowing Commerce to implement its own workaround.
*
* @see commerce_delete_field()
*/
function commerce_system_info_alter(&$info, $file, $type) {
$modules = array(
'commerce_product_reference',
'commerce_price',
'commerce_customer',
'commerce_line_item',
);
if ($type == 'module' && in_array($file->name, $modules)) {
unset($info['required']);
unset($info['explanation']);
}
}
/**
* Implements hook_html_head_alter().
*/
function commerce_html_head_alter(&$head_elements) {
if (isset($head_elements['system_meta_generator'])) {
$head_elements['system_meta_generator']['#attributes']['content'] .= '; Commerce 1';
}
}
/**
* Implements hook_init().
*/
function commerce_init() {
backdrop_add_http_header('X-Commerce-Core', '1');
}
/**
* Finds all fields of a particular field type.
*
* @param $field_type
* The type of field to search for.
* @param $entity_type
* Optional entity type to restrict the search to.
*
* @return
* An array of the matching fields keyed by the field name.
*/
function commerce_info_fields($field_type, $entity_type = NULL) {
$fields = array();
// Loop through the fields looking for any fields of the specified type.
foreach (field_info_field_map() as $field_name => $field_stub) {
if ($field_stub['type'] == $field_type) {
// Add this field to the return array if no entity type was specified or
// if the specified type exists in the field's bundles array.
if (empty($entity_type) || array_key_exists($entity_type, $field_stub['bundles'])) {
$field = field_info_field($field_name);
$fields[$field_name] = $field;
}
}
}
return $fields;
}
/**
* Deletes a reference to another entity from an entity with a reference field.
*
* @param $entity
* The entity that contains the reference field.
* @param $field_name
* The name of the entity reference field.
* @param $col_name
* The name of the column in the field's schema containing the referenced
* entity's ID.
* @param $ref_entity_id
* The ID of the entity to delete from the reference field.
*/
function commerce_entity_reference_delete($entity, $field_name, $col_name, $ref_entity_id) {
// Exit now if the entity does not have the expected field.
if (empty($entity->{$field_name})) {
return;
}
// Loop over each of the field's items in every language.
foreach ($entity->{$field_name} as $langcode => $items) {
$rekey = FALSE;
foreach ($items as $delta => $item) {
// If the item references the specified entity...
if (!empty($item[$col_name]) && $item[$col_name] == $ref_entity_id) {
// Unset the reference.
unset($entity->{$field_name}[$langcode][$delta]);
$rekey = TRUE;
}
}
if ($rekey) {
// Rekey the field items if necessary.
$entity->{$field_name}[$langcode] = array_values($entity->{$field_name}[$langcode]);
// If the reference field is empty, wipe its data altogether.
if (count($entity->{$field_name}[$langcode]) == 0) {
unset($entity->{$field_name}[$langcode]);
}
}
}
}
/**
* Attempts to directly activate a field that was disabled due to its module
* being disabled.
*
* The normal API function for updating fields, field_update_field(), will not
* work on disabled fields. As a workaround, this function directly updates the
* database, but it is up to the caller to clear the cache.
*
* @param $field_name
* The name of the field to activate.
*
* @return
* Boolean indicating whether or not the field was activated.
*/
function commerce_activate_field($field_name) {
// Set it to active via a query because field_update_field() does
// not work on inactive fields.
$config = config('field.field.' . $field_name);
if (!empty($config->getData() || $config->getData() != NULL)) {
$config->set('deleted', 0);
$config->save();
}
$updated = $config->get('deleted');
return !empty($updated) ? TRUE : FALSE;
}
/**
* Enables and deletes fields of the specified type.
*
* @param $type
* The type of fields to enable and delete.
*
* @see commerce_delete_field()
*/
function commerce_delete_fields($type) {
// Read the fields for any active or inactive field of the specified type.
foreach (field_read_fields(array('type' => $type), array('include_inactive' => TRUE)) as $field_name => $field) {
commerce_delete_field($field_name);
}
}
/**
* Enables and deletes the specified field.
*
* The normal API function for deleting fields, field_delete_field(), will not
* work on disabled fields. As a workaround, this function first activates the
* fields of the specified type and then deletes them.
*
* @param $field_name
* The name of the field to enable and delete.
*/
function commerce_delete_field($field_name) {
// In case the field is inactive, first activate it and clear the field cache.
if (commerce_activate_field($field_name)) {
field_cache_clear();
}
// Delete the field.
field_delete_field($field_name);
}
/**
* Deletes any field instance attached to entities of the specified type,
* regardless of whether or not the field is active.
*
* @param $entity_type
* The type of entity whose fields should be deleted.
* @param $bundle
* Optionally limit instance deletion to a specific bundle of the specified
* entity type.
*/
function commerce_delete_instances($entity_type, $bundle = NULL) {
$config = config('commerce.settings');
// Prepare a parameters array to load the specified instances.
$params = array(
'entity_type' => $entity_type,
);
if (!empty($bundle)) {
$params['bundle'] = $bundle;
// Delete this bundle's field bundle settings.
$config->clear('field_bundle_settings_' . $entity_type . '__' . $bundle);
}
else {
// Delete all field bundle settings for this entity type.
db_delete('variable')
->condition('name', db_like('field_bundle_settings_' . $entity_type . '__') . '%', 'LIKE')
->execute();
}
// Read and delete the matching field instances.
foreach (field_read_instances($params, array('include_inactive' => TRUE)) as $instance) {
commerce_delete_instance($instance);
}
}
/**
* Deletes the specified instance and handles field cleanup manually in case the
* instance is of a disabled field.
*
* @param $instance
* The field instance info array to be deleted.
*/
function commerce_delete_instance($instance) {
// First activate the instance's field if necessary.
$field_name = $instance['field_name'];
$activated = commerce_activate_field($field_name);
// Clear the field cache if we just activated the field.
if ($activated) {
field_cache_clear();
}
// Then delete the instance.
field_delete_instance($instance, FALSE);
// Now check to see if there are any other instances of the field left.
$field = field_info_field($field_name);
if (count($field['bundles']) == 0) {
field_delete_field($field_name);
}
elseif ($activated) {
// If there are remaining instances but the field was originally disabled,
// disabled it again now.
$field['active'] = 0;
field_update_field($field);
}
}
/**
* Makes any required form elements in a form unrequired.
*
* @param $form
* The form array to search for required elements.
*/
function commerce_unrequire_form_elements(&$form) {
array_walk_recursive($form, '_commerce_unrequire_element');
}
/**
* array_walk_recursive callback: makes an individual element unrequired.
*
* @param &$value
* The value of the form array being walked.
* @param $key
* The key of the form array corresponding to the present value.
*/
function _commerce_unrequire_element(&$value, $key) {
if ($key === '#required') {
$value = FALSE;
}
}
/**
* Returns the callback for a form ID as defined by hook_forms().
*
* @param $form_id
* The form ID to find the callback for.
* @return
* A string containing the form's callback function name.
*
* @see drupal_retrieve_form()
* @see hook_forms()
*/
function commerce_form_callback($form_id, $form_state) {
// If a function named after the $form_id does not exist, look for its
// definition in hook_forms().
if (!function_exists($form_id)) {
$forms = &backdrop_static(__FUNCTION__);
// In cases where many form_ids need to share a central builder function,
// such as the product editing form, modules can implement hook_forms(). It
// maps one or more form_ids to the correct constructor functions.
if (!isset($forms) || !isset($forms[$form_id])) {
$forms = module_invoke_all('forms', $form_id, $form_state['build_info']['args']);
}
if (isset($forms[$form_id]['callback'])) {
return $forms[$form_id]['callback'];
}
}
return $form_id;
}
/**
* Renders a View for display in some other element.
*
* @param $view_key
* The ID of the View to embed.
* @param $display_id
* The ID of the display of the View that will actually be rendered.
* @param $arguments
* An array of arguments to pass to the View.
* @param $override_url
* A url that overrides the url of the current view.
*
* @return
* The rendered output of the chosen View display.
*/
function commerce_embed_view($view_id, $display_id, $arguments, $override_url = '') {
// Load the specified View.
$view = views_get_view($view_id);
$view->set_display($display_id);
// Set the specific arguments passed in.
$view->set_arguments($arguments);
// Override the view url, if an override was provided.
if (!empty($override_url)) {
$view->override_url = $override_url;
}
// Prepare and execute the View query.
$view->pre_execute();
$view->execute();
// Return the rendered View.
return $view->render();
}
/**
* Returns the e-mail address from which to send commerce related e-mails.
*
* Currently this is just using the site's e-mail address, but this may be
* updated to use a specific e-mail address when we add a settings form for the
* store's physical address and contact information.
*/
function commerce_email_from() {
$config = config('commerce.settings');
$site_email = $config->get('site_mail');
if (!isset($site_email) || empty($site_email) || $site_email == NULL){
$site_email = ini_get('sendmail_from');
$config->set('site_mail', update_variable_get('site_mail', $site_email));
}
return $site_email;
}
/**
* Translate a data structure using i18n_string, if available.
*
* @param $type
* The i18n object type.
* @param $object
* The object or array to translate.
* @param $options
* An array of options passed along to i18n.
*
* @return
* The translated data structure if i18_string is available, the original
* otherwise.
*
* @see i18n_string_object_translate()
*/
function commerce_i18n_object($type, $object, $options = array()) {
// Clone the object, to ensure the original remains untouched.
if (is_object($object)) {
$object = clone $object;
}
if (module_exists('i18n_string')) {
return i18n_string_object_translate($type, $object, $options);
}
else {
return $object;
}
}
/**
* Implements hook_i18n_string_info().
*/
function commerce_i18n_string_info() {
$groups['commerce'] = array(
'title' => t('Drupal Commerce'),
'format' => TRUE,
);
return $groups;
}
/**
* Translate a string using i18n_string, if available.
*
* @param $name
* Textgroup and context glued with ':'.
* @param $default
* String in default language. Default language may or may not be English.
* @param $options
* An associative array of additional options, with the following keys:
* - langcode: the language code to translate to a language other than what is
* used to display the page; defaults to the current language
* - filter: filtering callback to apply to the translated string only
* - format: input format to apply to the translated string only
* - callback: callback to apply to the result (both to the translated or
* untranslated string)
* - update: whether to update source table; defaults to FALSE
* - translate: whether to return a translation; defaults to TRUE
*
* @return
* The translated string if i18n_string is available, the original otherwise.
*
* @see i18n_string()
*/
function commerce_i18n_string($name, $default, $options = array()) {
if (module_exists('i18n_string')) {
$result = i18n_string($name, $default, $options);
}
else {
$result = $default;
$options += array(
'format' => NULL,
'sanitize' => FALSE,
);
if ($options['sanitize']) {
$result = check_markup($result, $options['format']);
}
}
return $result;
}
/**
* Returns the currency code of the site's default currency.
*/
function commerce_default_currency() {
$config = config('commerce.settings');
$currency_code = $config->get('commerce_default_currency');
backdrop_alter('commerce_default_currency', $currency_code);
return $currency_code;
}
/**
* Returns a single currency array.
*
* @param $currency_code
* The code of the currency to return or NULL to return the default currency.
*
* @return
* The specified currency array or FALSE if it does not exist.
*/
function commerce_currency_load($currency_code = NULL) {
$currencies = commerce_currencies();
// Check to see if we should return the default currency.
if (empty($currency_code)) {
$currency_code = commerce_default_currency();
}
return isset($currencies[$currency_code]) ? $currencies[$currency_code] : FALSE;
}
/**
* Returns an array of all available currencies.
*
* @param $enabled
* Boolean indicating whether or not to return only enabled currencies.
* @param $reset
* Boolean indicating whether or not the cache should be reset before currency
* data is loaded and returned.
*
* @return
* An array of altered currency arrays keyed by the currency code.
*/
function commerce_currencies($enabled = FALSE, $reset = FALSE) {
$config = config('commerce.settings');
global $language;
$currencies = &backdrop_static(__FUNCTION__);
// If there is no static cache for currencies yet or a reset was specified...
if (!isset($currencies) || $reset) {
// First attempt to load currency data from the cache if we simply didn't
// have it statically cached and a reset hasn't been specified.
if (!$reset && $currencies_cached = cache_get('commerce_currencies:' . $language->langcode)) {
$currencies['all'] = $currencies_cached->data;
}
else {
// Otherwise we'll load currency definitions afresh from enabled modules.
// Begin by establishing some default values for currencies.
$defaults = array(
'symbol' => '',
'minor_unit' => '',
'decimals' => 2,
'rounding_step' => 0,
'thousands_separator' => ',',
'decimal_separator' => '.',
'symbol_placement' => 'hidden',
'symbol_spacer' => "\xC2\xA0",
'code_placement' => 'after',
'code_spacer' => "\xC2\xA0",
'format_callback' => '',
'conversion_callback' => '',
'conversion_rate' => 1,
);
// Include the currency file and invoke the currency info hook.
module_load_include('inc', 'commerce', 'includes/commerce.currency');
$currencies['all'] = module_invoke_all('commerce_currency_info');
backdrop_alter('commerce_currency_info', $currencies['all'], $language->langcode);
// Add default values if they don't exist.
foreach ($currencies['all'] as $currency_code => $currency) {
$currencies['all'][$currency_code] = array_merge($defaults, $currency);
}
// Sort the currencies
ksort($currencies['all']);
cache_set('commerce_currencies:' . $language->langcode, $currencies['all']);
}
$lang = ($config->get('commerce_enabled_currencies'));
// Form an array of enabled currencies based on the variable set by the
// checkboxes element on the currency settings form.
$enabled_currencies = array_diff(array_values($lang), array(0));
$currencies['enabled'] = array_intersect_key($currencies['all'], backdrop_map_assoc($enabled_currencies));
}
return $enabled ? $currencies['enabled'] : $currencies['all'];
}
/**
* Returns an associative array of the specified currency codes.
*
* @param $enabled
* Boolean indicating whether or not to include only enabled currencies.
*/
function commerce_currency_get_code($enabled = FALSE) {
return backdrop_map_assoc(array_keys(commerce_currencies($enabled)));
}
/**
* Wraps commerce_currency_get_code() for use by the Entity module.
*/
function commerce_currency_code_options_list() {
return commerce_currency_get_code(TRUE);
}
/**
* Returns the symbol of any or all currencies.
*
* @param $code
* Optional parameter specifying the code of the currency whose symbol to return.
*
* @return
* Either an array of all currency symbols keyed by the currency code or a
* string containing the symbol for the specified currency. If a currency is
* specified that does not exist, this function returns FALSE.
*/
function commerce_currency_get_symbol($currency_code = NULL) {
$currencies = commerce_currencies();
// Return a specific currency symbol if specified.
if (!empty($currency_code)) {
if (isset($currencies[$currency_code])) {
return $currencies[$currency_code]['symbol'];
}
else {
return FALSE;
}
}
// Otherwise turn the array values into the type name only.
foreach ($currencies as $currency_code => $currency) {
$currencies[$currency_code] = $currency['symbol'];
}
return $currencies;
}
/**
* Formats a price for a particular currency.
*
* @param $amount
* A numeric price amount value.
* @param $currency_code
* The three character code of the currency.
* @param $object
* When present, the object to which the price is attached.
* @param $convert
* Boolean indicating whether or not the amount needs to be converted to a
* decimal price amount when formatting.
*
* @return
* A fully formatted currency.
*/
function commerce_currency_format($amount, $currency_code, $object = NULL, $convert = TRUE) {
// First load the currency array.
$currency = commerce_currency_load($currency_code);
// Then convert the price amount to the currency's major unit decimal value.
if ($convert == TRUE) {
$amount = commerce_currency_amount_to_decimal($amount, $currency_code);
}
// Invoke the custom format callback if specified.
if (!empty($currency['format_callback'])) {
return $currency['format_callback']($amount, $currency, $object);
}
// Format the price as a number.
$price = number_format(commerce_currency_round(abs($amount), $currency), $currency['decimals'], $currency['decimal_separator'], $currency['thousands_separator']);
// Establish the replacement values to format this price for its currency.
$replacements = array(
'@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
'@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
'@price' => $price,
'@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
'@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
'@negative' => $amount < 0 ? '-' : '',
'@symbol_spacer_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol_spacer'] : '',
'@symbol_spacer' => $currency['symbol_placement'] == 'after' ? $currency['symbol_spacer'] : '',
'@code_spacer' => $currency['code_spacer'],
);
// We switched from using trim() after token replacement because it couldn't
// adequately trim non-breaking space characters while supporting certain
// currency symbols like the GBP £. preg_replace() it slightly slower, but
// the difference should be negligible on almost any site. If it becomes an
// issue, we can introduce an if statement here to use trim() by default and
// maintain an array of currency codes for which we must use preg_replace().
$pattern = '/^\s+|\s+$/us';
return preg_replace($pattern, '', check_plain(strtr('@code_before@code_spacer@negative@symbol_before@symbol_spacer_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements)));
}
/**
* Rounds a price amount for the specified currency.
*
* Rounding of the minor unit with a currency specific step size. For example,
* Swiss Francs are rounded using a step size of 0.05. This means a price of
* 10.93 is converted to 10.95.
*
* @param $amount
* The numeric amount value of the price to be rounded.
* @param $currency
* The currency array containing the rounding information pertinent to this
* price. Specifically, this function looks for the 'rounding_step' property
* for the step size to round to, supporting '0.05' and '0.02'. If the value
* is 0, this function performs normal rounding to the nearest supported
* decimal value.
*
* @return
* The rounded numeric amount value for the price.
*/
function commerce_currency_round($amount, $currency) {
if (!$currency['rounding_step']) {
return round($amount, $currency['decimals']);
}
$modifier = 1 / $currency['rounding_step'];
return round($amount * $modifier) / $modifier;
}
/**
* Converts a price amount from a currency to the target currency based on the
* current currency conversion rates.
*
* The Commerce module establishes a default conversion rate for every currency
* as 1, so without any additional information there will be a 1:1 conversion
* from one currency to the next. Other modules can provide UI based or web
* service based alterations to the conversion rate of the defined currencies as
* long as every rate is calculated relative to a single base currency. It does
* not matter which currency is the base currency as long as the same one is
* used for every rate calculation.
*
* To convert an amount from one currency to another, we simply take the amount
* value and multiply it by the current currency's conversion rate divided by
* the target currency's conversion rate.
*
* @param $amount
* The numeric amount value of the price to be rounded.
* @param $currency_code
* The currency code for the current currency of the price.
* @param $target_currency_code
* The currency code for the target currency of the price.
*
* @return
* The numeric amount value converted to its equivalent in the target currency.
*/
function commerce_currency_convert($amount, $currency_code, $target_currency_code) {
$currency = commerce_currency_load($currency_code);
// Invoke the custom conversion callback if specified.
if (!empty($currency['conversion_callback'])) {
return $currency['conversion_callback']($amount, $currency_code, $target_currency_code);
}
$target_currency = commerce_currency_load($target_currency_code);
// First multiply the amount to accommodate differences in decimals between
// the source and target currencies.
$exponent = $target_currency['decimals'] - $currency['decimals'];
$amount *= pow(10, $exponent);
return $amount * ($currency['conversion_rate'] / $target_currency['conversion_rate']);
}
/**
* Converts a price amount to an integer value for storage in the database.
*
* @param $decimal
* The decimal amount to convert to a price amount.
* @param $currency_code
* The currency code of the price whose decimals value will be used to
* multiply by the proper factor when converting the decimal amount.
* @param $round
* Whether or not the return value should be rounded and cast to an integer;
* defaults to TRUE as necessary for standard price amount column storage.
*
* @return
* The appropriate price amount based on the currency's decimals value.
*/
function commerce_currency_decimal_to_amount($decimal, $currency_code, $round = TRUE) {
static $factors;
// If the divisor for this currency hasn't been calculated yet...
if (empty($factors[$currency_code])) {
// Load the currency and calculate its factor as a power of 10.
$currency = commerce_currency_load($currency_code);
$factors[$currency_code] = pow(10, $currency['decimals']);
}
// Ensure the amount has the proper number of decimal places for the currency.
if ($round) {
$decimal = commerce_currency_round($decimal, commerce_currency_load($currency_code));
return (int) round($decimal * $factors[$currency_code]);
}
else {
return $decimal * $factors[$currency_code];
}
}
/**
* Converts a price amount to a decimal value based on the currency.
*
* @param $amount
* The price amount to convert to a decimal value.
* @param $currency_code
* The currency code of the price whose decimals value will be used to
* divide by the proper divisor when converting the amount.
*
* @return
* The decimal amount depending on the number of places the currency uses.
*/
function commerce_currency_amount_to_decimal($amount, $currency_code) {
static $divisors;
// If the divisor for this currency hasn't been calculated yet...
if (empty($divisors[$currency_code])) {
// Load the currency and calculate its divisor as a power of 10.
$currency = commerce_currency_load($currency_code);
$divisors[$currency_code] = pow(10, $currency['decimals']);
}
return $amount / $divisors[$currency_code];
}
/**
* Returns an associative array of month names keyed by numeric representation.
*/
function commerce_months() {
return array(
'01' => t('January'),
'02' => t('February'),
'03' => t('March'),
'04' => t('April'),
'05' => t('May'),
'06' => t('June'),
'07' => t('July'),
'08' => t('August'),
'09' => t('September'),
'10' => t('October'),
'11' => t('November'),
'12' => t('December'),
);
}
/**
* Returns an array of numerical comparison operators for use in Rules.
*/
function commerce_numeric_comparison_operator_options_list() {
return backdrop_map_assoc(array('<', '<=', '=', '>=', '>'));
}
/**
* Returns an options list of round modes.
*/
function commerce_round_mode_options_list() {
return array(
COMMERCE_ROUND_NONE => t('Do not round at all'),
COMMERCE_ROUND_HALF_UP => t('Round the half up'),
COMMERCE_ROUND_HALF_DOWN => t('Round the half down'),
COMMERCE_ROUND_HALF_EVEN => t('Round the half to the nearest even number'),
COMMERCE_ROUND_HALF_ODD => t('Round the half to the nearest odd number'),
);
}
/**
* Rounds a number using the specified rounding mode.
*
* @param $round_mode
* The round mode specifying which direction to round the number.
* @param $number
* The number to round.
*
* @return
* The number rounded based on the specified mode.
*
* @see commerce_round_mode_options_list()
*/
function commerce_round($round_mode, $number) {
// Remember if this is a negative or positive number and make it positive.
$negative = $number < 0;
$number = abs($number);
// Store the decimal value of the number.
$decimal = $number - floor($number);
// No need to round if there is no decimal value.
if ($decimal == 0) {
return $negative ? -$number : $number;
}
// Round it now according to the specified round mode.
switch ($round_mode) {
// PHP's round() function defaults to rounding the half up.
case COMMERCE_ROUND_HALF_UP:
$number = round($number);
break;
// PHP < 5.3.0 does not support rounding the half down, so we compare the
// decimal value and use floor() / ceil() directly.
case COMMERCE_ROUND_HALF_DOWN:
if ($decimal <= .5) {
$number = floor($number);
}
else {
$number = ceil($number);
}
break;
// PHP < 5.3.0 does not support rounding to the nearest even number, so we
// determine it ourselves if the decimal is .5.
case COMMERCE_ROUND_HALF_EVEN:
if ($decimal == .5) {
if (floor($number) % 2 == 0) {
$number = floor($number);
}
else {
$number = ceil($number);
}
}
else {
$number = round($number);
}
break;
// PHP < 5.3.0 does not support rounding to the nearest odd number, so we
// determine it ourselves if the decimal is .5.
case COMMERCE_ROUND_HALF_ODD:
if ($decimal == .5) {
if (floor($number) % 2 == 0) {
$number = ceil($number);
}
else {
$number = floor($number);
}
}
else {
$number = round($number);
}
break;
case COMMERCE_ROUND_NONE:
default:
break;
}
// Return the number preserving the initial negative / positive value.
return $negative ? -$number : $number;
}
/**
* Adds child elements to a SimpleXML element using the data provided.
*
* @param $simplexml_element
* The SimpleXML element that will be populated with children from the child
* data array. This should already be initialized with its container element.
* @param $child_data
* The array of data. It can be of any depth, but it only provides support for
* child elements and their values - not element attributes. If an element can
* have multiple child elements with the same name, you cannot depend on a
* simple associative array because of key collision. You must instead include
* each child element as a value array in a numerically indexed array.
*/
function commerce_simplexml_add_children(&$simplexml_element, $child_data) {
// Loop over all the child data...
foreach ($child_data as $key => $value) {
// If the current child is itself a container...
if (is_array($value)) {
// If it has a non-numeric key...
if (!is_numeric($key)) {
// Add a child element to the current element with the key as the name.
$child_element = $simplexml_element->addChild("$key");
// Add the value of this element to the child element.
commerce_simplexml_add_children($child_element, $value);
}
else {
// Otherwise assume we have multiple child elements of the same name and
// pass through to add the child data from the current value array to
// current element.
commerce_simplexml_add_children($simplexml_element, $value);
}
}
else {
// Otherwise add the child element with its simple value.
$simplexml_element->addChild("$key", htmlspecialchars($value, ENT_QUOTES, 'UTF-8', FALSE));
}
}
}
/**
* Generic access control for Drupal Commerce entities.
*
* @param $op
* The operation being performed. One of 'view', 'update', 'create' or
* 'delete'.