summaryrefslogtreecommitdiffstats
path: root/modules/cart/commerce_marketplace_cart.module
blob: 9af20549858c91939061dfdb6b071c519c25bc07 (plain)
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
<?php

/**
 * @file
 * Adapts core shopping cart features for Commerce Marketplace.
 */

/**
 * Implements hook_views_api().
 */
function commerce_marketplace_cart_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'commerce_marketplace_cart') . '/includes/views',
  );
}

/**
 * Implements hook_menu_alter().
 */
function commerce_marketplace_cart_menu_alter(&$items) {
  $items['cart']['page callback'] = 'commerce_marketplace_cart_view';
  $items['checkout']['page callback'] = 'commerce_marketplace_cart_checkout_router';
}

/**
 * Redirects invalid checkout attempts or displays the checkout form if valid.
 *
 * Overrides commerce_cart_checkout_router() to check quantity of all orders
 * in the order group.
 *
 * @see commerce_cart_checkout_router()
 * @see commerce_marketplace_cart_menu_alter()
 * @see commerce_cart_menu()
 */
function commerce_marketplace_cart_checkout_router() {
  global $user;

  // If no shopping cart order could be found, redirect away from checkout.
  if (
    !($orders = commerce_marketplace_cart_order_load_multiple($user->uid))
    || !commerce_marketplace_order_quantity($orders)
  ) {
    drupal_set_message(t('Add some items to your cart and then try checking out.'));
    drupal_goto(variable_get('commerce_checkout_empty_redirect', 'cart'));
  }

  $order = reset($orders);
  drupal_goto('checkout/' . $order->order_id);
}

/**
 * Displays the shopping cart form and associated information, providing option
 * to display a view of line items from multiple user's orders (for multiple
 * stores).
 *
 * Overrides commerce_cart_view().
 *
 * @see commerce_cart_view()
 */
function commerce_marketplace_cart_view() {
  global $user;

  // Default to displaying an empty message.
  $content = theme('commerce_cart_empty_page');

  // First check to make sure we have a valid order.
  if ($orders = commerce_marketplace_cart_order_load_multiple($user->uid)) {

    // Only show the cart form if we found product line items.
    $quantity = commerce_marketplace_order_quantity($orders);
    if ($quantity > 0) {

      // Order ID view contextual filter should be a string
      // listing all order IDs separated by a comma.
      $order_ids = implode(',', array_keys($orders));

      // Add the form for editing the cart contents.
      $content = commerce_embed_view('commerce_cart_form', 'default', array($order_ids), 'cart');
    }
  }

  return $content;
}

/**
 * Implements hook_views_pre_view().
 *
 * @see commerce_marketplace_cart_views_pre_build()
 */
function commerce_marketplace_cart_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'commerce_cart_form' || $view->name == 'commerce_cart_summary') {
    $cart_split_fields = commerce_marketplace_cart_get_splitter_field_instances(NULL, 'cart');
    if (!empty($cart_split_fields)) {

      foreach ($cart_split_fields as $field_name => $field_instance) {
        // If the field does not exist in the view, we want to add it.
        if (empty($view->field[$field_name])) {

          // Get database table name for this field.
          $field = field_info_field($field_name);
          $db_table_name = _field_sql_storage_tablename($field);

          // We don't want this new field to be visible anywhere.
          $options = array(
            'label' => $field_instance['label'],
            'exclude' => TRUE,
          );

          // Add the field to the view.
          $view->add_item($view->current_display, 'field', $db_table_name, $field_name, $options);
        }
      }
    }
  }
}

/**
 * Implements hook_views_pre_build().
 *
 * @see commerce_marketplace_cart_views_pre_view()
 */
function commerce_marketplace_cart_views_pre_build(&$view) {
  if ($view->name == 'commerce_cart_form' || $view->name == 'commerce_cart_summary') {

    $cart_split_fields = commerce_marketplace_cart_get_splitter_field_instances(NULL, 'cart');
    if (!empty($cart_split_fields)) {

      // Helper variable to avoid using such long string multiple times.
      $style_options = &$view->display[$view->current_display]->handler->options['style_options'];

      // Create an array containing just existing grouping field names,
      // so it is easy to search through it and decide whether our new
      // cart splitting should be added there or not.
      $existing_grouping_field_names = array();
      if (!empty($style_options['grouping'])) {
        foreach ($style_options['grouping'] as $existing_grouping) {
          $existing_grouping_field_names[] = $existing_grouping['field'];
        }
      }
      else {
        $style_options['grouping'] = array();
      }

      // Loop through all cart splitting fields, and add them
      // as view's grouping fields if they are not already there.
      foreach ($cart_split_fields as $field_name => $field_instance) {
        if (!in_array($field_name, $existing_grouping_field_names)) {
          $style_options['grouping'][] = array(
            'field' => $field_name,
            // Use rendered output to group rows.
            'rendered' => 1,
            // Remove tags from rendered output.
            'rendered_strip' => 0,
          );
        }
      }
    }
  }
}

