forked from xurizaemon/civicrm_entity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcivicrm_entity.module
907 lines (841 loc) · 29.1 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
<?php
/**
* @file
* Implement CiviCRM entities as a Drupal Entity
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2012
*/
/**
* Implements hook_menu().
*
* It may be that civicrm drupals entities could be 'fieldable' -
* refer to drupal fields with the linkages held in drupal? This code
* is not doing much right now.
*/
function civicrm_entity_menu(){
$items['admin/structure/types/manage/civicrm_relationship_type'] = array(
'title' => 'CiviCRM Relationship Type Settings',
'description' => 'Configure the settings for the CiviCRM Relationship Type.',
'page callback' => 'drupal_get_form',
'page arguments' => array('civicrm_entity_settings'),
'access arguments' => array('administer CiviCRM'),
'weight' => -10,
);
$items['admin/civicrm_entity/settings'] = array(
'title' => 'Settings',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
}
/**
* Implements hook_enable().
*
* Set weight higher than CiviCRM.
*
* @TODO Actually check what CiviCRM's weight should be.
*
* @TODO Shouldn't this be in .install?
*/
function civicrm_entity_enable() {
db_query("UPDATE {system} SET weight = 110 WHERE name = 'civicrm_entity'");
}
/**
* 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.
*/
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) {
// here for debug really
}
/**
* 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
*/
function civicrm_entity_schema_alter(&$schema) {
$schemaEntities = _civicrm_entity_enabled_entities();;
foreach ($schemaEntities as $drupal_entity => $civicrm_entity){
$schema[$drupal_entity] = civicrm_entity_get_schema($drupal_entity);
}
/* $schema['civicrm_relationship_type'] = array(
'description' => 'The base table for CiviCRM Relationship Types',
'fields' => array(
'id' => array(
'description' => 'The Relationship type id.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'label_a_b' => array(
'description' => 'Relationship Label',
'type' => 'text',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => '',
),
'is_active' => array(
'description' => 'Relationship Type is enabled',
'type' => 'integer',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
),
'primary key' => array('id'),
);
*/
}
/*
* 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
*/
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' => empty($field_spec['title'])? 'No description in CiviCRM Schema for field': $field_spec['title'],
'unsigned' => TRUE,
'not null' => TRUE,
) + civicrm_entity_get_field_type($field_spec);
}
return empty($schema[$table]) ? array() : $schema[$table];
}
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 $drupal_entity",
'module' => 'civicrm_entity',
'controller class' => 'CivicrmEntityController',
'metadata controller class' => 'CivicrmEntityMetadataController',
'views controller class' => 'CiviCRMEntityDefaultViewsController',
'fieldable' => FALSE,
'access callback' => 'civicrm_entity_access',
'bundles' => array(
$drupal_entity => array(
'label' => t("CiviCRM $drupal_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' => FALSE
)
),
'entity keys' => array(
'id' => 'id',
'label' => _civicrm_entity_labels($drupal_entity),
)
)
;
$info[$drupal_entity]['base table'] = $drupal_entity;
}
//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
*/
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;
}
function _civicrm_entity_enabled_entities() {
return array(
'civicrm_event' => 'event',
'civicrm_contact' => 'contact',
'civicrm_participant' => 'participant',
'civicrm_relationship' => 'relationship',
'civicrm_relationship_type' => 'relationship_type',
'civicrm_activity' => 'activity',
'civicrm_entity_tag' => 'entity_tag',
'civicrm_membership' => 'membership',
'civicrm_group' => 'group',
);
}
function _civicrm_entity_chained_fks(){
return array(
'CRM_Contact_DAO_Contact' => 'contact',
'CRM_Event_DAO_Event' => 'event',
);
}
/*
* OK v basic version of what the 'label' should be for each of these tables
* we can & probably should create a call back function
*
* http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_entity_info/7
*/
function _civicrm_entity_labels($entity) {
$labels = array(
'civicrm_event' => 'title',
'civicrm_contact' => 'display_name',
'civicrm_participant' => 'source',
'civicrm_relationship' => 'description',
'civicrm_relationship_type' => 'description',
'civicrm_activity' => 'subject',
'civicrm_entity_tag' => 'tag_id', // OK I'm just putting in something that won't error for now
'civicrm_membership' => 'id', // ditto
'civicrm_group'=> 'name',
);
return $labels[$entity];
}
/*
* Calculate fields for entities
*/
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' => empty($field_specs['title'])? 'title not defined see CRM-11547': $field_specs['title'],
'type' => $types[$field_specs['type']],
'sanitize' => 'check_plain'
);
if($field_specs['type'] == 16){
$info[$fieldname]['size'] = 'tiny';
}
/* this is a semi-reliable way of distinguishing 'real' fields from pseudofields
// 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)){
$fksEntity = $fks[$field_specs['FKClassName']];
$info[$fieldname . '_' . $fksEntity] = array(
'label' => empty($field_specs['title']) ? 'Title not defined in schema' : $field_specs['title'],
'type' => 'civicrm_' . $fksEntity,
'property_info' => array(
'field' => $fieldname,
'entity' => $fksEntity
),
'getter callback' => 'civicrm_entity_metadata_civicrm_entity_get_properties'
);
}
}
// 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'){
$fksEntity = 'contact';
$info[$fieldname . '_' . $fksEntity] = array(
'label' => empty($field_specs['title']) ? 'Title not defined in schema' : $field_specs['title'],
'type' => 'civicrm_' . $fksEntity,
'property_info' => array(
'field' => $fieldname,
'entity' => $fksEntity
),
'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'];
}
}
}
}
return $info;
}
/**
* 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?
*/
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 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 $info contact array
* @return object user object if success. False on Fail
*/
function civicrm_entity_user_creatable($contact){
return civicrm_entity_action_create_user($contact);
}
/**
* Condition Drupal User Account can be created or exists for contact
* (creates contact if appropriate).
*
* @param array $contact contact array
* @return object 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 StdClass $user Drupal User Object
*/
function civicrm_entity_action_load_user($entity) {
$contact = civicrm_api('uf_match', 'getsingle', array(
'version' => 3,
'contact_id' => $entity->id,
'return' => 'uf_id',
'domain_id' => civicrm_api('domain', 'getvalue', array('version' => 3, 'return' => 'id', 'current_domain' => TRUE)),
));
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 $entity CiviCRM Contact Object
* @return object|boolean $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.
//
// @TODO What happens if they don't have an email?
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'
));
}
$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
);
}
/**
* Load or create user as appropriate
*/
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);
}
/**
* Implement the post hook and fire the corresponding rules event
*/
function civicrm_entity_civicrm_post($op, $object_name, $object_id, &$object_ref) {
if (! module_exists('rules')) {
return;
}
if (in_array($object_name, array(
'Individual',
'Household',
'Organization'
))) {
$object_name = 'Contact';
}
$valid_objects = _civicrm_entity_enabled_entities();
$entityName = _civicrm_entity_get_entity_name_from_camel($object_name);
if (! in_array($entityName, $valid_objects, TRUE)) {
return;
}
$event_name = NULL;
switch ($op) {
case 'create':
case 'edit':
case 'delete':
$event_name = 'civicrm_' . $entityName . "_{$op}";
break;
default:
break;
}
if($entityName == 'entity_tag'){
//argh entity tag is completely non-standard!!! CRM-11933 logged
foreach ($object_ref[0] as $entityTag){
$object = new CRM_Core_BAO_EntityTag();
$object->entity_id = $entityTag;
$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
*
*(copied from api - may change in api
* @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;
}
/**
*
* @author eileen
*
*/
class civicrmEntity extends Entity {
protected function defaultLabel() {
return $this->title;
}
protected function defaultUri() {
return array(
'path' => 'task/' . $this->identifier()
);
}
}
/**
*
*/
class CivicrmEntityController extends EntityAPIController {
/**
* Implements DrupalEntityControllerInterface::load().
*/
public function load($ids = array(), $conditions = array()) {
$entities = array();
if(!civicrm_initialize(TRUE)){
return;
}
// not sure about revisioning out at this stage - I don't know if it could have any later use
// Revisions are not statically cached, and require a different query to
// other conditions, so separate the revision id into its own variable.
if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
$revision_id = $conditions[$this->revisionKey];
unset($conditions[$this->revisionKey]);
}
else {
$revision_id = FALSE;
}
/*
* this seems 'harmless' - but not necessarily relevant?
* ie. deals with caching on the drupal side
*/
// Create a new variable which is either a prepared version of the $ids
// array for later comparison with the entity cache, or FALSE if no $ids
// were passed. The $ids array is reduced as items are loaded from cache,
// and we need to know if it's empty for this reason to avoid querying the
// database when all requested entities are loaded from cache.
$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
// Try to load entities from the static cache, if the entity type supports
// static caching.
if ($this->cache && !$revision_id) {
$entities += $this->cacheGet($ids, $conditions);
// If any entities were loaded, remove them from the ids still to load.
if ($passed_ids) {
$ids = array_keys(array_diff_key($passed_ids, $entities));
}
}
/*
* OK - here is where we will actually 'Do' something that is Civi-Specific
* In drupal land $ids = FALSE would load all - let's only do specifix
*/
// Load any remaining entities from the database. This is the case if $ids
// is set to FALSE (so we load all entities), if there are any ids left to
// load, if loading a revision, or if $conditions was passed without $ids.
if ($ids === FALSE || $ids || $revision_id || ($conditions && !$passed_ids)) {
// Build the query.
foreach ($ids as $id){
$civiEntity = civicrm_api($this->entityInfo['description'], 'getsingle', array('version' => 3, 'id' => $id));
// @todo improve this casting
$queried_entities[$civiEntity['id']] = new civicrmEntity($civiEntity , 'civicrm_event');
}
}
// Pass all entities loaded from the database through $this->attachLoad(),
// which attaches fields (if supported by the entity type) and calls the
// entity type specific load callback, for example hook_node_load().
if (!empty($queried_entities)) {
$this->attachLoad($queried_entities, $revision_id);
$entities += $queried_entities;
}
if ($this->cache) {
// Add entities to the cache if we are not loading a revision.
if (!empty($queried_entities) && !$revision_id) {
$this->cacheSet($queried_entities);
}
}
// Ensure that the returned array is ordered the same as the original
// $ids array if this was passed in and remove any invalid ids.
if ($passed_ids) {
// Remove any invalid ids from the array.
$passed_ids = array_intersect_key($passed_ids, $entities);
foreach ($entities as $entity) {
$passed_ids[$entity->{$this->idKey}] = $entity;
}
$entities = $passed_ids;
}
return $entities;
}
/**
* Implements EntityAPIControllerInterface.
*
* @param $transaction
* Optionally a DatabaseTransaction object to use. Allows overrides to pass
* in their transaction object.
*/
public function save($entity, DatabaseTransaction $transaction = NULL) {
print_r($entity);
print_r($transaction);
print_r($this);
$params = (array) $entity;
unset($params['is_new']);
$params['version'] = 3;
$params['sequential'] = 1;
try {
$entity->is_new = ! empty($entity->is_new) || empty($entity->{$this->idKey});
//@todo should we call this hook when drupal saves (as opposed to Civi?) ditto insert, update
$this->invoke('presave', $entity);
if ($entity->is_new) {
$result = civicrm_api(substr($this->entityType, 8), 'create', $params);
//$this->invoke('insert', $entity); (see above)
}
else {
$result = civicrm_api(substr($this->entityType, 8), 'update', $params);
//$this->invoke('update', $entity); (see above)
}
unset($entity->is_new);
unset($entity->is_new_revision);
unset($entity->original);
if (! civicrm_error($result)) {
return (object) $result['values'][0];
}
throw new Exception($result['error_message']);
} catch (Exception $e) {
watchdog_exception($this->entityType, $e);
throw $e;
}
}
}
/**
*
*/
class CiviCRMEntityDefaultViewsController extends EntityDefaultViewsController {
/**
* Defines the result for hook_views_data().
*/
public function views_data() {
$data = array();
$this->relationships = array();
if (!empty($this->info['base table'])) {
$table = $this->info['base table'];
// Define the base group of this table. Fields that don't
// have a group defined will go into this field by default.
$data[$table]['table']['group'] = drupal_ucfirst($this->info['label']);
$data[$table]['table']['entity type'] = $this->type;
// If the plural label isn't available, use the regular label.
$label = isset($this->info['plural label']) ? $this->info['plural label'] : $this->info['label'];
$data[$table]['table']['base'] = array(
'field' => $this->info['entity keys']['id'],
'title' => drupal_ucfirst($label),
'help' => isset($this->info['description']) ? $this->info['description'] : '',
);
$data[$table]['table']['entity type'] = $this->type;
$data[$table] += $this->schema_fields();
// Add in any reverse-relationships which have been determined.
$data += $this->relationships;
}
return $data;
}
/**
* Try to come up with some views fields with the help of the schema and
* the entity property information.
*/
protected function schema_fields() {
// We are not using the 'normal' schema function here due to
// the problems discussed in the readme.
if(empty($this->info['base table'])){
return array();
}
$schema = civicrm_entity_get_schema($this->info['base table']);
$properties = entity_get_property_info($this->type) + array('properties' => array());
$data = array();
// we will take out the reliance on other schema related checks
// here ideally we would 'read' getfields output to determine if
// we are looking at a DB field or a custom / pseudofield
foreach ($properties['properties'] as $name => $property_info) {
if (!empty($property_info['schema field']) && !empty($schema['fields']) && isset($schema['fields'][$property_info['schema field']])) {
if ($views_info = $this->map_from_schema_info($name, $schema['fields'][$property_info['schema field']], $property_info)) {
$data[$name] = $views_info;
}
}
}
return $data;
}
}
/**
* Load contact entity according to user id.
*/
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;
$contact = civicrm_api('uf_match', 'getsingle', array(
'version' => 3,
'return' => 'contact_id',
'uf_id' => $data->uid,
'domain_id' => civicrm_api('domain', 'get', array('version' => 3, 'return' => 'id', 'current_domain' => TRUE)),
));
if(!empty($contact['contact_id'])){
$entity = entity_load('civicrm_contact', array($contact['contact_id']));
return $entity[$contact['contact_id']];
}
else {
return NULL;
}
}