forked from civicrm/civicrm-drupal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
civitest.module.sample
2041 lines (1783 loc) · 69.4 KB
/
civitest.module.sample
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
function civitest_civicrm_pre( $op, $objectName, $objectId, &$objectRef ) {
// Sample implementation of pre hook on line item row create. Available as of 4.1 beta3
if ( $objectName == 'LineItem' && $op == 'create' ) {
//if text type field and quantity is greater than 5, let's apply a discount
if ( $objectRef['html_type'] == 'Text' &&
$objectRef['qty'] > 5 ) {
//5% discount
$discount = 1 - 0.05;
$objectRef['unit_price'] = $objectRef['unit_price'] * $discount;
$objectRef['line_total'] = $objectRef['line_total'] * $discount;
//we would also need to update the total amount
//we know the table impacted with $objectRef['entity_table']
//and the contrib/event id with $objectRef['entity_id']
}
}
}
function civitest_civicrm_post( $op, $objectName, $objectId, &$objectRef ) {
// only interested in the profile object and create operation for now
if ( $objectName != 'Profile' || ( $op != 'create' && $op != 'edit' ) ) {
// send it to custom hook
return false;
}
// send an email to the user and cc administrator
// with a welcome message
civicrm_initialize( true );
require_once 'CRM/Utils/Mail.php';
$params = array( );
$fromName = 'My Org Administrator';
$fromEmail = '[email protected]';
$params['from'] = '"' . $fromName . '" <' . $fromEmail . '>';
$params['toEmail'] = $objectRef['email-1'];
$params['toName'] = "{$objectRef['first_name']} {$objectRef['last_name']}";
$params['subject'] = "Thank you for supporting My Org";
$params['cc'] = '[email protected]';
$objectValues = print_r( $objectRef, true );
$params['text'] = "
Dear $toName:
Thank you for your show of support. The details u signed up with are:
$objectValues
Regards
My Org Team
";
CRM_Utils_Mail::send( $params );
}
function civitest_civicrm_custom( $op, $groupID, $entityID, &$params ) {
if ( $op != 'create' && $op != 'edit' ) {
return;
}
// this is the custom group i am interested in updating when the row is updated
if ( $groupID != 1 ) {
return;
}
$tableName = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_CustomGroup',
$groupID,
'table_name' );
$sql = "
UPDATE $tableName
SET random_code_data_3 = 23
WHERE entity_id = $entityID
";
CRM_Core_DAO::executeQuery( $sql,
CRM_Core_DAO::$_nullArray );
}
/**
* Get the permissioned where clause for the user
*
* @param int $type the type of permission needed
* @param array $tables (reference ) add the tables that are needed for the select clause
* @param array $whereTables (reference ) add the tables that are needed for the where clause
* @param int $contactID the contactID for whom the check is made
*
* @return string the group where clause for this user
* @access public
*/
function civitest_civicrm_aclWhereClause( $type, &$tables, &$whereTables, &$contactID, &$where ) {
if ( ! $contactID ) {
return;
}
$permissionTable = 'civicrm_value_permission';
$regionTable = 'civicrm_value_region';
$fields = array( 'electorate' => 'Integer',
'province' => 'Integer',
'branch' => 'Integer' );
// get all the values from the permission table for this contact
$keys = implode( ', ', array_keys( $fields ) );
$sql = "
SELECT $keys
FROM {$permissionTable}
WHERE entity_id = $contactID
";
$dao = CRM_Core_DAO::executeQuery( $sql );
if ( ! $dao->fetch( ) ) {
return;
}
$tables[$regionTable] = $whereTables[$regionTable] =
"LEFT JOIN {$regionTable} regionTable ON contact_a.id = regionTable.entity_id";
$clauses = array( );
foreach( $fields as $field => $fieldType ) {
if ( ! empty( $dao->$field ) ) {
if ( strpos( CRM_Core_DAO::VALUE_SEPARATOR, $dao->$field ) !== false ) {
$value = substr( $dao->$field, 1, -1 );
$values = explode( CRM_Core_DAO::VALUE_SEPARATOR, $value );
foreach ( $values as $v ) {
$clauses[] = "regionTable.{$field} = $v";
}
} else {
if ( $fieldType == 'String' ) {
$clauses[] = "regionTable.{$field} = '{$dao->$field}'";
} else {
$clauses[] = "regionTable.{$field} = {$dao->$field}";
}
}
}
}
if ( ! empty( $clauses ) ) {
if ( ! empty( $where ) ) {
$where .= ' AND (' . implode( ' OR ', $clauses ) . ')';
} else {
$where .= ' (' . implode( ' OR ', $clauses ) . ')';
}
}
}
function civitest_civicrm_dashboard( $contactID, &$contentPlacement ) {
// REPLACE Activity Listing with custom content
$contentPlacement = 3;
return array( 'Custom Content' => "Here is some custom content: $contactID",
'Custom Table' => "
<table>
<tr><th>Contact Name</th><th>Date</th></tr>
<tr><td>Foo</td><td>Bar</td></tr>
<tr><td>Goo</td><td>Tar</td></tr>
</table>
",
);
}
function civitest_civicrm_buildAmount(
$pageType,
&$form,
&$amount
) {
//sample to modify priceset fee
$priceSetId = $form->get( 'priceSetId' );
if ( !empty( $priceSetId ) ) {
$feeBlock =& $amount;
// if you use this in sample data, u'll see changes in
// contrib page id = 1, event page id = 1 and
// contrib page id = 2 (which is a membership page
if (!is_array( $feeBlock ) || empty( $feeBlock ) ) {
return;
}
//in case of event we get eventId,
//so lets apply hook for eventId = 1
if ( $pageType == 'event' && $form->_eventId != 1 ) {
return;
}
//in case of contrbution
//for online case we get page id so we could apply for specific
if ( $pageType == 'contribution' ) {
if ( !in_array(
get_class( $form ),
array( 'CRM_Contribute_Form_Contribution', 'CRM_Contribute_Form_Contribution_Main')
)
) {
return;
}
}
if ($pageType == 'membership') {
// give a discount of 20% to everyone
foreach ( $feeBlock as &$fee ) {
if ( !is_array( $fee['options'] ) ) {
continue;
}
foreach ( $fee['options'] as &$option ) {
//for sample lets modify first option from all fields.
$option['amount'] = $option['amount'] * 0.8;
$option['label'] .= ' - ' . ts( 'Get a 20% discount since you know this hook' );
}
}
} else {
// unconditionally modify the first option to be a $100 fee
// to show our power!
foreach ( $feeBlock as &$fee ) {
if ( !is_array( $fee['options'] ) ) {
continue;
}
foreach ( $fee['options'] as &$option ) {
// lets modify first option from all fields.
$option['amount'] = 100;
$option['label'] = ts( 'Power of hooks' );
break;
}
}
}
}
}
function civitest_civicrm_aclGroup( $type, $contactID, $tableName, &$allGroups, &$currentGroups ) {
// only process saved search
if ( $tableName != 'civicrm_saved_search' ) {
return;
}
hrd_initialize( );
$currentGroups = $allGroups;
if ( ! CRM_Core_Permission::check( 'access secure contacts' ) ) {
unset( $currentGroups[HRD_SECURE_GROUP_ID] );
}
$currentGroups = array_keys( $currentGroups );
}
function civitest_civicrm_tabs( &$tabs, $contactID ) {
// unset the contribition tab
unset( $tabs[1] );
// lets rename the contribution tab with a differnt name and put it last
// this is just a demo, in the real world, you would create a url which would
// return an html snippet etc
$url = CRM_Utils_System::url( 'civicrm/contact/view/contribution',
"reset=1&snippet=1&force=1&cid=$contactID" );
$tabs[] = array( 'id' => 'mySupercoolTab',
'url' => $url,
'title' => 'Contribution Tab Renamed',
'weight' => 300 );
}
function civitest_civicrm_enableDisable( $recordBAO, $recordID, $isActive ) {
// create an activity for enable/disable relationship type
if ( $recordBAO == 'CRM_Contact_BAO_RelationshipType' ) {
$session = CRM_Core_Session::singleton( );
$uid = $session->get('userID');
if( $uid ) {
$params = array( 'activity_type_id' => 1,
'source_contact_id' => $uid,
'status_id' => 2,
'activity_date_time' => date('YmdHis')
);
if( $isActive ) {
$params['subject'] = ts('Enabled relationship type.');
} else {
$params['subject'] = ts('Disabled relationship type.');
}
civicrm_api('activity', 'create', $params);
}
}
}
function civitest_civicrm_tokens( &$tokens ) {
$tokens['contribution'] =
array(
'contribution.amount' => 'Amount of contribution',
'contribution.date' => 'Date of contribution',
'contribution.total_last_year' => 'Total amount contributed last year',
'contribution.date_of_first' => 'Date of first contribution',
'contribution.largest_this_year' => 'Largest this Year Contribution Amount',
'contribution.date_of_largest_this_year' => 'Largest this Year Contribution Date',
'contribution.average' => 'Average Contribution Amount',
'contribution.largest' => 'Largest Contribution' );
}
function civitest_civicrm_tokenValues( &$values,
&$contactIDs,
$dontCare,
$tokens,
$context ) {
if ( is_array( $contactIDs ) ) {
$contactIDString = implode( ',', array_values( $contactIDs ) );
}
$query = "
SELECT sum( total_amount ) as total_amount,
contact_id,
max( receive_date ) as receive_date
FROM civicrm_contribution
WHERE contact_id IN ( $contactIDString )
AND is_test = 0
GROUP BY contact_id
";
$dao = CRM_Core_DAO::executeQuery( $query );
while ( $dao->fetch( ) ) {
if ( ! array_key_exists( $dao->contact_id, $values ) ) {
$values[$dao->contact_id] = array( );
}
$values[$dao->contact_id]['contribution.amount'] = $dao->total_amount;
$values[$dao->contact_id]['contribution.date' ] = $dao->receive_date;
}
}
// example of token that does not depend on contactID
// and using the new format
function civitest_civicrm_tokenValues( &$values,
&$contactIDs,
$dontCare,
$tokens,
$context ) {
if ( isset( $tokens['views'] ) ) {
static $_cache = null;
if ( ! $_cache ) {
$_cache = array( );
foreach( $tokens['views'] as $token ) {
$_cache[$token] = CALL_YOUR_OWN_FUNCTION_TO_RENDER_THIS_VIEW( $token );
}
}
foreach( $contactIDs as $cid ) {
foreach( $tokens['views'] as $token ) {
$values[$cid]["views.{$token}"] = $_cache[$token];
}
}
}
}
function civitest_civicrm_pageRun( &$page ) {
// You can assign variables to the template using:
// $page->assign( 'varName', $varValue );
// in your template, {$varName} will output the contents of $varValue
// you should customize your template if doing so
$page->assign( 'varName', 'This is a variable assigned by the hook' );
}
/*
* The hook_nodeapi implementation to set the node title to that of event title.
* Could also be used set the title to anything we want.
*
*/
function civicrm_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
if ($op == 'load' && $node->type == 'event') {
$node->title = civicrm_cck_event_field_values('title', $node->field_title[0]['value']);
}
}
/*
* The function to pull out event data from civicrm for cck fields related to event.
*
*/
function civicrm_cck_event_field_values($field, $index = null) {
static $eventInfo;
if ( ! $eventInfo ) {
if ( ! civicrm_initialize( ) ) {
return;
}
$params = array( );
$eventInfo = civicrm_api('event', 'get', $params );
}
if ( strpos($_GET['q'], 'edit') ||
strpos($_GET['q'], 'add') ) {
$isAppend = true;
}
if ( isset( $index ) ) {
$isAppend = false;
}
$retArray = array( );
switch( $field ) {
case 'when':
foreach ( $eventInfo as $info ) {
$str = "{$info['start_date']} > through > {$info['end_date']}";
$retArray[] = $isAppend ? ("{$info['title']}:: " . $str) : $str;
}
break;
case 'location':
foreach ( $eventInfo as $info ) {
$params = array( 'entity_id' => $info['id'],'entity_table' => 'civicrm_event');
require_once 'CRM/Core/BAO/Location.php';
$values['location'] = CRM_Core_BAO_Location::getValues( $params, true );
$str = $values['location']['address'][1]['display'];
$retArray[] = $isAppend ? ("{$info['title']}:: " . $str) : $str;
}
break;
case 'register_link':
foreach ( $eventInfo as $info ) {
$str = '<a href="' .
CRM_Utils_System::url( 'civicrm/event/register',
"id={$info['id']}&reset=1", true ) .
'">» Register Now</a>';
$retArray[] = $isAppend ? ("{$info['title']}:: " . $str) : $str;
}
break;
case 'feeblock' :
require_once 'CRM/Core/BAO/Discount.php';
require_once 'CRM/Core/OptionGroup.php';
foreach ( $eventInfo as $info ) {
$discountId = CRM_Core_BAO_Discount::findSet( $info['id'], 'civicrm_event' );
if ( $discountId ) {
CRM_Core_OptionGroup::getAssoc( CRM_Core_DAO::getFieldValue( 'CRM_Order_DAO_Discount',
$discountId, 'option_group_id' ),
$feeBlock, true, 'id' );
} else {
CRM_Core_OptionGroup::getAssoc( "civicrm_event.amount.{$info['id']}", $feeBlock, true );
}
$feeLabels = array();
foreach ( $feeBlock as $block ) {
$feeLabels[] = $block['label'] . " $" . $block['value'];
}
$str = ' ' . implode($feeLabels, '<br/> ');
$retArray[] = $isAppend ? ("{$info['title']}:: " . $str) : $str;
}
break;
default:
foreach ( $eventInfo as $info ) {
if ( isset($info[$field]) ) {
$str = $info[$field];
$retArray[] = $isAppend ? ("{$info['title']}:: " . $str) : $str;
}
}
}
return empty($retArray) ? array() : isset($index) ? $retArray[$index] : $retArray;
}
function civitest_civicrm_customFieldOptions( $fieldID, &$options ) {
if ( $fieldID == 1 ) {
$options['Rocks'] = t( 'Hooks Rock' );
unset( $options['Edu'] );
} else if ( $fieldID == 2 ) {
$options['H'] = t(' Hook me' );
unset( $options['S'] );
}
}
/**
* The hook_searchTasks is implemented to display the list of actions allowed after doing a search
* More examples are shown to call this hook
*
* @param string $$objectType specifies the component
* @param array $tasks the list of actions
*
* @access public
*/
function civitest_civicrm_searchTasks( $objectType, &$tasks ) {
if ( $objectType == 'contact' ) {
$tasks[100] = array( 'title' => t( 'Contact Hook Action Task' ),
'class' => 'CRM_Contact_Form_Task_HookSample',
'result' => false );
}
if ( $objectType == 'contribution' ) {
$tasks[102] = array( 'title' => t( 'Contribution Hook Action Task' ),
'class' => 'CRM_Contribute_Form_Task_SearchTaskHookSample',
'result' => false );
}
if ( $objectType == 'membership' ) {
$tasks[103] = array( 'title' => t( 'Member Hook Action Task' ),
'class' => 'CRM_Member_Form_Task_SearchTaskHookSample',
'result' => false );
}
if ( $objectType == 'pledge' ) {
$tasks[104] = array( 'title' => t( 'Pledge Hook Action Task' ),
'class' => 'CRM_Pledge_Form_Task_SearchTaskHookSample',
'result' => false );
}
if ( $objectType == 'event' ) {
$tasks[105] = array( 'title' => t( 'Event Hook Action Task' ),
'class' => 'CRM_Event_Form_Task_SearchTaskHookSample',
'result' => false );
}
if ( $objectType == 'case' ) {
$tasks[106] = array( 'title' => t( 'Case Hook Action Task' ),
'class' => 'CRM_Case_Form_Task_SearchTaskHookSample',
'result' => false );
}
if ( $objectType == 'grant' ) {
$tasks[107] = array( 'title' => t( 'Grant Hook Action Task' ),
'class' => 'CRM_Grant_Form_Task_SearchTaskHookSample',
'result' => false );
}
if ( $objectType == 'activity' ) {
$tasks[108] = array( 'title' => t( 'Activity Hook Action Task' ),
'class' => 'CRM_Activity_Form_Task_SearchTaskHookSample',
'result' => false );
}
}
function civitest_civicrm_validateForm( $formName, &$fields, &$files, &$form, &$errors ) {
// sample implementation
if ( $formName == 'CRM_Contact_Form_Contact' ) {
// ensure that external identifier is present and valid
$externalID = CRM_Utils_Array::value( 'external_identifier', $fields );
if ( ! $externalID ) {
$errors['external_identifier'] = ts( 'External Identifier is a required field' );
} else {
require_once "CRM/Utils/Rule.php";
if ( ! CRM_Utils_Rule::integer( $externalID ) ) {
$errors['external_identifier'] = ts( 'External Identifier is not an integer' );
}
}
}
return;
}
function civitest_civicrm_pageRun( &$page ) {
// we are only interested in profile pages with gid = 1 and have a valid contact id
if ( $page->getVar( '_name' ) != 'CRM_Profile_Page_View' ||
$page->getVar( '_gid' ) != 1 ||
! CRM_Utils_Rule::positiveInteger( $page->getVar( '_id' ) ) ) {
return;
}
// get all relationships of
require_once 'CRM/Contact/BAO/Relationship.php';
$relationships = CRM_Contact_BAO_Relationship::getRelationship( $page->getVar( '_id' ) );
// if you want to filter and display only certain relationship, you can do so before assigninng to
// smarty. Do a CRM_Core_Error::debug( $relationships ) to see all the fields
$page->assign( 'relationships', $relationships );
// in addition to this, you also need to customize: templates/CRM/Profile/Page/View.tpl
// check: http://wiki.civicrm.org/confluence/display/CRMDOC/Customize+Built-in,+Profile,+Contribution+and+Event+Registration+Screens
// some sample tpl code is included here, modify as needed
/**
{if $relationships}
<table>
<tr>
<th>Name</th>
<th>Relation</th>
<th>Country</th>
</tr>
{foreach from=$relationships item=relation}
<tr>
<td>{$relation.name}</td>
<td>{$relation.relation}</td>
<td>{$relation.country}</td>
</tr>
{/foreach}
</table>
{/if}
**/
}
function civitest_civicrm_eventDiscount( &$form, &$params ) {
require_once 'CRM/Utils/Money.php';
// we only are interested in event id 1
if ( $form->getVar( '_eventId' ) != 1 ) {
return;
}
$numParticipants = 0;
foreach ( $params as $key => $value ) {
if ( isset( $params[$key]['amount'] ) &&
$params[$key]['amount'] > 0 ) {
$numParticipants++;
}
}
// Set discount rule (Example: if more than 1 participant, 5% additional discount per paying participant, upto a max of 50%)
if ( $numParticipants > 1 ) {
$discountPercentage = $numParticipants * 5;
if ( $discountPercentage > 50 ) {
$discountPercentage = 50;
}
$totalDiscount = 0;
foreach ( $params as $key => $value ) {
if ( CRM_Utils_Array::value( 'amount', $params[$key] ) > 0 ) {
$discount = round( ( $params[$key]['amount'] * $discountPercentage ) / 100.0 );
$totalDiscount += $discount;
$params[$key]['discountAmount'] = $discount;
$discountDisplay = CRM_Utils_Money::format( $discount, null, null );
// Set discount info added to participant.fee_level and contribution.amount_level
$params[$key]['discountMessage'] = " (discount: $discountDisplay)";
}
}
$totalDiscountDisplay = CRM_Utils_Money::format( $totalDiscount, null, null );
// Set the message to show on confirmation page, thank-you page and receipt
$params[0]['discount'] =
array( 'message' => "a discount of $totalDiscountDisplay has been applied to the total amount",
'applied' => true );
}
}
/**
* buildForm hook sample
*
* we want the custom date to be today's date. custom_3 is marriage date
* in the sample data
*/
function civitest_civicrm_buildForm( $formName, &$form ) {
if ( $formName == 'CRM_Contact_Form_Contact' ) {
$defaults['custom_3_-1'] = date('m/d/Y');
$form->setDefaults( $defaults );
}
// enable tracking feature
if ( ( $formName == 'CRM_Contribute_Form_Contribution_Main' ||
$formName == 'CRM_Contribute_Form_Contribution_Confirm' ||
$formName == 'CRM_Contribute_Form_Contribution_ThankYou' ) &&
$form->getVar( '_id' ) == 1 ) { // use CONTRIBUTION PAGE ID here
// use the custom field ID and custom field label here
$trackingFields = array( 'custom_4' => 'Campaign',
'custom_5' => 'Appeal',
'custom_6' => 'Fund' );
$form->assign( 'trackingFields', $trackingFields );
}
}
/**
* buildForm hook that would allow contacts to renew only existing memberships.
*/
function civitest_civicrm_buildForm( $formName, &$form ) {
if ( $formName == 'CRM_Contribute_Form_Contribution_Main' ) {
if ( is_array( $form->_membershipBlock ) ) {
//get logged in contact
$session = CRM_Core_Session::singleton();
$contactID = $session->get('userID');
//check for existing membership
$query = "SELECT membership_type_id
FROM civicrm_membership
WHERE membership_type_id IN ( {$form->_membershipBlock['membership_types']} )
AND civicrm_membership.contact_id = {$contactID}";
$dao = CRM_Core_DAO::executeQuery( $query );
$membershipTypeID = null;
while ( $dao->fetch( ) ) {
$membershipTypeID = $dao->membership_type_id;
}
if ( $membershipTypeID ) {
$form->freeze(array('selectMembership'));
$defaults['selectMembership'] = $membershipTypeID;
$form->setDefaults( $defaults );
}
}
}
}
function civitest_civicrm_mailingGroups( &$form, &$groups, &$mailings ) {
unset( $groups[4] );
$mailings[1] = 'This Mailing does not exist';
}
function _civitest_discountHelper( $eventID, $discountCode ) {
$sql = "
SELECT v.id as id, v.value as value, v.weight as weight
FROM civicrm_option_value v,
civicrm_option_group g
WHERE v.option_group_id = g.id
AND v.name = %1
AND g.name = %2
";
$params = array( 1 => array( $discountCode , 'String' ),
2 => array( "event_discount_{$eventID}", 'String' ) );
$dao = CRM_Core_DAO::executeQuery( $sql, $params );
if ( $dao->fetch( ) ) {
// ensure discountPercent is a valid numeric number <= 100
if ( $dao->value &&
is_numeric( $dao->value ) &&
$dao->value >= 0 &&
$dao->value <= 100 &&
is_numeric( $dao->weight ) ) {
return array( $dao->id, $dao->value, $dao->weight );
}
}
return array( null, null, null );
}
function civitest_civicrm_buildForm( $formName, &$form ) {
if ( $formName == 'CRM_Event_Form_Registration_Register' &&
$form->getVar( '_eventId' ) == 3 ) {
$form->addElement( 'text', 'discountCode', ts( 'Discount Code' ) );
// in template use
// {$form.discountCode.label} {$form.discountCode.html}
// also assign to template
$template = CRM_Core_Smarty::singleton( );
$beginHookFormElements = $template->get_template_vars( 'beginHookFormElements' );
if ( ! $beginHookFormElements ) {
$beginHookFormElements = array( );
}
$beginHookFormElements[] = 'discountCode';
$form->assign( 'beginHookFormElements', $beginHookFormElements );
$discountCode = CRM_Utils_Request::retrieve( 'discountCode', 'String', $form, false, null, $_REQUEST );
if ( $discountCode ) {
$defaults = array( 'discountCode' => $discountCode );
$form->setDefaults( $defaults );
}
}
}
/*
* Give random discounts for event signup.
*
* Warning : while implementing this hook, another post process hook
* : also need implementing to make sure code is only used for
* : the number of times that's allowed to.
*/
function civitest_civicrm_buildAmount( $pageType,
&$form,
&$amount ) {
$eventID = $form->getVar( '_eventId' );
if ( $pageType != 'event' ||
$eventID != 3 ) {
return;
}
$discountCode = CRM_Utils_Request::retrieve( 'discountCode', 'String', $form, false, null, $_REQUEST );
if ( ! $discountCode ) {
return;
}
list( $discountID, $discountPercent, $discountNumber ) = _civitest_discountHelper( $eventID, $discountCode );
if ( $discountNumber <= 0 ) {
// no more discount left
return;
}
foreach ( $amount as $amountId => $amountInfo ) {
$amount[$amountId]['value'] = $amount[$amountId]['value'] -
ceil($amount[$amountId]['value'] * $discountPercent / 100);
$amount[$amountId]['label'] = $amount[$amountId]['label'] .
"\t - with {$discountPercent}% discount";
}
}
/*
* The hook updates the random code used with event signup.
*/
function civitest_civicrm_postProcess( $class, &$form ) {
$eventID = $form->getVar( '_eventId' );
if ( ! is_a($form, 'CRM_Event_Form_Registration_Confirm') ||
$eventID != 3 ) {
return;
}
$discountCode = CRM_Utils_Request::retrieve( 'discountCode', 'String', $form, false, null, $_REQUEST );
if ( ! $discountCode ) {
return;
}
list( $discountID, $discountPercent, $discountNumber ) = _civitest_discountHelper( $eventID, $discountCode );
if ( ! $discountID ||
$discountNumber <= 0 ||
$discountNumber == 123456789 ) {
return;
}
$query = "
UPDATE civicrm_option_value v
SET v.weight = v.weight - 1
WHERE v.id = %1
AND v.weight > 0
";
$params = array( 1 => array( $discountID, 'Integer' ) );
CRM_Core_DAO::executeQuery( $query, $params );
}
/**
* Sample hook to add more actions for Create New
*/
function civitest_civicrm_links( $op, $objectName, $objectId, &$links, &$mask ) {
if ( $op == 'create.new.shorcuts' ) {
// add link to create new profile
$links[] = array( 'url' => '/civicrm/admin/uf/group?action=add&reset=1',
'title' => ts('New Profile'),
'ref' => 'new-profile');
}
}
function civitest_civicrm_membershipTypeValues( &$form, &$membershipTypeValues ) {
$membershipTypeValues[1]['name'] = 'General (50% discount)';
$membershipTypeValues[1]['minimum_fee'] = '50.00';
$membershipTypeValues[2]['name'] = 'Student (50% discount)';
$membershipTypeValues[2]['minimum_fee'] = '25.00';
}
function civitest_civicrm_summary( $contactID, &$content, &$contentPlacement ) {
// REPLACE default Contact Summary with your customized content
$contentPlacement = 3;
$content = "
<table>
<tr><th>Hook Data</th></tr>
<tr><td>Data 1</td></tr>
<tr><td>Data 2</td></tr>
</table>
";
}
function civitest_civicrm_contactListQuery( &$query, $name, $context, $id ) {
// This example limits contacts in my contact reference field lookup to a specific group
// Connect the hook to your Contact Reference custom field using the field ID (field id is 4 in this case)
if ( $context == 'customfield' &&
$id == 4 ) {
// Now construct the query to select only the contacts we want
// The query must return two columns - contact sort_name, and contact id
$query = "
SELECT c.sort_name, c.id
FROM civicrm_contact c, civicrm_group_contact cg
WHERE c.sort_name LIKE '$name%'
AND cg.group_id IN ( 4 )
AND cg.contact_id = c.id
AND cg.status = 'Added'
ORDER BY c.sort_name ";
}
}
/**
* Hook implementation for altering payment parameters before talking to a payment processor back end.
*
* @param string $paymentObj
* instance of payment class of the payment processor invoked (e.g., 'CRM_Core_Payment_Dummy')
* @param array &$rawParams
* array of params as passed to to the processor
* @params array &$cookedParams
* params after the processor code has translated them into its own key/value pairs
* @return void
*/
function civitest_civicrm_alterPaymentProcessorParams($paymentObj,
&$rawParams,
&$cookedParams) {
if ($paymentObj->class_name == Payment_Dummy ) {
$employer = empty($rawParams['custom_1']) ? '' : $rawParams['custom_1'];
$occupation = empty($rawParams['custom_2']) ? '' : $rawParams['custom_2'];
$cookedParams['custom'] = "$employer|$occupation";
}
else if ($paymentObj->class_name == Payment_AuthorizeNet) {
//Actual translation for one application:
//Employer > Ship to Country (x_ship_to_country)
//Occupation > Company (x_company)
//Solicitor > Ship-to First Name (x_ship_to_first_name)
//Event > Ship-to Last Name (x_ship_to_last_name)
//Other > Ship-to Company (x_ship_to_company)
$cookedParams['x_ship_to_country'] = $rawParams['custom_1'];
$cookedParams['x_company'] = $rawParams['custom_2'];
$cookedParams['x_ship_to_last_name'] = $rawParams['accountingCode']; //for now
$country_info = da_core_fetch_country_data_by_crm_id($rawParams['country-1']);
$cookedParams['x_ship_to_company'] = $country_info['iso_code'];
}
elseif ($paymentObj->billing_mode == 2) {
// Express Checkout
$cookedParams['desc'] = $rawParams['eventName'];
$cookedParams['custom'] = $rawParams['eventId'];
}
}
function civitest_civicrm_customFieldOptions($fieldID, &$options, $detailedFormat = false ) {
if ( $fieldID == 1 || $fieldID == 2 ) {
if ( $detailedFormat ) {
$options['fake_id_1'] = array( 'id' => 'fake_id_1',
'value' => 'XXX',
'label' => 'XXX' );
$options['fake_id_2'] = array( 'id' => 'fake_id_2',
'value' => 'YYY',
'label' => 'YYY' );
} else {
$options['XXX'] = 'XXX';
$options['YYY'] = 'YYY';
}
}
}
function civitest_civicrm_config( &$config ) {
$civitestRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
// fix php include path
$include_path = $civitestRoot . PATH_SEPARATOR . get_include_path( );
set_include_path( $include_path );
// fix template path
$templateDir = $civitestRoot . 'templates' . DIRECTORY_SEPARATOR;
$template = CRM_Core_Smarty::singleton( );
array_unshift( $template->template_dir, $templateDir );
}
function custom_ts( $string, $params = array( ) ) {
$string = str_replace( 'Participant', 'Delegate', $string );
static $i18n = null;
if ( ! $i18n ) {
$i18n = CRM_Core_I18n::singleton();
}
return $i18n->crm_translate( $string, $params );
}
/**
* You want a contribution page with exactly one amount and you
* you want to set all the values fixed and not give the user
* any choice
*/
function civitest_civicrm_buildForm( $formName, &$form ) {
if ( $formName == 'CRM_Contribute_Form_Contribution_Main' &&
$form->getVar( '_id' ) == 1 ) {
// 358 is the "option value id" of the only value in the amount table,
// you can get this id, by doing a view source on the HTML
$defaults = array( 'amount' => 358,
'is_recur' => 1,
'frequency_interval' => 1,
'frequency_unit' => 'month',
'installments' => 12 );
$form->setDefaults( $defaults );
// also freeze these elements
$elementNames = array_keys( $defaults );
foreach ( $elementNames as $element ) {
$elm =& $form->getElement( $element );
$elm->freeze( );
}
}
}
function civitest_civicrm_caseSummary($caseID) {
/* Quick way to test what some results look like.
return array('some_unique_id' => array( 'label' => ts('Some Date'),
'value' => '2009-02-11',
),
'some_other_id' => array( 'label' => ts('Some String'),
'value' => ts('Coconuts'),
),
);
*/
/*
For styling put this in css/extras.css:
#caseSummary {display: table;}
#modrtw {display: table-row; border: 1px solid #999999; width: 200px;}
#mcstat {display: table-row; border: 1px solid #999999; border-left: 0; width: 200px;}
#caseSummary label {display: table-cell;}
#caseSummary div {display: table-cell; padding-left: 5px; padding-right: 5px;}
*/
// More realistic example, but will return nothing unless you have these activities in your database.
// TIP: Put these queries into methods in a custom class. You will likely want to re-use them elsewhere, such as in a CiviReport.
// This query finds the earliest date of return to modified duties in a workplace disability case.
$params = array( 1 => array( $caseID, 'Integer' ) );
$sql = "SELECT min(activity_date_time) as mindate
FROM civicrm_activity a
INNER JOIN civicrm_case_activity ca on a.id=ca.activity_id
LEFT OUTER JOIN civicrm_option_group og on og.name='activity_type'
LEFT OUTER JOIN civicrm_option_value ov on
(og.id=ov.option_group_id AND ov.name='Return to modified duties')
WHERE ca.case_id=%1
AND ov.value=a.activity_type_id
LIMIT 1";
$modrtw = CRM_Core_DAO::singleValueQuery( $sql, $params );
// This query returns the current status of the medical consent as determined by
// the presence or absence of related activities.