/**
 * Implements hook_block_view_alter().
 *
 * Alters 'Shopping cart' block to display all non-empty orders from the order
 * group.
 *
 * @see commerce_cart_block_view()
 */
function commerce_marketplace_cart_block_view_alter(&$data, $block) {
  global $user;

  if ($block->module == 'commerce_cart' && $block->delta == 'cart') {
    // Default to an empty cart block message.
    $content = theme('commerce_cart_empty_block');

    // First check to ensure there are products in the shopping cart.
    if ($orders = commerce_marketplace_cart_order_load_multiple($user->uid)) {
      foreach ($orders as $order) {
        $wrapper = entity_metadata_wrapper('commerce_order', $order);

        // If there are no products in the cart...
        if (commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()) <= 0) {
          unset($orders[$order->order_id]);
        }
      }

      if (!empty($orders)) {
        // Order ID view contextual filter should be a string
        // listing all order IDs separated by a comma.p
        $order_ids = implode(',', array_keys($orders));

        // Build the variables array to send to the cart block template.
        $variables = array(
          'contents_view' => commerce_embed_view('commerce_cart_block', 'defaults', array($order_ids), $_GET['q']),
        );

        $content = theme('commerce_cart_block', $variables);
      }
    }

    $data['content'] = $content;
  }
}

/**
 * Implements hook_user_login().
 * Extends commerce_cart_user_login().
 *
 * When a user logs into the site, if they have a shopping cart orders
 * they should all be updated to belong to their user account.
 */
function commerce_marketplace_cart_user_login(&$edit, $account) {
  // Get the user's anonymous shopping cart orders if any exists.
  if ($orders = commerce_marketplace_cart_order_load_multiple()) {
    // Convert them to an authenticated cart.
    foreach ($orders as $order) {
      // Last user order (with ID == commerce_cart_order_id()) will be updated
      // by commerce_cart_user_login(), so no need to do it here too.
      if ($order->order_id != commerce_cart_order_id()) {
        commerce_cart_order_convert($order, $account);
      }
    }
  }
}

/**
 * Extends commerce_cart_order_load().
 *
 * Loads the most recent shopping cart order for the specified user and
 * specified store.
 */
function commerce_marketplace_cart_order_load($uid = 0, $conditions = array(), $reset = FALSE) {
  $orders = commerce_marketplace_cart_order_load_multiple($uid, $conditions, $reset);
  return reset($orders);
}

/**
 * Loads all shopping cart orders for the specified user and specified store.
 *
 * Extends commerce_cart_order_load().
 *
 * @see commerce_cart_order_load()
 */
function commerce_marketplace_cart_order_load_multiple($uid = 0, $conditions = array(), $reset = FALSE) {
  // Retrieve the order ID for the specified user's current shopping cart.
  $order_ids = commerce_marketplace_cart_order_ids($uid, $conditions, $reset);

  // If a valid cart order ID exists for the user, return it now.
  return !empty($order_ids) ? commerce_order_load_multiple($order_ids, NULL, $reset) : array();
}

/**
 * Returns order group ID for the current user.
 */
function commerce_marketplace_cart_get_current_order_group_id() {
  global $user;
  $orders = commerce_marketplace_cart_order_load_multiple($user->uid);
  if (!empty($orders)) {
    $order = reset($orders);
    return $order->order_group;
  }
  else {
    $last_group = db_select('commerce_order','co')->fields('co', array('order_group'))->orderby('order_group','DESC')->range(0,1)->execute()->fetchField();
    // If no order exists yet, just return 1 as the very first order group ID.
    return $last_group ? ++$last_group : 1;
  }
}

/**
 * Returns the current cart order ID for the given user.
 *
 * Extends commerce_cart_order_id().
 *
 * @see commerce_cart_order_id()
 */
