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