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