function commerce_marketplace_cart_order_ids($uid = 0, $conditions = array(), $reset = FALSE) {
  $cache_key = md5(json_encode($conditions));

  $cart_order_ids = &drupal_static(__FUNCTION__, array());

  // If reset delete all values in the static variable.
  if ($reset) {
    $cart_order_ids = array();
  }

  // Cart order IDs will be cached keyed by $uid and $cache_key generated
  // from other $conditions.
  // Return the cached value if available.
  if (isset($cart_order_ids[$uid][$cache_key])) {
    return $cart_order_ids[$uid][$cache_key];
  }

  // First let other modules attempt to provide a valid order ID for the given
  // uid. Instead of invoking hook_commerce_cart_order_id() directly, we invoke
  // it in each module implementing the hook and return the first valid order ID
  // returned (if any).
  foreach (module_implements('commerce_marketplace_cart_order_id') as $module) {
    $order_ids = module_invoke($module, 'commerce_marketplace_cart_order_ids', $uid, $conditions);

    // If a hook said the user should not have a cart, that overrides any other
    // potentially valid order ID. Return FALSE now.
    if ($order_ids === FALSE) {
      return $cart_order_ids[$uid][$cache_key] = array();
    }

    // If a hook returned a single order ID instead of an array, convert it.
    if (!is_array($order_ids)) {
      $order_ids = array($order_ids);
    }

    // Otherwise only return a valid order IDs.
    if (!empty($order_ids) && is_array($order_ids)) {
      return $cart_order_ids[$uid][$cache_key] = $order_ids;
    }
  }

  // If no order ID exists in anonymous user's session.
  if (!$uid && !commerce_cart_order_session_exists()) {
    return $cart_order_ids[$uid][$cache_key] = array();
  }

  // Create an array of valid shopping cart order statuses.
  $status_ids = array_keys(commerce_order_statuses(array('cart' => TRUE)));

  // Start building query to look for user's shopping cart orders.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'commerce_order', '=')
    ->propertyCondition('uid', $uid)
    ->propertyCondition('status', $status_ids, 'IN')
    ->propertyOrderBy('order_id', 'DESC');

  // If store ID was provided as FALSE, it means we want orders with products
  // not assigned to any store. And because EFQ does not support IS NULL
  // condition, we have to tag the query here and add the condition in
  // commerce_marketplace_cart_query_null_order_id_alter().

  // Process any additional conditions.
  if (!empty($conditions) && is_array($conditions)) {
    $null_fields = array();
    foreach ($conditions as $field_name => $field_value) {

      // Get database column name from the field information.
      $field = field_info_field($field_name);
      $column = key($field['columns']);

      // If a field should have any specific non-NULL value, we can use
      // standard EFQ functionality.
      if ($field_value !== NULL) {
        $query->fieldCondition($field_name, $column, $field_value, '=');
      }
      // For NULL values though we need some cheating. EntityFieldQuery does not
      // support IS NULL conditions natively (as it doesn't support LEFT JOINs),
      // therefore we need to go around it, as we definitely need it here.
      // Let's then prepare all the data we'll need for adding a LEFT JOIN
      // and relevant IS NULL condition using custom hook_query_TAG_alter()
      // implementation, and tag the query appropriately.
      // Some code borrowed from field_sql_storage_field_storage_query().
      else {
        // Gather all the data that will be needed to add a LEFT JOIN
        // and IS NULL condition later on.
        $tablename_function = ($query->age == FIELD_LOAD_CURRENT) ? '_field_sql_storage_tablename' : '_field_sql_storage_revision_tablename';
        $db_table_name = $tablename_function($field);
        $db_table_alias = _field_sql_storage_tablealias($db_table_name, '_null', $query);
        $db_field_name = _field_sql_storage_columnname($field_name, $column);

        // Add it to the array which we'll attach to the query's metadata.
        $null_fields[$db_table_name] = array(
          'table' => $db_table_name,
          'alias' => $db_table_alias,
          'conditions' => "commerce_order.order_id = $db_table_alias.entity_id",
          'field_name' => $db_field_name,
        );
      }
    }
    // If there were any fields on which we need IS NULL condition, let's add
    // them to the query's metadata and tag the query appropriately. The LEFT
    // JOINs and IS NULL conditions will be added to it in
    // commerce_marketplace_cart_query_cart_order_ids_null_fields_alter().
    if (!empty($null_fields)) {
      $query->addTag('cart_order_ids_null_fields');
      $query->addMetaData('cart_order_ids_null_fields', $null_fields);
    }
  }

  $query_params = array(
    ':uid' => $uid,
    ':status_ids' => $status_ids,
  );

  // For anonymous users look for a shopping cart order ID in the session.
  if (!$uid) {
    $session_order_ids = commerce_cart_order_session_order_ids();
    // If no order IDs were found in the session, let's still add the query
    // parameter with value of -1 (generally, it could be any value that always
    // would be different from any possible order ID) - to make sure that the
    // 'order_id' condition is still added to the query below, but could never
    // be true  - otherwise the query might return IDs of orders belonging
    // to other anonymous users.
    $query_params[':order_ids'] = (!empty($session_order_ids)) ? $session_order_ids : array(-1);
  }

  // We want the same behavior as in standard DC - return only orders from the
  // most recent order group.
  $order_group_id = db_query(
    'SELECT MAX(order_group)
      FROM {commerce_order}
      WHERE uid = :uid AND status IN (:status_ids)' . ((isset($query_params[':order_ids'])) ? ' AND order_id IN (:order_ids)' : ''),
      $query_params
  )->fetchField();

  $query->propertyCondition('order_group', $order_group_id);
  $entities = $query->execute();

  $cart_order_ids[$uid][$cache_key] = !empty($entities['commerce_order']) ? array_keys($entities['commerce_order']) : FALSE;

  return $cart_order_ids[$uid][$cache_key];
}

