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