INFRA-132 - CRM/Event - Misc
[civicrm-core.git] / CRM / Event / BAO / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26
27 */
28
29 /**
30 *
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2014
34 * $Id$
35 *
36 */
37 class CRM_Event_BAO_Participant extends CRM_Event_DAO_Participant {
38
39 /**
40 * Static field for all the participant information that we can potentially import
41 *
42 * @var array
43 * @static
44 */
45 static $_importableFields = NULL;
46
47 /**
48 * Static field for all the participant information that we can potentially export
49 *
50 * @var array
51 * @static
52 */
53 static $_exportableFields = NULL;
54
55 /**
56 * Static array for valid status transitions rules
57 *
58 * @var array
59 * @static
60 */
61 static $_statusTransitionsRules = array(
62 'Pending from pay later' => array('Registered', 'Cancelled'),
63 'Pending from incomplete transaction' => array('Registered', 'Cancelled'),
64 'On waitlist' => array('Cancelled', 'Pending from waitlist'),
65 'Pending from waitlist' => array('Registered', 'Cancelled'),
66 'Awaiting approval' => array('Cancelled', 'Pending from approval'),
67 'Pending from approval' => array('Registered', 'Cancelled'),
68 );
69
70 /**
71 *
72 */
73 public function __construct() {
74 parent::__construct();
75 }
76
77 /**
78 * Takes an associative array and creates a participant object
79 *
80 * the function extract all the params it needs to initialize the create a
81 * participant object. the params array could contain additional unused name/value
82 * pairs
83 *
84 * @param array $params
85 * (reference ) an assoc array of name/value pairs.
86 *
87 * @return CRM_Event_BAO_Participant object
88 * @static
89 */
90 public static function &add(&$params) {
91
92 if (!empty($params['id'])) {
93 CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params);
94 }
95 else {
96 CRM_Utils_Hook::pre('create', 'Participant', NULL, $params);
97 }
98
99 // converting dates to mysql format
100 if (!empty($params['register_date'])) {
101 $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']);
102 }
103
104 if (!empty($params['participant_fee_amount'])) {
105 $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']);
106 }
107
108 if (!empty($params['fee_amount'])) {
109 $params['fee_amount'] = CRM_Utils_Rule::cleanMoney($params['fee_amount']);
110 }
111
112 // ensure that role ids are encoded as a string
113 if (isset($params['role_id']) && is_array($params['role_id'])) {
114 $params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
115 }
116
117 $participantBAO = new CRM_Event_BAO_Participant;
118 if (!empty($params['id'])) {
119 $participantBAO->id = CRM_Utils_Array::value('id', $params);
120 $participantBAO->find(TRUE);
121 $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date);
122 }
123
124 $participantBAO->copyValues($params);
125
126 //CRM-6910
127 //1. If currency present, it should be valid one.
128 //2. We should have currency when amount is not null.
129 $currency = $participantBAO->fee_currency;
130 if ($currency ||
131 !CRM_Utils_System::isNull($participantBAO->fee_amount)
132 ) {
133 if (!CRM_Utils_Rule::currencyCode($currency)) {
134 $config = CRM_Core_Config::singleton();
135 $currency = $config->defaultCurrency;
136 }
137 }
138 $participantBAO->fee_currency = $currency;
139
140 $participantBAO->save();
141
142 $session = CRM_Core_Session::singleton();
143
144 // reset the group contact cache for this group
145 CRM_Contact_BAO_GroupContactCache::remove();
146
147 if (!empty($params['id'])) {
148 CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO);
149 }
150 else {
151 CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO);
152 }
153
154 return $participantBAO;
155 }
156
157 /**
158 * Given the list of params in the params array, fetch the object
159 * and store the values in the values array
160 *
161 * @param array $params
162 * Input parameters to find object.
163 * @param array $values
164 * Output values of the object.
165 *
166 * @param $ids
167 *
168 * @return CRM_Event_BAO_Participant|null the found object or null
169 * @static
170 */
171 public static function getValues(&$params, &$values, &$ids) {
172 if (empty($params)) {
173 return NULL;
174 }
175 $participant = new CRM_Event_BAO_Participant();
176 $participant->copyValues($params);
177 $participant->find();
178 $participants = array();
179 while ($participant->fetch()) {
180 $ids['participant'] = $participant->id;
181 CRM_Core_DAO::storeValues($participant, $values[$participant->id]);
182 $participants[$participant->id] = $participant;
183 }
184 return $participants;
185 }
186
187 /**
188 * Takes an associative array and creates a participant object
189 *
190 * @param array $params
191 * (reference ) an assoc array of name/value pairs.
192 *
193 * @return CRM_Event_BAO_Participant object
194 * @static
195 */
196 public static function create(&$params) {
197
198 $transaction = new CRM_Core_Transaction();
199 $status = NULL;
200
201 if (!empty($params['id'])) {
202 $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
203 }
204
205 $participant = self::add($params);
206
207 if (is_a($participant, 'CRM_Core_Error')) {
208 $transaction->rollback();
209 return $participant;
210 }
211
212 if ((!CRM_Utils_Array::value('id', $params)) ||
213 (isset($params['status_id']) && $params['status_id'] != $status)
214 ) {
215 CRM_Activity_BAO_Activity::addActivity($participant);
216 }
217
218 //CRM-5403
219 //for update mode
220 if (self::isPrimaryParticipant($participant->id) && $status) {
221 self::updateParticipantStatus($participant->id, $status, $participant->status_id);
222 }
223
224 $session = CRM_Core_Session::singleton();
225 $id = $session->get('userID');
226 if (!$id) {
227 $id = CRM_Utils_Array::value('contact_id', $params);
228 }
229
230 // add custom field values
231 if (!empty($params['custom']) &&
232 is_array($params['custom'])
233 ) {
234 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
235 }
236
237 //process note, CRM-7634
238 $noteId = NULL;
239 if (!empty($params['id'])) {
240 $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
241 $noteId = key($note);
242 }
243 $noteValue = NULL;
244 $hasNoteField = FALSE;
245 foreach (array(
246 'note',
247 'participant_note'
248 ) as $noteFld) {
249 if (array_key_exists($noteFld, $params)) {
250 $noteValue = $params[$noteFld];
251 $hasNoteField = TRUE;
252 break;
253 }
254 }
255 if ($noteId || $noteValue) {
256 if ($noteValue) {
257 $noteParams = array(
258 'entity_table' => 'civicrm_participant',
259 'note' => $noteValue,
260 'entity_id' => $participant->id,
261 'contact_id' => $id,
262 'modified_date' => date('Ymd'),
263 );
264 $noteIDs = array();
265 if ($noteId) {
266 $noteIDs['id'] = $noteId;
267 }
268 CRM_Core_BAO_Note::add($noteParams, $noteIDs);
269 }
270 elseif ($noteId && $hasNoteField) {
271 CRM_Core_BAO_Note::del($noteId, FALSE);
272 }
273 }
274
275 // Log the information on successful add/edit of Participant data.
276 $logParams = array(
277 'entity_table' => 'civicrm_participant',
278 'entity_id' => $participant->id,
279 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id),
280 'modified_id' => $id,
281 'modified_date' => date('Ymd'),
282 );
283
284 CRM_Core_BAO_Log::add($logParams);
285
286 $params['participant_id'] = $participant->id;
287
288 $transaction->commit();
289
290 // do not add to recent items for import, CRM-4399
291 if (empty($params['skipRecentView'])) {
292
293 $url = CRM_Utils_System::url('civicrm/contact/view/participant',
294 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
295 );
296
297 $recentOther = array();
298 if (CRM_Core_Permission::check('edit event participants')) {
299 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
300 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
301 );
302 }
303 if (CRM_Core_Permission::check('delete in CiviEvent')) {
304 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
305 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
306 );
307 }
308
309 $participantRoles = CRM_Event_PseudoConstant::participantRole();
310
311 if ($participant->role_id) {
312 $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
313
314 foreach ($role as & $roleValue) {
315 if (isset($roleValue)) {
316 $roleValue = $participantRoles[$roleValue];
317 }
318 }
319 $roles = implode(', ', $role);
320 }
321
322 $roleString = empty($roles) ? '' : $roles;
323 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
324 $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roleString . ' - ' . $eventTitle . ')';
325
326 // add the recently created Participant
327 CRM_Utils_Recent::add($title,
328 $url,
329 $participant->id,
330 'Participant',
331 $participant->contact_id,
332 NULL,
333 $recentOther
334 );
335 }
336
337 return $participant;
338 }
339
340 /**
341 * Check whether the event is full for participation and return as
342 * per requirements.
343 *
344 * @param int $eventId
345 * Event id.
346 * @param bool $returnEmptySeats
347 * Are we require number if empty seats.
348 * @param bool $includeWaitingList
349 * Consider waiting list in event full.
350 * calculation or not. (it is for cron job purpose)
351 *
352 * @param bool $returnWaitingCount
353 * @param bool $considerTestParticipant
354 *
355 * @return bool|int|null|string 1. false => If event having some empty spaces.@static
356 */
357 static function eventFull(
358 $eventId,
359 $returnEmptySeats = FALSE,
360 $includeWaitingList = TRUE,
361 $returnWaitingCount = FALSE,
362 $considerTestParticipant = FALSE
363 ) {
364 $result = NULL;
365 if (!$eventId) {
366 return $result;
367 }
368
369 // consider event is full when.
370 // 1. (count(is_counted) >= event_size) or
371 // 2. (count(participants-with-status-on-waitlist) > 0)
372 // It might be case there are some empty spaces and still event
373 // is full, as waitlist might represent group require spaces > empty.
374
375 $participantRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
376 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
377 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
378 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
379
380 //when we do require only waiting count don't consider counted.
381 if (!$returnWaitingCount && !empty($countedStatuses)) {
382 $allStatusIds = array_keys($countedStatuses);
383 }
384
385 $where = array(' event.id = %1 ');
386 if (!$considerTestParticipant) {
387 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
388 }
389 if (!empty($participantRoles)) {
390 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
391 }
392
393 $eventParams = array(1 => array($eventId, 'Positive'));
394
395 //in case any waiting, straight forward event is full.
396 if ($includeWaitingList && $onWaitlistStatusId) {
397
398 //build the where clause.
399 $whereClause = ' WHERE ' . implode(' AND ', $where);
400 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
401 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
402
403 $query = "
404 SELECT participant.id id,
405 event.event_full_text as event_full_text
406 FROM civicrm_participant participant
407 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
408 {$whereClause}";
409
410 $eventFullText = ts('This event is full.');
411 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
412 while ($participants->fetch()) {
413 //oops here event is full and we don't want waiting count.
414 if ($returnWaitingCount) {
415 return CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
416 }
417 else {
418 return ($participants->event_full_text) ? $participants->event_full_text : $eventFullText;
419 }
420 }
421 }
422
423 //consider only counted participants.
424 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
425 $whereClause = ' WHERE ' . implode(' AND ', $where);
426 $eventSeatsWhere = implode(' AND ', $where);
427
428 $query = "
429 SELECT participant.id id,
430 event.event_full_text as event_full_text,
431 event.max_participants as max_participants
432 FROM civicrm_participant participant
433 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
434 {$whereClause}";
435
436 $eventMaxSeats = NULL;
437 $eventFullText = ts('This event is full.');
438 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
439 while ($participants->fetch()) {
440 if ($participants->event_full_text) {
441 $eventFullText = $participants->event_full_text;
442 }
443 $eventMaxSeats = $participants->max_participants;
444 //don't have limit for event seats.
445 if ($participants->max_participants == NULL) {
446 return $result;
447 }
448 }
449
450 //get the total event seats occupied by these participants.
451 $eventRegisteredSeats = CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
452
453 if ($eventRegisteredSeats) {
454 if ($eventRegisteredSeats >= $eventMaxSeats) {
455 $result = $eventFullText;
456 }
457 elseif ($returnEmptySeats) {
458 $result = $eventMaxSeats - $eventRegisteredSeats;
459 }
460 return $result;
461 }
462 else {
463 $query = '
464 SELECT event.event_full_text,
465 event.max_participants
466 FROM civicrm_event event
467 WHERE event.id = %1';
468 $event = CRM_Core_DAO::executeQuery($query, $eventParams);
469 while ($event->fetch()) {
470 $eventFullText = $event->event_full_text;
471 $eventMaxSeats = $event->max_participants;
472 }
473 }
474
475 // no limit for registration.
476 if ($eventMaxSeats == NULL) {
477 return $result;
478 }
479 if ($eventMaxSeats) {
480 return ($returnEmptySeats) ? (int) $eventMaxSeats : FALSE;
481 }
482
483 return $eventFullText;
484 }
485
486 /**
487 * Return the array of all price set field options,
488 * with total participant count that field going to carry.
489 *
490 * @param int $eventId
491 * Event id.
492 * @param array $skipParticipantIds
493 * An array of participant ids those we should skip.
494 * @param bool $considerCounted
495 * @param bool $considerWaiting
496 * @param bool $considerTestParticipants
497 *
498 * @return array $optionsCount an array of each option id and total count
499 * @static
500 */
501 static function priceSetOptionsCount(
502 $eventId,
503 $skipParticipantIds = array(),
504 $considerCounted = TRUE,
505 $considerWaiting = TRUE,
506 $considerTestParticipants = FALSE
507 ) {
508 $optionsCount = array();
509 if (!$eventId) {
510 return $optionsCount;
511 }
512
513 $allStatusIds = array();
514 if ($considerCounted) {
515 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
516 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
517 }
518 if ($considerWaiting) {
519 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
520 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
521 }
522 $statusIdClause = NULL;
523 if (!empty($allStatusIds)) {
524 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
525 }
526
527 $isTestClause = NULL;
528 if (!$considerTestParticipants) {
529 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
530 }
531
532 $skipParticipantClause = NULL;
533 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
534 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
535 }
536
537 $sql = "
538 SELECT line.id as lineId,
539 line.entity_id as entity_id,
540 line.qty,
541 value.id as valueId,
542 value.count,
543 field.html_type
544 FROM civicrm_line_item line
545 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
546 AND participant.id = line.entity_id )
547 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
548 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
549 WHERE participant.event_id = %1
550 {$statusIdClause}
551 {$isTestClause}
552 {$skipParticipantClause}";
553
554 $lineItem = CRM_Core_DAO::executeQuery($sql, array(1 => array($eventId, 'Positive')));
555 while ($lineItem->fetch()) {
556 $count = $lineItem->count;
557 if (!$count) {
558 $count = 1;
559 }
560 if ($lineItem->html_type == 'Text') {
561 $count *= $lineItem->qty;
562 }
563 $optionsCount[$lineItem->valueId] = $count + CRM_Utils_Array::value($lineItem->valueId, $optionsCount, 0);
564 }
565
566 return $optionsCount;
567 }
568
569 /**
570 * Get the empty spaces for event those we can allocate
571 * to pending participant to become confirm.
572 *
573 * @param int $eventId
574 * Event id.
575 *
576 * @return int $spaces Number of Empty Seats/null.
577 * @static
578 */
579 public static function pendingToConfirmSpaces($eventId) {
580 $emptySeats = 0;
581 if (!$eventId) {
582 return $emptySeats;
583 }
584
585 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
586 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
587
588 $query = "
589 SELECT count(participant.id) as registered,
590 civicrm_event.max_participants
591 FROM civicrm_participant participant, civicrm_event
592 WHERE participant.event_id = {$eventId}
593 AND civicrm_event.id = participant.event_id
594 AND participant.status_id IN {$statusIds}
595 GROUP BY participant.event_id
596 ";
597 $dao = CRM_Core_DAO::executeQuery($query);
598 if ($dao->fetch()) {
599
600 //unlimited space.
601 if ($dao->max_participants == NULL || $dao->max_participants <= 0) {
602 return NULL;
603 }
604
605 //no space.
606 if ($dao->registered >= $dao->max_participants) {
607 return $emptySeats;
608 }
609
610 //difference.
611 return $dao->max_participants - $dao->registered;
612 }
613
614 //space in case no registeration yet.
615 return CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
616 }
617
618 /**
619 * Combine all the importable fields from the lower levels object
620 *
621 * @param string $contactType
622 * @param bool $status
623 * @param bool $onlyParticipant
624 *
625 * @return array array of importable Fields
626 * @static
627 */
628 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
629 if (!self::$_importableFields) {
630 if (!$onlyParticipant) {
631 if (!$status) {
632 $fields = array('' => array('title' => ts('- do not import -')));
633 }
634 else {
635 $fields = array('' => array('title' => ts('- Participant Fields -')));
636 }
637 }
638 else {
639 $fields = array();
640 }
641
642 $tmpFields = CRM_Event_DAO_Participant::import();
643
644 $note = array(
645 'participant_note' => array(
646 'title' => ts('Participant Note'),
647 'name' => 'participant_note',
648 'headerPattern' => '/(participant.)?note$/i',
649 )
650 );
651
652 // Split status and status id into 2 fields
653 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
654 $participantStatus = array(
655 'participant_status' => array(
656 'title' => ts('Participant Status'),
657 'name' => 'participant_status',
658 'data_type' => CRM_Utils_Type::T_STRING,
659 )
660 );
661 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
662
663 // Split role and role id into 2 fields
664 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
665 $participantRole = array(
666 'participant_role' => array(
667 'title' => ts('Participant Role'),
668 'name' => 'participant_role',
669 'data_type' => CRM_Utils_Type::T_STRING,
670 )
671 );
672 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
673
674 $eventType = array(
675 'event_type' => array(
676 'title' => ts('Event Type'),
677 'name' => 'event_type',
678 'data_type' => CRM_Utils_Type::T_STRING,
679 )
680 );
681
682 $tmpContactField = $contactFields = array();
683 $contactFields = array();
684 if (!$onlyParticipant) {
685 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
686
687 // Using new Dedupe rule.
688 $ruleParams = array(
689 'contact_type' => $contactType,
690 'used' => 'Unsupervised',
691 );
692 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
693
694 if (is_array($fieldsArray)) {
695 foreach ($fieldsArray as $value) {
696 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
697 $value,
698 'id',
699 'column_name'
700 );
701 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
702 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
703 if (!$status) {
704 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
705 }
706 else {
707 $title = $tmpContactField[trim($value)]['title'];
708 }
709
710 $tmpContactField[trim($value)]['title'] = $title;
711 }
712 }
713 }
714 $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
715 if ($extIdentifier) {
716 $tmpContactField['external_identifier'] = $extIdentifier;
717 $tmpContactField['external_identifier']['title'] =
718 CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
719 }
720 $tmpFields['participant_contact_id']['title'] =
721 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
722
723 $fields = array_merge($fields, $tmpContactField);
724 $fields = array_merge($fields, $tmpFields);
725 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
726 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant'));
727
728 self::$_importableFields = $fields;
729 }
730
731 return self::$_importableFields;
732 }
733
734 /**
735 * Combine all the exportable fields from the lower levels object
736 *
737 * @return array array of exportable Fields
738 * @static
739 */
740 public static function &exportableFields() {
741 if (!self::$_exportableFields) {
742 if (!self::$_exportableFields) {
743 self::$_exportableFields = array();
744 }
745
746 $fields = array();
747
748 $participantFields = CRM_Event_DAO_Participant::export();
749 $noteField = array(
750 'participant_note' => array(
751 'title' => 'Participant Note',
752 'name' => 'participant_note',
753 )
754 );
755
756 $participantStatus = array(
757 'participant_status' => array(
758 'title' => 'Participant Status',
759 'name' => 'participant_status',
760 )
761 );
762
763 $participantRole = array(
764 'participant_role' => array(
765 'title' => 'Participant Role',
766 'name' => 'participant_role',
767 )
768 );
769
770 //CRM-13595 add event id to participant export
771 $eventid = array(
772 'event_id' => array(
773 'title' => 'Event ID',
774 'name' => 'event_id',
775 )
776 );
777 $eventtitle = array(
778 'event_title' => array(
779 'title' => 'Event Title',
780 'name' => 'event_title',
781 )
782 );
783
784 $discountFields = CRM_Core_DAO_Discount::export();
785
786 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventid, $eventtitle, $noteField, $discountFields);
787
788 // add custom data
789 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant'));
790 self::$_exportableFields = $fields;
791 }
792
793 return self::$_exportableFields;
794 }
795
796 /**
797 * Get the event name/sort name for a particular participation / participant
798 *
799 * @param int $participantId
800 * Id of the participant.
801 *
802 * @return array $name associated array with sort_name and event title
803 * @static
804 */
805 public static function participantDetails($participantId) {
806 $query = "
807 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
808 FROM civicrm_participant
809 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
810 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
811 WHERE civicrm_participant.id = {$participantId}
812 ";
813 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
814
815 $details = array();
816 while ($dao->fetch()) {
817 $details['name'] = $dao->name;
818 $details['title'] = $dao->title;
819 $details['cid'] = $dao->cid;
820 }
821
822 return $details;
823 }
824
825 /**
826 * Get the values for pseudoconstants for name->value and reverse.
827 *
828 * @param array $defaults
829 * (reference) the default values, some of which need to be resolved.
830 * @param bool $reverse
831 * True if we want to resolve the values in the reverse direction (value -> name).
832 *
833 * @return void
834 * @static
835 */
836 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
837 self::lookupValue($defaults, 'event', CRM_Event_PseudoConstant::event(), $reverse);
838 self::lookupValue($defaults, 'status', CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), $reverse);
839 self::lookupValue($defaults, 'role', CRM_Event_PseudoConstant::participantRole(), $reverse);
840 }
841
842 /**
843 * This function is used to convert associative array names to values
844 * and vice-versa.
845 *
846 * This function is used by both the web form layer and the api. Note that
847 * the api needs the name => value conversion, also the view layer typically
848 * requires value => name conversion
849 */
850 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
851 $id = $property . '_id';
852
853 $src = $reverse ? $property : $id;
854 $dst = $reverse ? $id : $property;
855
856 if (!array_key_exists($src, $defaults)) {
857 return FALSE;
858 }
859
860 $look = $reverse ? array_flip($lookup) : $lookup;
861
862 if (is_array($look)) {
863 if (!array_key_exists($defaults[$src], $look)) {
864 return FALSE;
865 }
866 }
867 $defaults[$dst] = $look[$defaults[$src]];
868 return TRUE;
869 }
870
871 /**
872 * Delete the record that are associated with this participation
873 *
874 * @param int $id
875 * Id of the participation to delete.
876 *
877 * @return void
878 * @static
879 */
880 public static function deleteParticipant($id) {
881 CRM_Utils_Hook::pre('delete', 'Participant', $id, CRM_Core_DAO::$_nullArray);
882
883 $transaction = new CRM_Core_Transaction();
884
885 //delete activity record
886 $params = array(
887 'source_record_id' => $id,
888 // activity type id for event registration
889 'activity_type_id' => 5,
890 );
891
892 CRM_Activity_BAO_Activity::deleteActivity($params);
893
894 // delete the participant payment record
895 // we need to do this since the cascaded constraints
896 // dont work with join tables
897 $p = array('participant_id' => $id);
898 CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
899
900 // cleanup line items.
901 $participantsId = array();
902 $participantsId = self::getAdditionalParticipantIds($id);
903 $participantsId[] = $id;
904 CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
905
906 //delete note when participant deleted.
907 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant');
908 $noteId = key($note);
909 if ($noteId) {
910 CRM_Core_BAO_Note::del($noteId, FALSE);
911 }
912
913 $participant = new CRM_Event_DAO_Participant();
914 $participant->id = $id;
915 $participant->delete();
916
917 $transaction->commit();
918
919 CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
920
921 // delete the recently created Participant
922 $participantRecent = array(
923 'id' => $id,
924 'type' => 'Participant',
925 );
926
927 CRM_Utils_Recent::del($participantRecent);
928
929 return $participant;
930 }
931
932 /**
933 * Checks duplicate participants
934 *
935 * @param array $duplicates
936 * (reference ) an assoc array of name/value pairs.
937 * @param array $input
938 * An assosiative array of name /value pairs.
939 * from other function
940 *
941 * @return CRM_Contribute_BAO_Contribution object
942 * @static
943 */
944 public static function checkDuplicate($input, &$duplicates) {
945 $eventId = CRM_Utils_Array::value('event_id', $input);
946 $contactId = CRM_Utils_Array::value('contact_id', $input);
947
948 $clause = array();
949 $input = array();
950
951 if ($eventId) {
952 $clause[] = "event_id = %1";
953 $input[1] = array($eventId, 'Integer');
954 }
955
956 if ($contactId) {
957 $clause[] = "contact_id = %2";
958 $input[2] = array($contactId, 'Integer');
959 }
960
961 if (empty($clause)) {
962 return FALSE;
963 }
964
965 $clause = implode(' AND ', $clause);
966
967 $query = "SELECT id FROM civicrm_participant WHERE $clause";
968 $dao = CRM_Core_DAO::executeQuery($query, $input);
969 $result = FALSE;
970 while ($dao->fetch()) {
971 $duplicates[] = $dao->id;
972 $result = TRUE;
973 }
974 return $result;
975 }
976
977 /**
978 * Fix the event level
979 *
980 * When price sets are used as event fee, fee_level is set as ^A
981 * separated string. We need to change that string to comma
982 * separated string before using fee_level in view mode.
983 *
984 * @param string $eventLevel
985 * Event_leval string from db.
986 *
987 * @static
988 *
989 * @return void
990 */
991 public static function fixEventLevel(&$eventLevel) {
992 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) &&
993 (substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
994 ) {
995 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($eventLevel, 1, -1)));
996 $pos = strrpos($eventLevel, '(multiple participants)', 0);
997 if ($pos) {
998 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
999 }
1000 }
1001 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
1002 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
1003 substr($eventLevel, 0, 1)
1004 ));
1005 }
1006 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
1007 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
1008 substr($eventLevel, 0, -1)
1009 ));
1010 }
1011 }
1012
1013 /**
1014 * Get the additional participant ids.
1015 *
1016 * @param int $primaryParticipantId
1017 * Primary partycipant Id.
1018 * @param bool $excludeCancel
1019 * Do not include participant those are cancelled.
1020 *
1021 * @param int $oldStatusId
1022 *
1023 * @return array $additionalParticipantIds
1024 * @static
1025 */
1026 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1027 $additionalParticipantIds = array();
1028 if (!$primaryParticipantId) {
1029 return $additionalParticipantIds;
1030 }
1031
1032 $where = "participant.registered_by_id={$primaryParticipantId}";
1033 if ($excludeCancel) {
1034 $cancelStatusId = 0;
1035 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
1036 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1037 $where .= " AND participant.status_id != {$cancelStatusId}";
1038 }
1039
1040 if ($oldStatusId) {
1041 $where .= " AND participant.status_id = {$oldStatusId}";
1042 }
1043
1044 $query = "
1045 SELECT participant.id
1046 FROM civicrm_participant participant
1047 WHERE {$where}";
1048
1049 $dao = CRM_Core_DAO::executeQuery($query);
1050 while ($dao->fetch()) {
1051 $additionalParticipantIds[$dao->id] = $dao->id;
1052 }
1053 return $additionalParticipantIds;
1054 }
1055
1056 /**
1057 * Get the event fee info for given participant ids
1058 * either from line item table / participant table.
1059 *
1060 * @param array $participantIds
1061 * Participant ids.
1062 * @param bool $hasLineItems
1063 * Do fetch from line items.
1064 *
1065 * @return array $feeDetails
1066 * @static
1067 */
1068 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1069 $feeDetails = array();
1070 if (!is_array($participantIds) || empty($participantIds)) {
1071 return $feeDetails;
1072 }
1073
1074 $select = '
1075 SELECT participant.id as id,
1076 participant.fee_level as fee_level,
1077 participant.fee_amount as fee_amount';
1078 $from = 'FROM civicrm_participant participant';
1079 if ($hasLineItems) {
1080 $select .= ' ,
1081 lineItem.id as lineId,
1082 lineItem.label as label,
1083 lineItem.qty as qty,
1084 lineItem.unit_price as unit_price,
1085 lineItem.line_total as line_total,
1086 field.label as field_title,
1087 field.html_type as html_type,
1088 field.id as price_field_id,
1089 value.id as price_field_value_id,
1090 value.description as description,
1091 IF( value.count, value.count, 0 ) as participant_count';
1092 $from .= "
1093 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1094 AND lineItem.entity_id = participant.id )
1095 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1096 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1097 ";
1098 }
1099 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1100 $query = "$select $from $where";
1101
1102 $feeInfo = CRM_Core_DAO::executeQuery($query);
1103 $feeProperties = array('fee_level', 'fee_amount');
1104 $lineProperties = array(
1105 'lineId',
1106 'label',
1107 'qty',
1108 'unit_price',
1109 'line_total',
1110 'field_title',
1111 'html_type',
1112 'price_field_id',
1113 'participant_count',
1114 'price_field_value_id',
1115 'description',
1116 );
1117 while ($feeInfo->fetch()) {
1118 if ($hasLineItems) {
1119 foreach ($lineProperties as $property) {
1120 $feeDetails[$feeInfo->id][$feeInfo->lineId][$property] = $feeInfo->$property;
1121 }
1122 }
1123 else {
1124 foreach ($feeProperties as $property) {
1125 $feeDetails[$feeInfo->id][$property] = $feeInfo->$property;
1126 }
1127 }
1128 }
1129
1130 return $feeDetails;
1131 }
1132
1133 /**
1134 * Retrieve additional participants display-names and URL to view their participant records.
1135 * (excludes cancelled participants automatically)
1136 *
1137 * @param int $primaryParticipantID
1138 * Id of primary participant record.
1139 *
1140 * @return array $additionalParticipants $displayName => $viewUrl
1141 * @static
1142 */
1143 public static function getAdditionalParticipants($primaryParticipantID) {
1144 $additionalParticipantIDs = array();
1145 $additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
1146 if (!empty($additionalParticipantIDs)) {
1147 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1148 $additionalContactID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1149 $additionalParticipantID,
1150 'contact_id', 'id'
1151 );
1152 $additionalContactName = CRM_Contact_BAO_Contact::displayName($additionalContactID);
1153 $pViewURL = CRM_Utils_System::url('civicrm/contact/view/participant',
1154 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1155 );
1156
1157 $additionalParticipants[$additionalContactName] = $pViewURL;
1158 }
1159 }
1160 return $additionalParticipants;
1161 }
1162
1163 /**
1164 * Function for update primary and additional participant status
1165 *
1166 * @param int $participantID
1167 * Primary participant's id.
1168 * @param int $oldStatusID
1169 * @param int $newStatusID
1170 * @param bool $updatePrimaryStatus
1171 *
1172 * @return bool|void
1173 * @static
1174 */
1175 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1176 if (!$participantID || !$oldStatusID) {
1177 return;
1178 }
1179
1180 if (!$newStatusID) {
1181 $newStatusID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1182 }
1183 elseif ($updatePrimaryStatus) {
1184 CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1185 }
1186
1187 $cascadeAdditionalIds = self::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1188
1189 if (!empty($cascadeAdditionalIds)) {
1190 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1191 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1192 $params = array(1 => array($newStatusID, 'Integer'));
1193 $dao = CRM_Core_DAO::executeQuery($query, $params);
1194 return TRUE;
1195 }
1196 return FALSE;
1197 }
1198
1199 /**
1200 * Function for update status for given participant ids
1201 *
1202 * @param int $participantIds
1203 * Array of participant ids.
1204 * @param int $statusId
1205 * Status id for participant.
1206 * @param bool $updateRegisterDate
1207 *
1208 * @return void
1209 *
1210 * @static
1211 */
1212 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1213 if (!is_array($participantIds) || empty($participantIds) || !$statusId) {
1214 return;
1215 }
1216
1217 //lets update register date as we update status to keep track
1218 //when we did update status, useful for moving participant
1219 //from pending to expired.
1220 $setClause = "status_id = {$statusId}";
1221 if ($updateRegisterDate) {
1222 $setClause .= ", register_date = NOW()";
1223 }
1224
1225 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1226
1227 $query = "
1228 UPDATE civicrm_participant
1229 SET {$setClause}
1230 WHERE id IN {$participantIdClause}";
1231
1232 $dao = CRM_Core_DAO::executeQuery($query);
1233 }
1234
1235 /**
1236 * Function takes participant ids and statuses
1237 * update status from $fromStatusId to $toStatusId
1238 * and send mail + create activities.
1239 *
1240 * @param array $participantIds
1241 * Participant ids.
1242 * @param int $toStatusId
1243 * Update status id.
1244 * @param int $fromStatusId
1245 * From status id.
1246 *
1247 * return void
1248 * @param bool $returnResult
1249 * @param bool $skipCascadeRule
1250 *
1251 * @return array
1252 * @static
1253 */
1254 static function transitionParticipants(
1255 $participantIds, $toStatusId,
1256 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1257 ) {
1258 if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
1259 return;
1260 }
1261
1262 //thumb rule is if we triggering primary participant need to triggered additional
1263 $allParticipantIds = $primaryANDAdditonalIds = array();
1264 foreach ($participantIds as $id) {
1265 $allParticipantIds[] = $id;
1266 if (self::isPrimaryParticipant($id)) {
1267 //filter additional as per status transition rules, CRM-5403
1268 if ($skipCascadeRule) {
1269 $additionalIds = self::getAdditionalParticipantIds($id);
1270 }
1271 else {
1272 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1273 }
1274 if (!empty($additionalIds)) {
1275 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1276 $primaryANDAdditonalIds[$id] = $additionalIds;
1277 }
1278 }
1279 }
1280
1281 //get the unique participant ids,
1282 $allParticipantIds = array_unique($allParticipantIds);
1283
1284 //pull required participants, contacts, events data, if not in hand
1285 static $eventDetails = array();
1286 static $domainValues = array();
1287 static $contactDetails = array();
1288
1289 $contactIds = $eventIds = $participantDetails = array();
1290
1291 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
1292 $participantRoles = CRM_Event_PseudoConstant::participantRole();
1293 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
1294 "class = 'Pending'"
1295 );
1296
1297 //first thing is pull all necessory data from db.
1298 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1299
1300 //get all participants data.
1301 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1302 $dao = CRM_Core_DAO::executeQuery($query);
1303 while ($dao->fetch()) {
1304 $participantDetails[$dao->id] = array(
1305 'id' => $dao->id,
1306 'role' => $participantRoles[$dao->role_id],
1307 'is_test' => $dao->is_test,
1308 'event_id' => $dao->event_id,
1309 'status_id' => $dao->status_id,
1310 'fee_amount' => $dao->fee_amount,
1311 'contact_id' => $dao->contact_id,
1312 'register_date' => $dao->register_date,
1313 'registered_by_id' => $dao->registered_by_id,
1314 );
1315 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1316 $contactIds[$dao->contact_id] = $dao->contact_id;
1317 }
1318
1319 if (!array_key_exists($dao->event_id, $eventDetails)) {
1320 $eventIds[$dao->event_id] = $dao->event_id;
1321 }
1322 }
1323
1324 //get the domain values.
1325 if (empty($domainValues)) {
1326 // making all tokens available to templates.
1327 $domain = CRM_Core_BAO_Domain::getDomain();
1328 $tokens = array(
1329 'domain' => array('name', 'phone', 'address', 'email'),
1330 'contact' => CRM_Core_SelectValues::contactTokens(),
1331 );
1332
1333 foreach ($tokens['domain'] as $token) {
1334 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
1335 }
1336 }
1337
1338 //get all required contacts detail.
1339 if (!empty($contactIds)) {
1340 // get the contact details.
1341 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
1342 FALSE, FALSE, NULL,
1343 array(),
1344 'CRM_Event_BAO_Participant'
1345 );
1346 foreach ($currentContactDetails as $contactId => $contactValues) {
1347 $contactDetails[$contactId] = $contactValues;
1348 }
1349 }
1350
1351 //get all required events detail.
1352 if (!empty($eventIds)) {
1353 foreach ($eventIds as $eventId) {
1354 //retrieve event information
1355 $eventParams = array('id' => $eventId);
1356 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1357
1358 //get default participant role.
1359 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1360
1361 //get the location info
1362 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1363 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1364 }
1365 }
1366
1367 //now we are ready w/ all required data.
1368 //take a decision as per statuses.
1369
1370 $emailType = NULL;
1371 $toStatus = $statusTypes[$toStatusId];
1372 $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes);
1373
1374 switch ($toStatus) {
1375 case 'Pending from waitlist':
1376 case 'Pending from approval':
1377 switch ($fromStatus) {
1378 case 'On waitlist':
1379 case 'Awaiting approval':
1380 $emailType = 'Confirm';
1381 break;
1382 }
1383 break;
1384
1385 case 'Expired':
1386 //no matter from where u come send expired mail.
1387 $emailType = $toStatus;
1388 break;
1389
1390 case 'Cancelled':
1391 //no matter from where u come send cancel mail.
1392 $emailType = $toStatus;
1393 break;
1394 }
1395
1396 //as we process additional w/ primary, there might be case if user
1397 //select primary as well as additionals, so avoid double processing.
1398 $processedParticipantIds = array();
1399 $mailedParticipants = array();
1400
1401 //send mails and update status.
1402 foreach ($participantDetails as $participantId => $participantValues) {
1403 $updateParticipantIds = array();
1404 if (in_array($participantId, $processedParticipantIds)) {
1405 continue;
1406 }
1407
1408 //check is it primary and has additional.
1409 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1410 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1411
1412 if ($emailType) {
1413 $mail = self::sendTransitionParticipantMail($additonalId,
1414 $participantDetails[$additonalId],
1415 $eventDetails[$participantDetails[$additonalId]['event_id']],
1416 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1417 $domainValues,
1418 $emailType
1419 );
1420
1421 //get the mail participant ids
1422 if ($mail) {
1423 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1424 }
1425 }
1426 $updateParticipantIds[] = $additonalId;
1427 $processedParticipantIds[] = $additonalId;
1428 }
1429 }
1430
1431 //now send email appropriate mail to primary.
1432 if ($emailType) {
1433 $mail = self::sendTransitionParticipantMail($participantId,
1434 $participantValues,
1435 $eventDetails[$participantValues['event_id']],
1436 $contactDetails[$participantValues['contact_id']],
1437 $domainValues,
1438 $emailType
1439 );
1440
1441 //get the mail participant ids
1442 if ($mail) {
1443 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1444 }
1445 }
1446
1447 //now update status of group/one at once.
1448 $updateParticipantIds[] = $participantId;
1449
1450 //update the register date only when we,
1451 //move participant to pending class, CRM-6496
1452 $updateRegisterDate = FALSE;
1453 if (array_key_exists($toStatusId, $pendingStatuses)) {
1454 $updateRegisterDate = TRUE;
1455 }
1456 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1457 $processedParticipantIds[] = $participantId;
1458 }
1459
1460 //return result for cron.
1461 if ($returnResult) {
1462 $results = array(
1463 'mailedParticipants' => $mailedParticipants,
1464 'updatedParticipantIds' => $processedParticipantIds,
1465 );
1466
1467 return $results;
1468 }
1469 }
1470
1471 /**
1472 * Send mail and create activity
1473 * when participant status changed.
1474 *
1475 * @param int $participantId
1476 * Participant id.
1477 * @param array $participantValues
1478 * Participant detail values. status id for participants.
1479 * @param array $eventDetails
1480 * Required event details.
1481 * @param array $contactDetails
1482 * Required contact details.
1483 * @param array $domainValues
1484 * Required domain values.
1485 * @param string $mailType
1486 * (eg 'approval', 'confirm', 'expired' ).
1487 *
1488 * return void
1489 *
1490 * @return bool
1491 * @static
1492 */
1493 static function sendTransitionParticipantMail(
1494 $participantId,
1495 $participantValues,
1496 $eventDetails,
1497 $contactDetails,
1498 &$domainValues,
1499 $mailType
1500 ) {
1501 //send emails.
1502 $mailSent = FALSE;
1503
1504 //don't send confirmation mail to additional
1505 //since only primary able to confirm registration.
1506 if (!empty($participantValues['registered_by_id']) &&
1507 $mailType == 'Confirm'
1508 ) {
1509 return $mailSent;
1510 }
1511 $toEmail = CRM_Utils_Array::value('email', $contactDetails);
1512 if ($toEmail) {
1513
1514 $contactId = $participantValues['contact_id'];
1515 $participantName = $contactDetails['display_name'];
1516
1517 //calculate the checksum value.
1518 $checksumValue = NULL;
1519 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1520 $checksumLife = 'inf';
1521 $endDate = CRM_Utils_Array::value('end_date', $eventDetails);
1522 if ($endDate) {
1523 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1524 }
1525 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1526 }
1527
1528 //take a receipt from as event else domain.
1529 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1530 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1531 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1532 }
1533
1534 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1535 array(
1536 'groupName' => 'msg_tpl_workflow_event',
1537 'valueName' => 'participant_' . strtolower($mailType),
1538 'contactId' => $contactId,
1539 'tplParams' => array(
1540 'contact' => $contactDetails,
1541 'domain' => $domainValues,
1542 'participant' => $participantValues,
1543 'event' => $eventDetails,
1544 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails),
1545 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails),
1546 'isAdditional' => $participantValues['registered_by_id'],
1547 'isExpired' => $mailType == 'Expired',
1548 'isConfirm' => $mailType == 'Confirm',
1549 'checksumValue' => $checksumValue,
1550 ),
1551 'from' => $receiptFrom,
1552 'toName' => $participantName,
1553 'toEmail' => $toEmail,
1554 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
1555 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
1556 )
1557 );
1558
1559 // 3. create activity record.
1560 if ($mailSent) {
1561 $now = date('YmdHis');
1562 $activityType = 'Event Registration';
1563 $activityParams = array(
1564 'subject' => $subject,
1565 'source_contact_id' => $contactId,
1566 'source_record_id' => $participantId,
1567 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1568 $activityType,
1569 'name'
1570 ),
1571 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1572 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1573 'is_test' => $participantValues['is_test'],
1574 'status_id' => 2,
1575 );
1576
1577 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
1578 CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
1579 }
1580 }
1581 }
1582
1583 return $mailSent;
1584 }
1585
1586 /**
1587 * Get participant status change message.
1588 *
1589 * @param int $participantId
1590 * @param $statusChangeTo
1591 * @param int $fromStatusId
1592 *
1593 * @return string
1594 */
1595 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1596 $statusMsg = NULL;
1597 $results = self::transitionParticipants(array($participantId),
1598 $statusChangeTo, $fromStatusId, TRUE
1599 );
1600
1601 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1602 //give user message only when mail has sent.
1603 if (is_array($results) && !empty($results)) {
1604 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1605 foreach ($results['updatedParticipantIds'] as $processedId) {
1606 if (is_array($results['mailedParticipants']) &&
1607 array_key_exists($processedId, $results['mailedParticipants'])
1608 ) {
1609 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1610 array(
1611 1 => $allStatuses[$statusChangeTo],
1612 2 => $results['mailedParticipants'][$processedId],
1613 )
1614 );
1615 }
1616 }
1617 }
1618 }
1619
1620 return $statusMsg;
1621 }
1622
1623 /**
1624 * Get event full and waiting list message.
1625 *
1626 * @param int $eventId
1627 * @param int $participantId
1628 *
1629 * @return string
1630 */
1631 public static function eventFullMessage($eventId, $participantId = NULL) {
1632 $eventfullMsg = $dbStatusId = NULL;
1633 $checkEventFull = TRUE;
1634 if ($participantId) {
1635 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1636 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1637 //participant already in counted status no need to check for event full messages.
1638 $checkEventFull = FALSE;
1639 }
1640 }
1641
1642 //early return.
1643 if (!$eventId || !$checkEventFull) {
1644 return $eventfullMsg;
1645 }
1646
1647 //event is truly full.
1648 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1649 if (is_string($emptySeats) && $emptySeats !== NULL) {
1650 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1651 $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", array(
1652 1 => $maxParticipants
1653 )) . '<br />';
1654 }
1655
1656 $hasWaiting = FALSE;
1657 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1658 if (is_numeric($waitListedCount)) {
1659 $hasWaiting = TRUE;
1660 //only current processing participant is on waitlist.
1661 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1662 $hasWaiting = FALSE;
1663 }
1664 }
1665
1666 if ($hasWaiting) {
1667 $waitingStatusId = array_search('On waitlist',
1668 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1669 );
1670 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1671 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1672 );
1673
1674 $eventfullMsg .= ts("There are %2 people currently on the waiting list for this event. You can <a href='%1'>view waitlisted registrations here</a>, or you can continue and register additional participants using this form.",
1675 array(
1676 1 => $viewWaitListUrl,
1677 2 => $waitListedCount,
1678 )
1679 );
1680 }
1681
1682 return $eventfullMsg;
1683 }
1684
1685 /**
1686 * Check for whether participant is primary or not
1687 *
1688 * @param int $participantId
1689 *
1690 * @return true if participant is primary
1691 */
1692 public static function isPrimaryParticipant($participantId) {
1693
1694 $participant = new CRM_Event_DAO_Participant();
1695 $participant->registered_by_id = $participantId;
1696
1697 if ($participant->find(TRUE)) {
1698 return TRUE;
1699 }
1700 return FALSE;
1701 }
1702
1703 /**
1704 * Get additional participant Ids for cascading with primary participant status
1705 *
1706 * @param int $participantId
1707 * Participant id.
1708 * @param int $oldStatusId
1709 * Previous status.
1710 * @param int $newStatusId
1711 * New status.
1712 *
1713 * @return true if allowed
1714 */
1715 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1716
1717 $additionalParticipantIds = array();
1718
1719 static $participantStatuses = array();
1720
1721 if (empty($participantStatuses)) {
1722 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1723 }
1724
1725 if (CRM_Utils_Array::value($participantStatuses[$oldStatusId], self::$_statusTransitionsRules) &&
1726 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1727 ) {
1728 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1729 }
1730
1731 return $additionalParticipantIds;
1732 }
1733
1734 /**
1735 * Get participant record count for a Contact
1736 *
1737 * @param int $contactID
1738 *
1739 * @return int count of participant records
1740 * @static
1741 */
1742 public static function getContactParticipantCount($contactID) {
1743 $query = "SELECT count(*)
1744 FROM civicrm_participant
1745 WHERE civicrm_participant.contact_id = {$contactID} AND
1746 civicrm_participant.is_test = 0";
1747 return CRM_Core_DAO::singleValueQuery($query);
1748 }
1749
1750 /**
1751 * Get participant ids by contribution id
1752 *
1753 * @param int $contributionId
1754 * Contribution Id.
1755 * @param bool $excludeCancelled
1756 * Exclude cancelled additional participant.
1757 *
1758 * @return array $participantsId
1759 * @static
1760 */
1761 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1762
1763 $ids = array();
1764 if (!$contributionId) {
1765 return $ids;
1766 }
1767
1768 // get primary participant id
1769 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1770 $participantId = CRM_Core_DAO::singleValueQuery($query);
1771
1772 // get additional participant ids (including cancelled)
1773 if ($participantId) {
1774 $ids = array_merge(array(
1775 $participantId
1776 ), self::getAdditionalParticipantIds($participantId,
1777 $excludeCancelled
1778 ));
1779 }
1780
1781 return $ids;
1782 }
1783
1784 /**
1785 * Get additional Participant edit & view url .
1786 *
1787 * @param array $participantIds
1788 * An array of additional participant ids.
1789 *
1790 * @return array of Urls.
1791 * @static
1792 */
1793 public static function getAdditionalParticipantUrl($participantIds) {
1794 foreach ($participantIds as $value) {
1795 $links = array();
1796 $details = self::participantDetails($value);
1797 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1798 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1799 );
1800 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1801 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1802 );
1803 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1804 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1805 return $links;
1806 }
1807 }
1808
1809 /**
1810 * To create trxn entry if an event has discount.
1811 *
1812 * @param int $eventID
1813 * Event id.
1814 * @param array $contributionParams
1815 * Contribution params.
1816 *
1817 * @param $feeLevel
1818 *
1819 * @static
1820 */
1821 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1822 // CRM-11124
1823 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
1824 if (!empty($checkDiscount)) {
1825 $feeLevel = current($feeLevel);
1826 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
1827 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1828 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1829 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1830 $params = array(
1831 1 => array($priceSetId, 'Integer'),
1832 2 => array($feeLevel, 'String')
1833 );
1834 $mainAmount = CRM_Core_DAO::singleValueQuery($query, $params);
1835 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1836 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
1837 $contributionParams['contribution']->financial_type_id, $relationTypeId);
1838 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1839 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1840 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1841 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1842 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1843
1844 CRM_Core_BAO_FinancialTrxn::create($contributionParams['trxnParams']);
1845 }
1846 }
1847 return;
1848 }
1849
1850 /**
1851 * Delete participants of contact
1852 *
1853 * CRM-12155
1854 *
1855 * @param int $contactId
1856 * Contact id.
1857 *
1858 * @static
1859 */
1860 public static function deleteContactParticipant($contactId) {
1861 $participant = new CRM_Event_DAO_Participant();
1862 $participant->contact_id = $contactId;
1863 $participant->find();
1864 while ($participant->fetch()) {
1865 self::deleteParticipant($participant->id);
1866 }
1867 }
1868
1869 /**
1870 * @param array $params
1871 * @param int $participantId
1872 * @param int $contributionId
1873 * @param $feeBlock
1874 * @param array $lineItems
1875 * @param $paidAmount
1876 * @param int $priceSetId
1877 */
1878 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1879 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1880 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1881 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1882 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
1883 CRM_Price_BAO_PriceSet::processAmount($feeBlock,
1884 $params, $lineItems
1885 );
1886
1887 // get the submitted
1888 foreach ($feeBlock as $id => $values) {
1889 CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
1890 $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1891 }
1892 if (!empty($submittedLineItems)) {
1893 $insertLines = $submittedLineItems;
1894
1895 $submittedFieldValueIds = array_keys($submittedLineItems);
1896 $updateLines = array();
1897 foreach ($previousLineItems as $id => $previousLineItem) {
1898 // check through the submitted items if the previousItem exists,
1899 // if found in submitted items, do not use it for new item creations
1900 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1901 // if submitted line items are existing don't fire INSERT query
1902 unset($insertLines[$previousLineItem['price_field_value_id']]);
1903 // for updating the line items i.e. use-case - once deselect-option selecting again
1904 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
1905 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1)
1906 ) {
1907 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1908 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1909 }
1910 }
1911 }
1912
1913 $submittedFields = implode(', ', $submittedFieldId);
1914 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1915 }
1916 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1917 $updateLineItem = "UPDATE civicrm_line_item li
1918 INNER JOIN civicrm_financial_item fi
1919 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1920 SET li.qty = 0,
1921 li.line_total = 0.00,
1922 li.tax_amount = NULL
1923 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1924 (price_field_value_id NOT IN ({$submittedFieldValues}))
1925 ";
1926 CRM_Core_DAO::executeQuery($updateLineItem);
1927
1928 // gathering necessary info to record negative (deselected) financial_item
1929 $updateFinancialItem = "
1930 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1931 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1932 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1933 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1934 ";
1935 $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
1936 $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1937 $trxnId['id'] = $trxn['financialTrxnId'];
1938 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1939 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
1940 $updateFinancialItemInfoValues = array();
1941
1942 while ($updateFinancialItemInfoDAO->fetch()) {
1943 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1944 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1945 // the below params are not needed
1946 unset($updateFinancialItemInfoValues['id']);
1947 unset($updateFinancialItemInfoValues['created_date']);
1948 // if not submitted and difference is not 0 make it negative
1949 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1950 // INSERT negative financial_items
1951 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
1952 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
1953 // INSERT negative financial_items for tax amount
1954 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1955 $updateFinancialItemInfoValues['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1956 $updateFinancialItemInfoValues['description'] = $taxTerm;
1957 if ($updateFinancialItemInfoValues['financial_type_id']) {
1958 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1959 }
1960 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
1961 }
1962 }
1963 // if submitted and difference is 0 add a positive entry again
1964 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1965 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1966 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
1967 // INSERT financial_items for tax amount
1968 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1969 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1970 ) {
1971 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1972 $updateFinancialItemInfoValues['description'] = $taxTerm;
1973 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1974 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1975 }
1976 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
1977 }
1978 }
1979 }
1980 }
1981 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
1982 $updateLineItem = "UPDATE civicrm_line_item li
1983 INNER JOIN civicrm_financial_item fi
1984 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1985 SET li.qty = 0,
1986 li.line_total = 0.00,
1987 li.tax_amount = NULL
1988 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1989 CRM_Core_DAO::executeQuery($updateLineItem);
1990 }
1991 if (!empty($updateLines)) {
1992 foreach ($updateLines as $valueId => $vals) {
1993 if (isset($vals['tax_amount'])) {
1994 $taxAmount = $vals['tax_amount'];
1995 }
1996 else {
1997 $taxAmount = "NULL";
1998 }
1999 $updateLineItem = "
2000 UPDATE civicrm_line_item li
2001 SET li.qty = {$vals['qty']},
2002 li.line_total = {$vals['line_total']},
2003 li.tax_amount = {$taxAmount},
2004 li.unit_price = {$vals['unit_price']},
2005 li.label = '{$vals['label']}'
2006 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
2007 (price_field_value_id = {$valueId})
2008 ";
2009 CRM_Core_DAO::executeQuery($updateLineItem);
2010 }
2011 }
2012 // insert new 'adjusted amount' transaction entry and update contribution entry.
2013 // ensure entity_financial_trxn table has a linking of it.
2014 // insert new line items
2015 if (!empty($insertLines)) {
2016 foreach ($insertLines as $valueId => $lineParams) {
2017 $lineParams['entity_table'] = 'civicrm_participant';
2018 $lineParams['entity_id'] = $participantId;
2019 $lineParams['contribution_id'] = $contributionId;
2020 $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
2021 }
2022 }
2023
2024 // the recordAdjustedAmt code would execute over here
2025 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
2026 if (count($ids) > 1) {
2027 $total = 0;
2028 foreach ($ids as $val) {
2029 $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
2030 }
2031 $updatedAmount = $total;
2032 }
2033 else {
2034 $updatedAmount = $params['amount'];
2035 }
2036 if (strlen($params['tax_amount']) != 0) {
2037 $taxAmount = $params['tax_amount'];
2038 }
2039 else {
2040 $taxAmount = "NULL";
2041 }
2042 self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
2043
2044 $fetchCon = array('id' => $contributionId);
2045 $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
2046 // insert financial items
2047 if (!empty($insertLines)) {
2048 foreach ($insertLines as $valueId => $lineParams) {
2049 $lineParams['entity_table'] = 'civicrm_participant';
2050 $lineParams['entity_id'] = $participantId;
2051 $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
2052 // insert financial items
2053 // ensure entity_financial_trxn table has a linking of it.
2054 $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution);
2055 if (isset($lineObj->tax_amount)) {
2056 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE);
2057 }
2058 }
2059 }
2060
2061 // update participant fee_amount column
2062 $partUpdateFeeAmt['id'] = $participantId;
2063 foreach ($lineItems as $lineValue) {
2064 if ($lineValue['price_field_value_id']) {
2065 $line[$lineValue['price_field_value_id']] = $lineValue['label'] . ' - ' . $lineValue['qty'];
2066 }
2067 }
2068
2069 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
2070 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2071 self::add($partUpdateFeeAmt);
2072
2073 //activity creation
2074 self::addActivityForSelection($participantId, 'Change Registration');
2075 }
2076
2077 /**
2078 * @param $updatedAmount
2079 * @param $paidAmount
2080 * @param int $contributionId
2081 */
2082 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2083 $balanceAmt = $updatedAmount - $paidAmount;
2084 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2085 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2086 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2087 $completedStatusId = array_search('Completed', $contributionStatuses);
2088
2089 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2090 $skip = FALSE;
2091 if ($balanceAmt) {
2092 if ($balanceAmt > 0 && $paidAmount != 0) {
2093 $contributionStatusVal = $partiallyPaidStatusId;
2094 }
2095 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2096 $contributionStatusVal = $pendingRefundStatusId;
2097 }
2098 elseif ($paidAmount == 0) {
2099 //skip updating the contribution status if no payment is made
2100 $skip = TRUE;
2101 $updatedContributionDAO->cancel_date = 'null';
2102 $updatedContributionDAO->cancel_reason = NULL;
2103 }
2104 // update contribution status and total amount without trigger financial code
2105 // as this is handled in current BAO function used for change selection
2106 $updatedContributionDAO->id = $contributionId;
2107 if (!$skip) {
2108 $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
2109 }
2110 $updatedContributionDAO->total_amount = $updatedAmount;
2111 $updatedContributionDAO->tax_amount = $taxAmount;
2112 $updatedContributionDAO->save();
2113
2114 $ftDetail = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
2115 // adjusted amount financial_trxn creation
2116 if (empty($ftDetail['trxn_id'])) {
2117 $updatedContribution =
2118 CRM_Contribute_BAO_Contribution::getValues(array('id' => $contributionId), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
2119 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2120 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId);
2121
2122 $adjustedTrxnValues = array(
2123 'from_financial_account_id' => NULL,
2124 'to_financial_account_id' => $toFinancialAccount,
2125 'total_amount' => $balanceAmt,
2126 'status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'),
2127 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
2128 'contribution_id' => $updatedContribution->id,
2129 'trxn_date' => date('YmdHis'),
2130 'currency' => $updatedContribution->currency
2131 );
2132 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
2133 }
2134 else {
2135 // update the financial trxn amount as well, as the fee selections has been updated
2136 if ($balanceAmt != $ftDetail['total_amount']) {
2137 CRM_Core_DAO::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2138 }
2139 }
2140 }
2141 }
2142
2143 /**
2144 * @param int $participantId
2145 * @param $activityType
2146 *
2147 * @throws CRM_Core_Exception
2148 */
2149 public static function addActivityForSelection($participantId, $activityType) {
2150 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2151 $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2152
2153 $date = CRM_Utils_Date::currentDBDate();
2154 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
2155 $eventTitle = $event[$eventId];
2156 $subject = "Registration selections changed for $eventTitle";
2157 $targetCid = $contactId;
2158 $srcRecId = $participantId;
2159
2160 // activity params
2161 $activityParams = array(
2162 'source_contact_id' => $targetCid,
2163 'source_record_id' => $srcRecId,
2164 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
2165 $activityType,
2166 'name'
2167 ),
2168 'subject' => $subject,
2169 'activity_date_time' => $date,
2170 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
2171 'Completed',
2172 'name'
2173 ),
2174 'skipRecentView' => TRUE,
2175 );
2176
2177 // create activity with target contacts
2178 $session = CRM_Core_Session::singleton();
2179 $id = $session->get('userID');
2180 if ($id) {
2181 $activityParams['source_contact_id'] = $id;
2182 $activityParams['target_contact_id'][] = $targetCid;
2183 }
2184 CRM_Activity_BAO_Activity::create($activityParams);
2185 }
2186
2187 /**
2188 * Get options for a given field.
2189 * @see CRM_Core_DAO::buildOptions
2190 *
2191 * @param string $fieldName
2192 * @param string $context
2193 * : @see CRM_Core_DAO::buildOptionsContext.
2194 * @param array $props
2195 * : whatever is known about this dao object.
2196 *
2197 * @return Array|bool
2198 */
2199 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2200 $params = array('condition' => array());
2201
2202 if ($fieldName == 'status_id' && $context != 'validate') {
2203 // Get rid of cart-related option if disabled
2204 // FIXME: Why does this option even exist if cart is disabled?
2205 if (!CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME, 'enable_cart')) {
2206 $params['condition'][] = "name <> 'Pending in cart'";
2207 }
2208 }
2209
2210 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
2211 }
2212 }