/**
 * Implements hook_query_TAG_alter() for cart_order_ids_null_fields.
 *
 * Adds extra condition to store select query not supported by default by EFQ.
 *
 * @see commerce_marketplace_cart_order_ids()
 */
function commerce_marketplace_cart_query_cart_order_ids_null_fields_alter(QueryAlterableInterface $query) {
  foreach ($query->getMetaData('cart_order_ids_null_fields') as $null_field) {
    $query->leftJoin($null_field['table'], $null_field['alias'], $null_field['conditions']);
    $query->isNull($null_field['alias'] . '.' . $null_field['field_name']);
  }
}

/**
 * Implements hook_form_alter().
 */
function commerce_marketplace_cart_form_alter(&$form, &$form_state, $form_id) {

  // Override original add to cart form submit callback with our own to make
  // sure new order is created for each store.
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') !== FALSE) {
    $delta = array_search('commerce_cart_add_to_cart_form_submit', $form['#submit']);
    $form['#submit'][$delta] = 'commerce_marketplace_cart_add_to_cart_form_submit';
  }

  // Shopping cart form.
  if (strpos($form_id, 'views_form_commerce_cart_form_') === 0) {
    // If the cart form View shows line items, update submits for both buttons
    // so that when either one is used, statuses of all orders are updated.
    $view = reset($form_state['build_info']['args']);
    if (!empty($view->result)) {
      // Shopping cart: Update cart button - update
      if (FALSE !== $key = array_search('commerce_cart_line_item_views_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][$key] = 'commerce_marketplace_cart_line_item_views_form_submit';
      }
    }
  }
}

/**
 * Form submit handler: add the selected product to the cart.
 *
 * Overrides commerce_cart_add_to_cart_form_submit().
 *
 * @see commerce_cart_add_to_cart_form_submit()
 */
function commerce_marketplace_cart_add_to_cart_form_submit($form, &$form_state) {
  $product_id = $form_state['values']['product_id'];
  $product = commerce_product_load($product_id);

  // If the line item passed to the function is new...
  if (empty($form_state['line_item']->line_item_id)) {
    // Create the new product line item of the same type.
    $line_item = commerce_product_line_item_new($product, $form_state['values']['quantity'], 0, $form_state['line_item']->data, $form_state['line_item']->type);

    // Allow modules to prepare this as necessary. This hook is defined by the
    // Product Pricing module.
    drupal_alter('commerce_product_calculate_sell_price_line_item', $line_item);

    // Remove line item field values the user didn't have access to modify.
    foreach ($form_state['values']['line_item_fields'] as $field_name => $value) {
      // Note that we're checking the Commerce Cart settings that we inserted
      // into this form element array back when we built the form. This means a
      // module wanting to alter a line item field widget to be available must
      // update both its form element's #access value and the field_access value
      // of the #commerce_cart_settings array.
      if (empty($form['line_item_fields'][$field_name]['#commerce_cart_settings']['field_access'])) {
        unset($form_state['values']['line_item_fields'][$field_name]);
      }
    }

    // Unset the line item field values array if it is now empty.
    if (empty($form_state['values']['line_item_fields'])) {
      unset($form_state['values']['line_item_fields']);
    }

    // Add field data to the line item.
    field_attach_submit('commerce_line_item', $line_item, $form['line_item_fields'], $form_state);

    // Process the unit price through Rules so it reflects the user's actual
    // purchase price.
    rules_invoke_event('commerce_product_calculate_sell_price', $line_item);

    // Only attempt an Add to Cart if the line item has a valid unit price.
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    if (!is_null($line_item_wrapper->commerce_unit_price->value())) {
      // Add the product to the specified shopping cart.
      $form_state['line_item'] = commerce_marketplace_cart_product_add(
        $form_state['values']['uid'],
        $line_item,
        isset($line_item->data['context']['add_to_cart_combine']) ? $line_item->data['context']['add_to_cart_combine'] : TRUE
      );
    }
    else {
      drupal_set_message(t('%title could not be added to your cart.', array('%title' => $product->title)), 'error');
    }
  }
}

