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