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