/**
 * Adds the specified product to a customer's shopping cart.
 *
 * Overrides commerce_cart_product_add().
 *
 * @see commerce_cart_product_add()
 */
function commerce_marketplace_cart_product_add($uid, $line_item, $combine = TRUE) {
  // Do not add the line item if it doesn't have a unit price.
  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

  if (is_null($line_item_wrapper->commerce_unit_price->value())) {
    return FALSE;
  }

  $product = $line_item_wrapper->commerce_product->value();

  $conditions = array();

  // Loop through all the field instances on that product type.
  foreach (commerce_marketplace_cart_get_splitter_field_instances($product->type) as $field_name => $instance) {
    $referenced_entity_info = $line_item_wrapper->commerce_product->$field_name->entityInfo();
    $referenced_entity_id = $referenced_entity_info['entity keys']['id'];

    if ($line_item_wrapper->commerce_product->$field_name->value()) {
      $conditions[$field_name] = $line_item_wrapper->commerce_product->$field_name->$referenced_entity_id->value();
    }
    else {
      $conditions[$field_name] = NULL;
    }
  }

  // If product is not assigned to any store, we need to check for orders not
  // assigned to any store either, which means passing FALSE as a second param
  // to commerce_marketplace_cart_order_load().
  $order = commerce_marketplace_cart_order_load($uid, $conditions);

  // If no order existed, create one now.
  if (empty($order)) {
    // We need to get order group ID before calling commerce_cart_order_new(),
    // as it will already save a new order with order group ID set to 0.
    $order_group = commerce_marketplace_cart_get_current_order_group_id();
    $order = commerce_cart_order_new($uid);
    $order->order_group = $order_group;
  }

  // Set the incoming line item's order_id.
  $line_item->order_id = $order->order_id;

  // Wrap the order for easy access to field data.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

  // Add all splitter field values to the order.
  foreach ($conditions as $field_name => $field_value) {
    if (!empty($field_value)) {
      $order_wrapper->$field_name = $field_value;
    }
  }

  // Extract the product and quantity we're adding from the incoming line item.
  $product = $line_item_wrapper->commerce_product->value();
  $quantity = $line_item->quantity;

  // Invoke the product prepare event with the shopping cart order.
  rules_invoke_all('commerce_cart_product_prepare', $order, $product, $line_item->quantity);

  // Determine if the product already exists on the order and increment its
  // quantity instead of adding a new line if it does.
  $matching_line_item = NULL;

  // If we are supposed to look for a line item to combine into...
  if ($combine) {
    // Generate an array of properties and fields to compare.
    $comparison_properties = array('type', 'commerce_product');

    // Add any field that was exposed on the Add to Cart form to the array.
    // TODO: Bypass combination when an exposed field is no longer available but
    // the same base product is added to the cart.
    foreach (field_info_instances('commerce_line_item', $line_item->type) as $info) {
      if (!empty($info['commerce_cart_settings']['field_access'])) {
        $comparison_properties[] = $info['field_name'];
      }
    }

    // Allow other modules to specify what properties should be compared when
    // determining whether or not to combine line items.
    drupal_alter('commerce_cart_product_comparison_properties', $comparison_properties);

    // Loop over each line item on the order.
    foreach ($order_wrapper->commerce_line_items as $delta => $matching_line_item_wrapper) {
      // Examine each of the comparison properties on the line item.
      foreach ($comparison_properties as $property) {
        // If any property does not match the same property on the incoming line
        // item...
        if ($matching_line_item_wrapper->{$property}->raw() != $line_item_wrapper->{$property}->raw()) {
          // Continue the loop with the next line item.
          continue 2;
        }
      }

      // If every comparison line item matched, combine into this line item.
      $matching_line_item = $matching_line_item_wrapper->value();
      break;
    }
  }

  // If no matching line item was found...
  if (empty($matching_line_item)) {
    // Save the incoming line item now so we get its ID.
    commerce_line_item_save($line_item);

    // Add it to the order's line item reference value.
    $order_wrapper->commerce_line_items[] = $line_item;
  }
  else {
    // Increment the quantity of the matching line item, update the data array,
    // and save it.
    $matching_line_item->quantity += $quantity;
    $matching_line_item->data = array_merge($line_item->data, $matching_line_item->data);

    commerce_line_item_save($matching_line_item);

    // Clear the line item cache so the updated quantity will be available to
    // the ensuing load instead of the original quantity as loaded above.
    entity_get_controller('commerce_line_item')->resetCache(array($matching_line_item->line_item_id));

    // Update the line item variable for use in the invocation and return value.
    $line_item = $matching_line_item;
  }

  // Save the updated order.
  commerce_order_save($order);

  // Invoke the product add event with the newly saved or updated line item.
  rules_invoke_all('commerce_cart_product_add', $order, $product, $quantity, $line_item);

  // Return the line item.
  return $line_item;
}

