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