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