/**
 * Submit handler to show the shopping cart updated message.
 *
 * Overrides commerce_cart_line_item_views_form_submit().
 *
 * @see commerce_cart_line_item_views_form_submit()
 */
function commerce_marketplace_cart_line_item_views_form_submit($form, &$form_state) {
  global $user;

  // Process only orders with the 'cart' status type.
  if ($orders = commerce_marketplace_cart_order_load_multiple($user->uid)) {
    foreach ($orders as $group_order) {
      // Reset the status of the order to cart.
      $group_order = commerce_order_status_update($group_order, 'cart', TRUE);

      // Skip saving in the status update and manually save here to force a save
      // even when the status doesn't actually change.
      if (variable_get('commerce_order_auto_revision', TRUE)) {
        $group_order->revision = TRUE;
        $group_order->log = t('Customer updated the order via the shopping cart form.');
      }

      commerce_order_save($group_order);

      // Re-add updated order to the form.
      if ($group_order->order_id == $form_state['order']->order_id) {
        $form_state['order'] = $group_order;
      }
    }
  }

  drupal_set_message(t('Your shopping cart has been updated.'));
}

/**
 * Implements hook_form_FORM_ID_alter() for field_ui_field_edit_form().
 *
 * Alters the Field UI field edit form to add per-instance settings for fields
 * on product types governing the use of product fields as attribute selection
 * fields on the Add to Cart form.
 *
 * @see field_ui_field_edit_form()
 * @see commerce_marketplace_cart_field_ui_field_edit_form_submit()
 */
function commerce_marketplace_cart_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  // Extract the instance info from the form.
  $instance = $form['#instance'];

  // If the current field instance is not locked, is attached to a product type,
  // and of a field type that defines an options list...
  if (
    empty($form['locked'])
    && $instance['entity_type'] == 'commerce_product'
    && commerce_marketplace_cart_field_splitter_eligible($form['#field'])
  ) {
    // Get the current instance's attribute settings for use as default values.
    $commerce_marketplace_cart_settings = commerce_marketplace_cart_field_instance_splitter_settings($instance);

    $form['instance']['commerce_marketplace_cart_settings'] = array(
      '#type' => 'fieldset',
      '#title' => t('Marketplace settings'),
      '#weight' => 5,
      '#collapsible' => FALSE,
    );
    $form['instance']['commerce_marketplace_cart_settings']['order_splitter_field'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable this field to function as an order splitter field.'),
      '#description' => t('If two products with different field values will be added to the shopping cart, two separate orders will be created for them.'),
      '#default_value' => $commerce_marketplace_cart_settings['order_splitter_field'],
    );
    // Field commerce_store should *always* function as the splitter field.
    if ($instance['field_name'] == 'commerce_store') {
      $form['instance']['commerce_marketplace_cart_settings']['order_splitter_field']['#disabled'] = TRUE;
    }
    $form['instance']['commerce_marketplace_cart_settings']['cart_splitter_field'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable this field to function as a shopping cart splitter field.'),
      '#description' => t('If two products with different field values belong to the same order, they will be displayed in separate cart blocks both on the <em>Shopping cart</em> and the <em>Checkout</em> pages.'),
      '#default_value' => $commerce_marketplace_cart_settings['cart_splitter_field'],
      '#states' => array(
        'visible' => array(
          ':input[name="instance[commerce_marketplace_cart_settings][order_splitter_field]"]' => array('checked' => TRUE),
        ),
      ),
    );

    $form['#submit'][] = 'commerce_marketplace_cart_field_ui_field_edit_form_submit';
  }
}

/**
 * @see commerce_marketplace_cart_form_field_ui_field_edit_form_alter()
 */
