forked from eileenmcnaughton/civicrm_entity
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcivicrm_entity.module
1059 lines (976 loc) · 33 KB
/
civicrm_entity.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
* Implement CiviCRM entities as a Drupal Entity.
*/
/**
* Implements hook_menu_later().
*
* Entity API creates all the fields page links but the basic 'manage' page is missing
* so we use the /fields page at that url
*/
function civicrm_entity_menu_alter(&$items) {
foreach (entity_get_info() as $entity_name => $entity_info) {
if (!empty($entity_info['module']) && $entity_info['module'] == 'civicrm_entity') {
foreach ($entity_info['bundles'] as $file_type => $bundle_info) {
if (isset($bundle_info['admin'])) {
// Get the base path and access.
$path = $bundle_info['admin']['path'];
$items[$path] = $items[$path . '/fields'];
$items[$path]['type'] = MENU_NORMAL_ITEM;
$items[$path]['title'] = $entity_info['label'];
$items[$path]['description'] = t('CiviCRM @entity entity', array('@entity' => $entity_name));
$items[$path . '/fields']['type'] = MENU_DEFAULT_LOCAL_TASK;
}
}
}
}
}
/**
* Implements hook_permission().
*/
function civicrm_entity_permission() {
return array(
'civicrm_entity.rules.administer' => array(
'title' => t('Administer CiviCRM rule configurations'),
'restrict access' => TRUE,
),
);
}
/**
* Entity access callback.
*
* @param $op
* @param $entity
* @param $account
* @param $entity_type
*
* @return bool
*/
function civicrm_entity_access($op, $entity, $account, $entity_type) {
if ($op == 'view' && $entity_type == 'civicrm_event') {
return user_access('view event info');
}
elseif ($op == 'view' && $entity_type == 'civicrm_participant') {
return user_access('view event participants');
}
else {
return user_access('administer CiviCRM');
}
}
/**
* Implements hook_views_data_alter().
*/
/*
function civicrm_entity_views_data_alter($data) { }
*/
/**
* Implements hook_schema_alter().
*
* Note we are just doing this in a very simple form relationship type
* which is not defined by views at this stage. We have the problem
* that the CiviCRM views integration uses the _data hook & would need
* to use _data_alter hook to be compatible with entity views
* integration
*
* @param $schema
*/
function civicrm_entity_schema_alter(&$schema) {
$schema_entities = _civicrm_entity_enabled_entities();;
foreach ($schema_entities as $drupal_entity => $civicrm_entity) {
$schema[$drupal_entity] = civicrm_entity_get_schema($drupal_entity);
}
}
/**
* Get schema for entities.
*
* This approach may not be required as using the schema_alter hook
* (as opposed to schema_hook) seems to get around a bunch of the
* reasons I used a separate schema.
*
* @param $table
*
* @return array
*/
function civicrm_entity_get_schema($table) {
if (!civicrm_initialize(TRUE)) {
return;
}
$schema = array();
$schema[$table] = array(
'description' => 'The base table for ' . $table,
'primary key' => array('id'),
'fields' => array(),
);
$civicrm_entity = substr($table, 8);
$fields = civicrm_api($civicrm_entity, 'getfields', array('version' => 3));
$fields = $fields['values'];
foreach ($fields as $fieldname => $field_spec) {
if (empty($field_spec['name'])) {
continue;
}
$unique_name = empty($field_spec['uniqueName']) ? $fieldname : $field_spec['uniqueName'];
$schema[$table]['fields'][$unique_name] = array(
'real_field' => $field_spec['name'],
'description' => _civicrm_entity_get_title($field_spec),
'unsigned' => TRUE,
'not null' => TRUE,
) + civicrm_entity_get_field_type($field_spec);
}
return empty($schema[$table]) ? array() : $schema[$table];
}
/**
* Please document this function.
*
* @param $field_spec
*
* @return array
*/
function civicrm_entity_get_field_type($field_spec) {
if ($field_spec['name'] == 'id') {
return array('type' => 'serial');
}
switch ($field_spec['type']) {
case CRM_Utils_Type::T_INT:
case CRM_Utils_Type::T_BOOLEAN:
return array('type' => 'integer');
case CRM_Utils_Type::T_MONEY:
case CRM_Utils_Type::T_FLOAT:
return array('type' => 'float');
case CRM_Utils_Type::T_TEXT:
case CRM_Utils_Type::T_STRING:
case CRM_Utils_Type::T_LONGTEXT:
case CRM_Utils_Type::T_CCNUM:
case CRM_Utils_Type::T_EMAIL:
case CRM_Utils_Type::T_URL:
return array('type' => 'text');
case CRM_Utils_Type::T_DATE:
case CRM_Utils_Type::T_TIME:
return array('type' => 'varchar', 'mysql_type' => 'datetime');
case CRM_Utils_Type::T_ENUM:
return array('type' => 'varchar', 'mysql_type' => 'enum');
case CRM_Utils_Type::T_BLOB:
case CRM_Utils_Type::T_MEDIUMBLOB:
return array('type' => 'blob');
case CRM_Utils_Type::T_TIMESTAMP:
return array('type' => 'varchar', 'mysql_type' => 'timestamp');
}
return array('type' => $field_spec['type']);
}
/**
* Here we declare selected CiviCRM entities to Drupal.
*
* This is necessary for entity module to pick them up.
*/
function civicrm_entity_entity_info() {
$entities = _civicrm_entity_enabled_entities();
foreach ($entities as $drupal_entity => $civicrm_entity) {
$info[$drupal_entity] = array(
'description' => $civicrm_entity,
'optional' => TRUE,
'label' => "CiviCRM " . ucwords($civicrm_entity),
'module' => 'civicrm_entity',
'controller class' => 'CivicrmEntityController',
'metadata controller class' => 'CivicrmEntityMetadataController',
'views controller class' => 'CiviCRMEntityDefaultViewsController',
'ui class' => 'RulesDataUIEntity',
'fieldable' => TRUE,
'extra fields controller class' => 'EntityDefaultExtraFieldsController',
'access callback' => 'civicrm_entity_access',
'admin ui' => array(
'path' => $drupal_entity,
'controller class' => 'CivicrmEntityUIController',
'file' => 'civicrm_entity_controller.inc',
),
'bundles' => array(
$drupal_entity => array(
'label' => t('CiviCRM @entity', array('@entity' => ucwords($civicrm_entity))),
'admin' => array(
'path' => 'admin/structure/types/manage/' . $drupal_entity,
'access arguments' => array('administer CiviCRM'),
),
),
),
'view modes' => array(
'full' => array(
'label' => t('Default'),
'custom settings' => TRUE,
),
),
'entity keys' => array(
'id' => 'id',
'label' => _civicrm_entity_labels($drupal_entity),
),
'base table' => $drupal_entity,
);
$label_callback = 'civicrm_entity_' . $drupal_entity . '_label_callback';
if (function_exists($label_callback)) {
$info[$drupal_entity]['label callback'] = $label_callback;
}
}
// OK - so we are not doing this for the ones declared in views
// until more testing has been done.
$info['civicrm_relationship_type']['views controller class'] = 'CiviCRMEntityDefaultViewsController';
return $info;
}
/**
* Here we declare Selected CiviCRM entities fields to Drupal.
*
* Some trickiness here as declaring the 'schema' via our special civi
* schema function seems to cause fields to be declared twice if we us
* property_info rather than property_info_alter.
*
* At the moment civicrm_relationship_type is the only entity being
* managed through 'our' schema.
*
* @param $info
*
* @return
*/
function civicrm_entity_entity_property_info_alter(&$info) {
if (!civicrm_initialize(TRUE)) {
return;
}
// We'll start with a few basic entities but we could get them the
// same way the API explorer does.
$entities = _civicrm_entity_enabled_entities();
foreach ($entities as $drupal_entity => $civicrm_entity) {
$info[$drupal_entity]['properties'] = _civicrm_entity_getproperties($civicrm_entity, 'property_info');
// $info[$drupal_entity]['bundles'] = array();
}
// This makes the drupal user available when chaining from a rule.
$info['civicrm_contact']['properties']['civicrm_user'] = array(
'label' => 'Drupal User',
'description' => 'Drupal User for contact',
'type' => 'user',
);
// Attach a CiviCRM Contact property to drupal users.
$info['user']['properties']['civicrm_contact'] = array(
'label' => 'CiviCRM Contact',
'description' => 'CiviCRM Contact for user',
'type' => 'civicrm_contact',
'field' => FALSE,
'translatable' => FALSE,
'getter callback' => 'civicrm_entity_user_contact_get',
);
return $info;
}
/**
* Whitelist of enabled entities. We don't have a compelling reason for not including all entities
* but some entities are fairly non-standard and of course the rule hook would instantiate rules
* more often if all were enabled.
*
* The whitelist approach is mostly out of caution
*
* @return array of enabled entities keyed by the drupal entity name
*/
function _civicrm_entity_enabled_entities() {
$whitelist = array(
'civicrm_address' => 'address',
'civicrm_event' => 'event',
'civicrm_contact' => 'contact',
'civicrm_contribution' => 'contribution',
'civicrm_participant' => 'participant',
'civicrm_relationship' => 'relationship',
'civicrm_relationship_type' => 'relationship_type',
'civicrm_activity' => 'activity',
'civicrm_entity_tag' => 'entity_tag',
'civicrm_membership' => 'membership',
'civicrm_membership_type' => 'membership_type',
'civicrm_group' => 'group',
'civicrm_grant' => 'grant',
'civicrm_tag' => 'tag',
);
//dirty check for whether financialType exists
if (!method_exists('CRM_Contribute_PseudoConstant', 'contributionType' )){
$whitelist['civicrm_financial_type'] = 'financial_type';
}
return $whitelist;
}
/**
* Please document this function.
*/
function _civicrm_entity_chained_fks() {
return array(
'CRM_Contact_DAO_Contact' => 'contact',
'CRM_Event_DAO_Event' => 'event',
);
}
/**
* Provide label (column) for each entity types.
*
* @TODO Use the CiviCRM 4.5 getlist function - possibly ported into this module to support 4.4
*
* @see http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_entity_info/7
*
* @param $entity
*
* @return
*/
function _civicrm_entity_labels($entity) {
$labels = array(
'civicrm_activity' => 'subject',
'civicrm_address' => 'address_name',
'civicrm_contact' => 'display_name',
'civicrm_contribution' => 'source',
'civicrm_event' => 'title',
'civicrm_participant' => 'source',
'civicrm_relationship' => 'description',
'civicrm_relationship_type' => 'description',
// OK, I'm just putting in something that won't error for now.
'civicrm_entity_tag' => 'tag_id',
'civicrm_financial_type' => 'description',
// Ditto.
'civicrm_membership' => 'id',
'civicrm_membership_type' => 'name',
'civicrm_group' => 'name',
'civicrm_grant' => 'id',
'civicrm_tag' => 'name',
);
return $labels[$entity];
}
function _civicrm_entity_get_title($field_specs, $entity_type='') {
if (!empty($entity_type)) {
$label_field = _civicrm_entity_labels($entity_type);
} else {
$label_field = 'title';
}
if (empty($field_specs[$label_field])) {
if (array_key_exists('label', $field_specs)) {
$label_field = 'label';
} else if (array_key_exists('name', $field_specs)) {
$label_field = 'name';
}
}
$title = empty($field_specs[$label_field]) ? 'Title not defined in schema': $field_specs[$label_field] ;
return $title;
}
/**
* Label callback for civicrm_contact entity type.
*
* drupal_alter('civicrm_entity_' . $entity, $, $alterable2, $context);
*
* @param $entity
* @param $entity_type
*
* @return null|string
*/
function civicrm_entity_civicrm_contact_label_callback($entity, $entity_type) {
$label = isset($entity->display_name) ? $entity->display_name : '';
// drupal_alter('civicrm_entity_contact_label', $label, $entity);
if (isset($entity->email) && !empty($entity->email)) {
$label = t('!label <!email>', array('!label' => $label, '!email' => $entity->email));
}
elseif (isset($entity->phone) && !empty($entity->phone)) {
$label = t('!label <!phone>', array('!label' => $label, '!phone' => $entity->phone));
}
return $label;
}
/**
* Calculate fields for entities
*
* @param $civicrm_entity
* @param string $context
*
* @return array
*/
function _civicrm_entity_getproperties($civicrm_entity, $context = '') {
$info = array();
if ($civicrm_entity == 'contact') {
$info['civi_user'] = array(
'label' => 'Drupal User',
'type' => 'user',
);
}
$fields = civicrm_api($civicrm_entity, 'getfields', array(
'version' => 3,
'action' => 'create',
));
foreach ($fields['values'] as $fieldname => $field_specs) {
// Type is empty for custom fields - we should sort that out but
// skipping for now we are only doing 'integers' at this stage.
$types = array(
1 => 'integer',
2 => 'text',
32 => 'text',
16 => 'integer',
);
if (!empty($field_specs['type']) && array_key_exists($field_specs['type'], $types)) {
$info[$fieldname] = array(
'label' => _civicrm_entity_get_title($field_specs),
'type' => $types[$field_specs['type']],
'sanitize' => 'check_plain',
'setter callback' => 'entity_property_verbatim_set',
);
if (!empty($field_specs['api.required'])) {
$info[$fieldname]['required'] = TRUE;
}
if ($field_specs['type'] == 16) {
$info[$fieldname]['size'] = 'tiny';
}
// This is a semi-reliable way of distinguishing 'real' fields
// from pseudo fields and custom fields and impacts on views
// (which is only implemented in a very minor way at this stage
// because it is 'blocked' by the default views install using
// hook_views_data rather than hook_views_data_alter.
if (!empty($field_specs['name'])) {
$info[$fieldname]['schema field'] = $field_specs['name'];
}
// We will add contact as a related entity for FK references to
// contact. This could be expanded to all FKs e.g event_id in
// Participant. Could load the event at the moment we are being
// cautious.
if (CRM_Utils_Array::value('FKClassName', $field_specs)) {
$fks = _civicrm_entity_chained_fks();
if (array_key_exists($field_specs['FKClassName'], $fks)) {
$fks_entity = $fks[$field_specs['FKClassName']];
$info[$fieldname . '_' . $fks_entity] = array(
'label' => _civicrm_entity_get_title($field_specs),
'type' => 'civicrm_' . $fks_entity,
'property_info' => array(
'field' => $fieldname,
'entity' => $fks_entity,
),
'getter callback' => 'civicrm_entity_metadata_civicrm_entity_get_properties',
);
}
}
// @TODO We are treating contact as the only possible entity
// which is not great - need to figure out better approach - can
// we have more than one? Define 'civicrm_entity'?
if ($fieldname == 'entity_id') {
$fks_entity = 'contact';
$info[$fieldname . '_' . $fks_entity] = array(
'label' => _civicrm_entity_get_title($field_specs),
'type' => 'civicrm_' . $fks_entity,
'property_info' => array(
'field' => $fieldname,
'entity' => $fks_entity,
),
'getter callback' => 'civicrm_entity_metadata_civicrm_entity_get_properties',
);
}
if (!empty($field_specs['options'])) {
// $info[$fieldname]['type'] = 'list<integer>';
$info[$fieldname]['options list'] = '_civicrm_entity_rules_attach_options';
$info[$fieldname]['options data'] = $field_specs['options'];
if ($context == 'property_info') {
$info[$fieldname]['property defaults']['options list'] = $field_specs['options'];
}
}
$info['type'] = array(
'label' => t('Type'),
'description' => t('Dummy field for bundle key'),
'type' => 'token',
'setter callback' => 'entity_property_verbatim_set',
'required' => FALSE,
'property defaults' => array('civicrm_' . strtolower($civicrm_entity)),
);
}
}
return $info;
}
function civicrm_entity_form($form, &$form_state, $entity, $op, $entity_type) {
// Add the field related form elements.
$form_state['entity'] = new CivicrmEntity((array) $entity, $entity_type);
field_attach_form($entity_type, $entity, $form, $form_state);
//not quite sure why these are not being added but ....
$wrapper = entity_metadata_wrapper($entity_type);
foreach ($wrapper as $name => $child) {
$info = $child->info();
$form[$name] = array(
'#type' => $info['type'],
'#title' => $info['label'],
'#description' => !empty($info['description']) ? $info['description'] : '',
);
}
$form['actions'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('form-actions')),
'#weight' => 400,
);
$form['#validate'] = array();
$form['#submit'] = array();
$form['#validate'][] = 'civicrm_entity_form_validate';
$form['#submit'][] = 'civicrm_entity_form_submit';
// We add the form's #submit array to this button along with the actual submit
// handler to preserve any submit handlers added by a form callback_wrapper.
$submit = array();
if (!empty($form['#submit'])) {
$submit += $form['#submit'];
}
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#submit' => $submit + array(),
);
return $form;
}
/**
* Form API validate callback for the entity form
*/
function civicrm_entity_form_validate(&$form, &$form_state) {
$entity = $form_state['entity'];
$entity_type = $form_state['entity_type'];
// Notify field widgets to validate their data.
field_attach_form_validate($entity_type, $entity, $form, $form_state);
}
/**
* Form API submit callback for the entity form.
*
*/
function civicrm_entity_form_submit(&$form, &$form_state) {
$entity_type = $form_state['entity_type'];
//@todo - what is the correct way to do this - taken from bangpound but then I had to do casting
$entity = entity_ui_controller($entity_type)->entityFormSubmitBuildEntity($form, $form_state);
$entity = new CivicrmEntity((array) $entity, $entity_type);
// Add in created and changed times.
if ($entity->is_new = isset($entity->is_new) ? $entity->is_new : 0){
$entity->created = time();
}
$entity->changed = time();
$entity->save();
$t_args = array(
'%label' => entity_label($entity_type, $entity),
);
drupal_set_message(t('Drupal fields on %label have been updated.', $t_args));
}
/**
* Implement getter callback.
*
* NB this is in a separate file called callbacks.inc in entity module
* - I couldn't see how it was loaded so maybe the name has some
* magic?
*
* @param $data
* @param $options
* @param $name
* @param $type
* @param $info
*
* @return object
*/
function civicrm_entity_metadata_civicrm_entity_get_properties($data, $options, $name, $type, $info) {
$entity = civicrm_api($info['property_info']['entity'], 'get', array(
'version' => 3,
'id' => $data->$info['property_info']['field'],
'sequential' => 1,
));
return (object) $entity['values'][0];
}
/**
* Condition Drupal User Account exists for contact.
*
* @param array $contact
* Contact array.
*
* @return object
* Drupal user object if success, FALSE on fail.
*/
function civicrm_entity_user_exists($contact) {
return civicrm_entity_action_load_user($contact);
}
/**
* Condition Drupal User Account can be created for contact (creates contact).
*
* @param array $contact
* contact array
*
* @return object
* Drupal user object if success, FALSE on Fail
*/
function civicrm_entity_user_creatable($contact) {
return civicrm_entity_action_create_user($contact, TRUE);
}
/**
* Condition Drupal User Account can be created or exists for contact.
*
* Ccreates contact if appropriate.
*
* @param array $contact
* contact array
*
* @return mixed
* Drupal user object if success, FALSE on fail.
*/
function civicrm_entity_user_exists_or_creatable($contact) {
return civicrm_entity_action_load_create_user($contact);
}
/**
* Given a contact object return the Drupal user.
*
* @param StdClass $entity
* Contact Std Object
*
* @return object
* Drupal user object.
*/
function civicrm_entity_action_load_user($entity) {
$domain_id = civicrm_api('domain', 'getvalue', array(
'version' => 3,
'return' => 'id',
'current_domain' => TRUE,
));
$params = array(
'version' => 3,
'contact_id' => $entity->id,
'return' => 'uf_id',
'domain_id' => $domain_id,
);
$contact = civicrm_api('uf_match', 'getsingle', $params);
if (empty($contact['is_error'])) {
return array('civicrm_user' => user_load($contact['uf_id']));
}
}
/**
* Given a contact object, load or create then return a drupal user.
*
* @param object $contact
* CiviCRM Contact Object
*
* @param $is_active
* @param bool $notify
* @param bool $signin
*
* @throws Exception
* @return object
* $user Drupal user object or FALSE.
*/
function civicrm_entity_action_create_user($contact, $is_active, $notify = FALSE, $signin = FALSE) {
if (!is_array($contact)) {
// Perhaps we should be accepting object rather than array here?
$contact = (array) $contact;
}
// We'll use the civicrm sync mechanism to see if Civi can match the
// contact to an existing user.
//
// Don't think this is a great approach but will use for now - could
// just create the user but no great support for that yet.
if (empty($contact['display_name']) || empty($contact['email'])) {
$contact = civicrm_api('contact', 'getsingle', array(
'version' => 3,
'id' => $contact['id'],
'sequential' => 1,
'return' => 'email,display_name',
));
}
if (!is_string($contact['email']) && isset($contact['email'][0]->email)) {
$contact['email'] = $contact['email'][0]->email;
}
// @TODO What happens if they don't have an email at this point?
// An email is a pre-requisite for a Drupal account, so the action
// fails if they don't have an email.
$params = array(
'name' => $contact['display_name'],
'mail' => $contact['email'],
'email' => $contact['email'],
'init' => $contact['email'],
);
// Check if the requested username is available.
$errors = array();
$config = CRM_Core_Config::singleton();
$config->userSystem->checkUserNameEmailExists($params, $errors);
if (!empty($errors)) {
foreach ($errors as $error) {
drupal_set_message(t($error), 'error');
}
return FALSE;
}
$params['cms_name'] = $params['name'] = $user['name'] = !empty($contact['display_name']) ? $contact['display_name'] : $params['mail'];
$params['cms_pass'] = $user['pass'] = substr(str_shuffle("abcefghijklmnopqrstuvwxyz"), 0, 8);
$params['status'] = $is_active;
if ($notify) {
$params['notify'] = TRUE;
}
$params['roles'] = array(
DRUPAL_AUTHENTICATED_RID => 'authenticated user',
);
// Set $config->inCiviCRM = TRUE to prevent creating a duplicate
// contact from user_save().
$config = CRM_Core_Config::singleton();
$config->inCiviCRM = TRUE;
$user_object = user_save('', $params);
$user_object->password = $user['pass'];
$config->inCiviCRM = FALSE;
// If selected in action configuration, notify the newly created
// user & send registration link. Does not contain password in D7.
if ($notify) {
drupal_mail('user', 'register_no_approval_required', $params['mail'], NULL, array('account' => $user_object), variable_get('site_mail', '[email protected]'));
}
// CiviCRM doesn't do this when created off CiviCRM Form.
//
// Note that we 'pretend' to be logging in to make it do a ufmatch
// on just the email.
CRM_Core_BAO_UFMatch::synchronizeUFMatch($user_object, $user_object->uid, $contact['email'], 'drupal', NULL, NULL, TRUE);
// If selected in action configuration, automatically sign in the
// current user.
if ($signin) {
global $user;
$user = user_load($user_object->uid);
watchdog('civicrm_entity', 'User %name logged in via CiviCRM Entity rule execution.', array('%name' => $user->name), WATCHDOG_INFO);
$form_values = array('uid' => $user->uid);
user_login_finalize($form_values);
}
return array('civicrm_user' => $user_object);
}
function civicrm_entity_query($type, $property, $value, $limit) {
$return = entity_load($type, $ids = FALSE, array($property => $value, 'options' => array('limit' => $limit)));
return array('entity_fetched' => array_values($return));
}
/**
* Info alteration callback for the entity query action.
* @todo this is copy of rules_action_entity_query_info_alter
*
* @param $element_info
* @param RulesAbstractPlugin $element
*/
function civicrm_entity_query_info_alter(&$element_info, RulesAbstractPlugin $element) {
$element->settings += array('type' => NULL, 'property' => NULL);
if ($element->settings['type']) {
$element_info['parameter']['property']['options list'] = 'rules_action_entity_query_property_options_list';
if ($element->settings['property']) {
$wrapper = rules_get_entity_metadata_wrapper_all_properties($element);
if (isset($wrapper->{$element->settings['property']}) && $property = $wrapper->{$element->settings['property']}) {
$element_info['parameter']['value']['type'] = $property->type();
$element_info['parameter']['value']['options list'] = $property->optionsList() ? 'rules_action_entity_query_value_options_list' : FALSE;
}
}
}
$element_info['provides']['entity_fetched']['type'] = 'list<' . $element->settings['type'] . '>';
}
/**
* Load or create user as appropriate.
*
* @param $entity
* @param int $is_active
* @param int $notify
*
* @return object
*/
function civicrm_entity_action_load_create_user($entity, $is_active = 0, $notify = 0) {
if ($user = civicrm_entity_action_load_user($entity)) {
if ($is_active && !$user['civicrm_user']->status) {
$user['civicrm_user']->status = $is_active;
$user['civicrm_user']->save;
}
return $user;
}
return civicrm_entity_action_create_user((array) $entity, $is_active, $notify);
}
/**
* @param $user
*
* @param null $email
*
* @return mixed
*/
function civicrm_entity_action_load_create_contact($user, $email = NULL) {
try {
return civicrm_entity_action_load_contact($user);
}
catch (CiviCRM_API3_Exception $e) {
$ufMatch = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $user->uid, ($email ? $email : $user->mail), 'Drupal', FALSE, 'Individual');
$entities = entity_load('civicrm_contact', $ufMatch->contact_id);
return array('civicrm_contact' => reset($entities));
}
}
/**
* @param $user
*
* @return mixed
* @throws CiviCRM_API3_Exception
*/
function civicrm_entity_action_load_contact($user) {
if (!civicrm_initialize()) {
return;
}
$contact_id = civicrm_api3('uf_match', 'getvalue', array(
'uf_id' => $user->uid,
'return' => 'contact_id',
'domain_id' => CRM_Core_Config::domainID()
));
$entities = entity_load('civicrm_contact', array($contact_id));
return array('civicrm_contact' => reset($entities));
}
/**
* Implement the post hook and fire the corresponding rules event.
*
* @param $op
* @param $object_name
* @param $object_id
* @param $object_ref
*/
function civicrm_entity_civicrm_post($op, $object_name, $object_id, &$object_ref) {
if (!module_exists('rules')) {
return;
}
$contact_types = array(
'Individual',
'Household',
'Organization',
);
if (in_array($object_name, $contact_types)) {
$object_name = 'Contact';
}
$valid_objects = _civicrm_entity_enabled_entities();
$entity_name = _civicrm_entity_get_entity_name_from_camel($object_name);
if (!in_array($entity_name, $valid_objects, TRUE)) {
return;
}
$event_name = NULL;
switch ($op) {
case 'create':
case 'edit':
case 'delete':
$event_name = 'civicrm_' . $entity_name . "_{$op}";
break;
default:
break;
}
if ($entity_name == 'entity_tag') {
// Argh entity tag is completely non-standard!!!
// @see CRM-11933
foreach ($object_ref[0] as $entity_tag) {
$object = new CRM_Core_BAO_EntityTag();
$object->entity_id = $entity_tag;
$object->entity_table = 'civicrm_contact';
$object->tag_id = $object_id;
if ($object->find(TRUE)) {
// This find is probably not necessary but until more testing
// on the tag create is done I will.
rules_invoke_event($event_name, $object);
}
}
}
else {
if ($event_name) {
rules_invoke_event($event_name, $object_ref);
}
}
}
/**
* Convert possibly camel name to underscore separated entity name.
*
* @see _civicrm_api_get_entity_name_from_camel()
*
* @TODO Why don't we just call the above function directly?
* Because the function is officially 'likely' to change as it is an internal api function and calling api functions directly is explicitly not supported
*
* @param string $entity
* Entity name in various formats e.g:
* Contribution => contribution,
* OptionValue => option_value,
* UFJoin => uf_join.
*
* @return string
* $entity entity name in underscore separated format
*/
function _civicrm_entity_get_entity_name_from_camel($entity) {
if ($entity == strtolower($entity)) {
return $entity;
}
else {
$entity = ltrim(strtolower(
str_replace('U_F', 'uf',
// That's CamelCase, beside an odd UFCamel that is expected as uf_camel
preg_replace('/(?=[A-Z])/', '_$0', $entity)
)), '_');
}
return $entity;
}
/**
* Load contact entity according to user id.
*
* @param $data
* @param array $options
* @param $name
* @param $type
* @param $info
*
* @return null
*/
function civicrm_entity_user_contact_get($data, array $options, $name, $type, $info) {
if (!module_exists('civicrm') || !function_exists('civicrm_initialize')) {
return;
}
if (!civicrm_initialize()) {
return;
}
$domain_id = civicrm_api('domain', 'getvalue', array(
'version' => 3,
'return' => 'id',
'current_domain' => TRUE,
));
$contact = civicrm_api('uf_match', 'getsingle', array(
'version' => 3,
'return' => 'contact_id',
'uf_id' => $data->uid,
'domain_id' => $domain_id,
));
if (!empty($contact['contact_id'])) {
$entity = entity_load('civicrm_contact', array($contact['contact_id']));
return $entity[$contact['contact_id']];
}
else {
return NULL;
}
}
/**
* Implements hook_rules_action_info_alter
* I can't seem to get my info_alter function called by hook so am doing this hacky intercept