function commerce_marketplace_cart_field_ui_field_edit_form_submit($form, &$form_state) {
  $old_instance = $form['#instance'];
  $updated_instance = $form_state['values']['instance'];
  // If updated field instance should be used as the order splitter field.
  if (commerce_marketplace_cart_field_instance_is_splitter($updated_instance, 'order')) {
    // We will base new field instance for commerce_order entities
    // on the original field instance from commerce_product entity type.
    $order_instance = $updated_instance;

    $order_instance['entity_type'] = 'commerce_order';

    // We want to create a new instance on each commerce_order bundle.
    $commerce_order_info = entity_get_info('commerce_order');
    foreach (array_keys($commerce_order_info['bundles']) as $bundle_name) {
      $order_instance['bundle'] = $bundle_name;

      // Check whether the field instance already exists on specific
      // commerce_order bundle.
      $existing_instance = field_info_instance($order_instance['entity_type'], $order_instance['field_name'], $order_instance['bundle']);

      // If it doesn't exist, let's create it.
      if (empty($existing_instance)) {
        field_create_instance($order_instance);
        drupal_set_message(t('Related %field_name field instance on %bundle bundle of %entity_type entity type has been automatically created.', array(
          '%field_name' => $order_instance['field_name'],
          '%entity_type' => $order_instance['entity_type'],
          '%bundle' => $order_instance['bundle'],
        )));
      }
    }
  }
  // If updated field instance should not be used as the order splitter field,
  // let's check if the original instance was used as an splitter, and if so,
  // let's display a message that it will not be used anymore and perhaps
  // should be deleted.
  elseif (commerce_marketplace_cart_field_instance_is_splitter($old_instance, 'order')) {
    $order_entity_type = 'commerce_order';
    $commerce_order_info = entity_get_info($order_entity_type);
    foreach (array_keys($commerce_order_info['bundles']) as $bundle_name) {
      if (field_info_instance($order_entity_type, $old_instance['field_name'], $bundle_name)) {
        drupal_set_message(t('Related %field_name field instance on %entity_type entity type of %bundle type has not been automatically deleted - please do it manually if it is no longer needed. Warning: this might incur any existing data stored in that field to be permanently lost!', array(
          '%field_name' => $old_instance['field_name'],
          '%entity_type' => $order_entity_type,
          '%bundle' => $bundle_name,
        )), 'warning');
      }
    }
  }
}

/**
 * Determines whether or not the given field is eligible to function as a
 * product attribute field on the Add to Cart form.
 *
 * @param $field
 *   The info array of the field whose eligibility you want to determine.
 *
 * @return
 *   TRUE or FALSE indicating the field's eligibility.
 */
function commerce_marketplace_cart_field_splitter_eligible($field) {
  // Returns TRUE if the field is single value (i.e. has a cardinality of 1) and
  // is defined by a module implementing hook_options_list() to provide an array
  // of allowed values structured as human-readable option names keyed by value.
  return $field['cardinality'] == 1 && function_exists($field['module'] . '_options_list');
}

/**
 * Returns order splitter field instances.
 *
 * @param string|null $bundle_name
 *   A bundle of commerce_product entity type which to return splitter field
 *   instances for. Instances for all bundles will be returned if not provided.
 * @return array
 *   An array of spritter field instances keyed by field names.
 */
function commerce_marketplace_cart_get_splitter_field_instances($bundle_name = NULL, $type = 'order') {
  static $drupal_static_fast;

  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['commerce_marketplace_cart_splitters'] = &drupal_static(__FUNCTION__);
  }
  $splitter_field_instances = &$drupal_static_fast['commerce_marketplace_cart_splitters'];

  if (!isset($splitter_field_instances)) {
    // Get all field instances for commerce_product entity type,
    // and optionally for specific bundle name (if provided).
    $instances = field_info_instances('commerce_product', $bundle_name);

    // If bundle name was not provided, we'll get field instances for all
    // commerce_product bundles, additionally keyed by bundle name.
    // In such a case we want to flatten this array first.
    if (empty($bundle_name)) {
      $flattened_instances = array();
      foreach ($instances as $bundle_name => $bundle_instances) {
        $flattened_instances += $bundle_instances;
      }
      $instances = $flattened_instances;
    }

    // Loop through all the field instances on that product type.
    foreach ($instances as $field_name => $instance) {
      // A field qualifies if it is single value, required and uses a widget
      // with a definite set of options. For the sake of simplicity, this is
      // currently restricted to fields defined by the options module.
      $field = field_info_field($field_name);

      // If the instance is of a field type that is eligible to function as
      // a product attribute field and if its attribute field settings
      // specify that this functionality is enabled...
      if (
        commerce_marketplace_cart_field_splitter_eligible($field)
        && commerce_marketplace_cart_field_instance_is_splitter($instance, $type)
      ) {
        $splitter_field_instances[$field_name] = $instance;
      }
    }
  }

  return $splitter_field_instances;
}

/**
 * Returns an array of attribute settings for a field instance.
 *
 * Fields attached to product types may be used as product attribute fields with
 * selection widgets on Add to Cart forms. This function returns the default
 * values for a given field instance.
 *
 * @param $instance
 *   The info array of the field instance whose attribute settings should be
 *   retrieved.
 *
 * @return
 *   An array of attribute settings including:
 *   - attribute_field: boolean indicating whether or not the instance should
 *     be used as a product attribute field on the Add to Cart form; defaults
 *     to FALSE
 *   - attribute_widget: string indicating the type of form element to use on
 *     the Add to Cart form for customers to select the attribute option;
 *     defaults to 'select', may also be 'radios'
 *   - attribute_widget_title: string used as the title of the attribute form
 *     element on the Add to Cart form.
 */
function commerce_marketplace_cart_field_instance_splitter_settings($instance) {
  if (
    empty($instance['commerce_marketplace_cart_settings'])
    || !is_array($instance['commerce_marketplace_cart_settings'])
  ) {
    $commerce_marketplace_cart_settings = array();
  }
  else {
    $commerce_marketplace_cart_settings = $instance['commerce_marketplace_cart_settings'];
  }

  // Supply default values for the cart settings pertaining here to
  // product attribute fields.
  $commerce_marketplace_cart_settings += array(
    'order_splitter_field' => FALSE,
    'cart_splitter_field' => FALSE,
  );

  return $commerce_marketplace_cart_settings;
}

/**
 * Determines whether or not a field instance is fucntioning as a product
 * attribute field.
 *
 * @param $instance
 *   The instance info array for the field instance.
 *
 * @return
 *   Boolean indicating whether or not the field instance is an attribute field.
 */
function commerce_marketplace_cart_field_instance_is_splitter($instance, $type) {
  $commerce_marketplace_cart_settings = commerce_marketplace_cart_field_instance_splitter_settings($instance);
  return !empty($commerce_marketplace_cart_settings[$type . '_splitter_field']);
}

/**
 *
 */
function commerce_marketplace_cart_configure_order_splitter_fields() {
  foreach (field_info_instances('commerce_product') as $bundle_name => $fields) {
    foreach ($fields as $field_name => $instance) {
      if (commerce_marketplace_cart_field_instance_is_splitter($instance, 'order')) {
        $instance['entity_type'] = 'commerce_order';
        $instance['bundle'] = 'commerce_order';
        $existing_instance = field_info_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
        if (empty($existing_instance)) {
          field_create_instance($instance);
          drupal_set_message(t('Created %field_name field instance on %entity_type entity type of %bundle type.', array(
            '%field_name' => $instance['field_name'],
            '%entity_type' => $instance['entity_type'],
            '%bundle' => $instance['bundle'],
          )));
        }
      }
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter() for field_ui_field_delete_form().
 *
 * Disallow to delete a field instance from commerce_order entity type
 * if such field is used as order splitter on any commerce_product bundle.
 *
 * @see field_ui_field_delete_form()
 */
function commerce_marketplace_cart_form_field_ui_field_delete_form_alter(&$form, &$form_state) {
  $instance_being_deleted = $form_state['build_info']['args'][0];

  // Deleting an order splitter field instance from commerce_product entity type
  // should be allowed, no further checks required in such a case.
  $entity_type_to_check = 'commerce_product';
  if ($instance_being_deleted['entity_type'] == $entity_type_to_check) {
    return;
  }

  // Otherwise we need to check if a field to be deleted is not used
  // as an order splitter on any commerce_product entity type.
  $commerce_order_info = entity_get_info($entity_type_to_check);
  foreach (array_keys($commerce_order_info['bundles']) as $bundle_name) {
    $instance = field_info_instance($entity_type_to_check, $form['field_name']['#value'], $bundle_name);
    if (commerce_marketplace_cart_field_instance_is_splitter($instance, 'order')) {
      unset($form['actions']['submit']);
      $form['description']['#markup'] = t('This field is configured as order splitter field on %bundle_name bundle of %entity_type entity type and thus cannot be deleted.', array(
        '%entity_type' => $entity_type_to_check,
        '%bundle_name' => $bundle_name,
      ));
    }
  }
}