Merge pull request #2267 from eileenmcnaughton/test-fixes
[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 //campaign fields.
702 if (isset($tmpFields['participant_campaign_id'])) {
703 $tmpFields['participant_campaign'] = array('title' => ts('Campaign Title'));
704 }
705
706 $fields = array_merge($fields, $tmpContactField);
707 $fields = array_merge($fields, $tmpFields);
708 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
709 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant'));
710
711 self::$_importableFields = $fields;
712 }
713
714 return self::$_importableFields;
715 }
716
717 /**
718 * combine all the exportable fields from the lower levels object
719 *
720 * @return array array of exportable Fields
721 * @access public
722 * @static
723 */
724 static function &exportableFields() {
725 if (!self::$_exportableFields) {
726 if (!self::$_exportableFields) {
727 self::$_exportableFields = array();
728 }
729
730 $fields = array();
731
732 $participantFields = CRM_Event_DAO_Participant::export();
733 $noteField = array(
734 'participant_note' => array('title' => 'Participant Note',
735 'name' => 'participant_note',
736 ));
737
738 $participantStatus = array(
739 'participant_status' => array('title' => 'Participant Status',
740 'name' => 'participant_status',
741 ));
742
743 $participantRole = array(
744 'participant_role' => array('title' => 'Participant Role',
745 'name' => 'participant_role',
746 ));
747
748 //campaign fields.
749 if (isset($participantFields['participant_campaign_id'])) {
750 $participantFields['participant_campaign'] = array('title' => ts('Campaign Title'));
751 }
752
753 $discountFields = CRM_Core_DAO_Discount::export();
754
755 $fields = array_merge($participantFields, $participantStatus, $participantRole, $noteField, $discountFields);
756
757 // add custom data
758 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant'));
759 self::$_exportableFields = $fields;
760 }
761
762 return self::$_exportableFields;
763 }
764
765 /**
766 * function to get the event name/sort name for a particular participation / participant
767 *
768 * @param int $participantId id of the participant
769
770 *
771 * @return array $name associated array with sort_name and event title
772 * @static
773 * @access public
774 */
775 static function participantDetails($participantId) {
776 $query = "
777 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
778 FROM civicrm_participant
779 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
780 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
781 WHERE civicrm_participant.id = {$participantId}
782 ";
783 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
784
785 $details = array();
786 while ($dao->fetch()) {
787 $details['name'] = $dao->name;
788 $details['title'] = $dao->title;
789 $details['cid'] = $dao->cid;
790 }
791
792 return $details;
793 }
794
795 /**
796 * Get the values for pseudoconstants for name->value and reverse.
797 *
798 * @param array $defaults (reference) the default values, some of which need to be resolved.
799 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
800 *
801 * @return void
802 * @access public
803 * @static
804 */
805 static function resolveDefaults(&$defaults, $reverse = FALSE) {
806 self::lookupValue($defaults, 'event', CRM_Event_PseudoConstant::event(), $reverse);
807 self::lookupValue($defaults, 'status', CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), $reverse);
808 self::lookupValue($defaults, 'role', CRM_Event_PseudoConstant::participantRole(), $reverse);
809 }
810
811 /**
812 * This function is used to convert associative array names to values
813 * and vice-versa.
814 *
815 * This function is used by both the web form layer and the api. Note that
816 * the api needs the name => value conversion, also the view layer typically
817 * requires value => name conversion
818 */
819 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
820 $id = $property . '_id';
821
822 $src = $reverse ? $property : $id;
823 $dst = $reverse ? $id : $property;
824
825 if (!array_key_exists($src, $defaults)) {
826 return FALSE;
827 }
828
829 $look = $reverse ? array_flip($lookup) : $lookup;
830
831 if (is_array($look)) {
832 if (!array_key_exists($defaults[$src], $look)) {
833 return FALSE;
834 }
835 }
836 $defaults[$dst] = $look[$defaults[$src]];
837 return TRUE;
838 }
839
840 /**
841 * Delete the record that are associated with this participation
842 *
843 * @param int $id id of the participation to delete
844 *
845 * @return void
846 * @access public
847 * @static
848 */
849 static function deleteParticipant($id) {
850 CRM_Utils_Hook::pre('delete', 'Participant', $id, CRM_Core_DAO::$_nullArray);
851
852 $transaction = new CRM_Core_Transaction();
853
854 //delete activity record
855 $params = array(
856 'source_record_id' => $id,
857 // activity type id for event registration
858 'activity_type_id' => 5,
859 );
860
861 CRM_Activity_BAO_Activity::deleteActivity($params);
862
863 // delete the participant payment record
864 // we need to do this since the cascaded constraints
865 // dont work with join tables
866 $p = array('participant_id' => $id);
867 CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
868
869 // cleanup line items.
870 $participantsId = array();
871 $participantsId = self::getAdditionalParticipantIds($id);
872 $participantsId[] = $id;
873 CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
874
875 //delete note when participant deleted.
876 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant');
877 $noteId = key($note);
878 if ($noteId) {
879 CRM_Core_BAO_Note::del($noteId, FALSE);
880 }
881
882 $participant = new CRM_Event_DAO_Participant();
883 $participant->id = $id;
884 $participant->delete();
885
886 $transaction->commit();
887
888 CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
889
890 // delete the recently created Participant
891 $participantRecent = array(
892 'id' => $id,
893 'type' => 'Participant',
894 );
895
896 CRM_Utils_Recent::del($participantRecent);
897
898 return $participant;
899 }
900
901 /**
902 *Checks duplicate participants
903 *
904 * @param array $duplicates (reference ) an assoc array of name/value pairs
905 * @param array $input an assosiative array of name /value pairs
906 * from other function
907 *
908 * @return object CRM_Contribute_BAO_Contribution object
909 * @access public
910 * @static
911 */
912 static function checkDuplicate($input, &$duplicates) {
913 $eventId = CRM_Utils_Array::value('event_id', $input);
914 $contactId = CRM_Utils_Array::value('contact_id', $input);
915
916 $clause = array();
917 $input = array();
918
919 if ($eventId) {
920 $clause[] = "event_id = %1";
921 $input[1] = array($eventId, 'Integer');
922 }
923
924 if ($contactId) {
925 $clause[] = "contact_id = %2";
926 $input[2] = array($contactId, 'Integer');
927 }
928
929 if (empty($clause)) {
930 return FALSE;
931 }
932
933 $clause = implode(' AND ', $clause);
934
935 $query = "SELECT id FROM civicrm_participant WHERE $clause";
936 $dao = CRM_Core_DAO::executeQuery($query, $input);
937 $result = FALSE;
938 while ($dao->fetch()) {
939 $duplicates[] = $dao->id;
940 $result = TRUE;
941 }
942 return $result;
943 }
944
945 /**
946 * fix the event level
947 *
948 * When price sets are used as event fee, fee_level is set as ^A
949 * seperated string. We need to change that string to comma
950 * separated string before using fee_level in view mode.
951 *
952 * @param string $eventLevel event_leval string from db
953 *
954 * @static
955 *
956 * @return void
957 */
958 static function fixEventLevel(&$eventLevel) {
959 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) &&
960 (substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
961 ) {
962 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
963 substr($eventLevel, 1, -1)
964 ));
965 if ($pos = strrpos($eventLevel, '(multiple participants)', 0)) {
966 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
967 }
968 }
969 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
970 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
971 substr($eventLevel, 0, 1)
972 ));
973 }
974 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
975 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
976 substr($eventLevel, 0, -1)
977 ));
978 }
979 }
980
981 /**
982 * get the additional participant ids.
983 *
984 * @param int $primaryParticipantId primary partycipant Id
985 * @param boolean $excludeCancel do not include participant those are cancelled.
986 *
987 * @return array $additionalParticipantIds
988 * @static
989 */
990 static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
991 $additionalParticipantIds = array();
992 if (!$primaryParticipantId) {
993 return $additionalParticipantIds;
994 }
995
996 $where = "participant.registered_by_id={$primaryParticipantId}";
997 if ($excludeCancel) {
998 $cancelStatusId = 0;
999 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
1000 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1001 $where .= " AND participant.status_id != {$cancelStatusId}";
1002 }
1003
1004 if ($oldStatusId) {
1005 $where .= " AND participant.status_id = {$oldStatusId}";
1006 }
1007
1008 $query = "
1009 SELECT participant.id
1010 FROM civicrm_participant participant
1011 WHERE {$where}";
1012
1013 $dao = CRM_Core_DAO::executeQuery($query);
1014 while ($dao->fetch()) {
1015 $additionalParticipantIds[$dao->id] = $dao->id;
1016 }
1017 return $additionalParticipantIds;
1018 }
1019
1020 /**
1021 * Get the event fee info for given participant ids
1022 * either from line item table / participant table.
1023 *
1024 * @param array $participantIds participant ids.
1025 * @param boolean $hasLineItems do fetch from line items.
1026 *
1027 * @return array $feeDetails
1028 * @static
1029 */
1030 function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1031 $feeDetails = array();
1032 if (!is_array($participantIds) || empty($participantIds)) {
1033 return $feeDetails;
1034 }
1035
1036 $select = '
1037 SELECT participant.id as id,
1038 participant.fee_level as fee_level,
1039 participant.fee_amount as fee_amount';
1040 $from = 'FROM civicrm_participant participant';
1041 if ($hasLineItems) {
1042 $select .= ' ,
1043 lineItem.id as lineId,
1044 lineItem.label as label,
1045 lineItem.qty as qty,
1046 lineItem.unit_price as unit_price,
1047 lineItem.line_total as line_total,
1048 field.label as field_title,
1049 field.html_type as html_type,
1050 field.id as price_field_id,
1051 value.id as price_field_value_id,
1052 value.description as description,
1053 IF( value.count, value.count, 0 ) as participant_count';
1054 $from .= "
1055 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1056 AND lineItem.entity_id = participant.id )
1057 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1058 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1059 ";
1060 }
1061 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1062 $query = "$select $from $where";
1063
1064 $feeInfo = CRM_Core_DAO::executeQuery($query);
1065 $feeProperties = array('fee_level', 'fee_amount');
1066 $lineProperties = array(
1067 'lineId', 'label', 'qty', 'unit_price',
1068 'line_total', 'field_title', 'html_type',
1069 'price_field_id', 'participant_count', 'price_field_value_id', 'description',
1070 );
1071 while ($feeInfo->fetch()) {
1072 if ($hasLineItems) {
1073 foreach ($lineProperties as $property) {
1074 $feeDetails[$feeInfo->id][$feeInfo->lineId][$property] = $feeInfo->$property;
1075 }
1076 }
1077 else {
1078 foreach ($feeProperties as $property) $feeDetails[$feeInfo->id][$property] = $feeInfo->$property;
1079 }
1080 }
1081
1082 return $feeDetails;
1083 }
1084
1085 /**
1086 * Retrieve additional participants display-names and URL to view their participant records.
1087 * (excludes cancelled participants automatically)
1088 *
1089 * @param int $primaryParticipantID id of primary participant record
1090 *
1091 * @return array $additionalParticipants $displayName => $viewUrl
1092 * @static
1093 */
1094 static function getAdditionalParticipants($primaryParticipantID) {
1095 $additionalParticipantIDs = array();
1096 $additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
1097 if (!empty($additionalParticipantIDs)) {
1098 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1099 $additionalContactID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1100 $additionalParticipantID,
1101 'contact_id', 'id'
1102 );
1103 $additionalContactName = CRM_Contact_BAO_Contact::displayName($additionalContactID);
1104 $pViewURL = CRM_Utils_System::url('civicrm/contact/view/participant',
1105 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1106 );
1107
1108 $additionalParticipants[$additionalContactName] = $pViewURL;
1109 }
1110 }
1111 return $additionalParticipants;
1112 }
1113
1114 /**
1115 * Function for update primary and additional participant status
1116 *
1117 * @param int $participantID primary participant's id
1118 * @param int $statusId status id for participant
1119 * return void
1120 * @access public
1121 * @static
1122 */
1123 static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1124 if (!$participantID || !$oldStatusID) {
1125 return;
1126 }
1127
1128 if (!$newStatusID) {
1129 $newStatusID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1130 }
1131 elseif ($updatePrimaryStatus) {
1132 CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1133 }
1134
1135 $cascadeAdditionalIds = self::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1136
1137 if (!empty($cascadeAdditionalIds)) {
1138 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1139 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1140 $params = array(1 => array($newStatusID, 'Integer'));
1141 $dao = CRM_Core_DAO::executeQuery($query, $params);
1142 return TRUE;
1143 }
1144 return FALSE;
1145 }
1146
1147 /**
1148 * Function for update status for given participant ids
1149 *
1150 * @param int $participantIds array of participant ids
1151 * @param int $statusId status id for participant
1152 * @params boolean $updateRegisterDate way to track when status changed.
1153 *
1154 * return void
1155 * @access public
1156 * @static
1157 */
1158 static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1159 if (!is_array($participantIds) || empty($participantIds) || !$statusId) {
1160 return;
1161 }
1162
1163 //lets update register date as we update status to keep track
1164 //when we did update status, useful for moving participant
1165 //from pending to expired.
1166 $setClause = "status_id = {$statusId}";
1167 if ($updateRegisterDate) {
1168 $setClause .= ", register_date = NOW()";
1169 }
1170
1171 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1172
1173 $query = "
1174 UPDATE civicrm_participant
1175 SET {$setClause}
1176 WHERE id IN {$participantIdClause}";
1177
1178 $dao = CRM_Core_DAO::executeQuery($query);
1179 }
1180
1181 /*
1182 * Function takes participant ids and statuses
1183 * update status from $fromStatusId to $toStatusId
1184 * and send mail + create activities.
1185 *
1186 * @param array $participantIds participant ids.
1187 * @param int $toStatusId update status id.
1188 * @param int $fromStatusId from status id
1189 *
1190 * return void
1191 * @access public
1192 * @static
1193 */
1194 static function transitionParticipants($participantIds, $toStatusId,
1195 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1196 ) {
1197 if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
1198 return;
1199 }
1200
1201 //thumb rule is if we triggering primary participant need to triggered additional
1202 $allParticipantIds = $primaryANDAdditonalIds = array();
1203 foreach ($participantIds as $id) {
1204 $allParticipantIds[] = $id;
1205 if (self::isPrimaryParticipant($id)) {
1206 //filter additional as per status transition rules, CRM-5403
1207 if ($skipCascadeRule) {
1208 $additionalIds = self::getAdditionalParticipantIds($id);
1209 }
1210 else {
1211 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1212 }
1213 if (!empty($additionalIds)) {
1214 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1215 $primaryANDAdditonalIds[$id] = $additionalIds;
1216 }
1217 }
1218 }
1219
1220 //get the unique participant ids,
1221 $allParticipantIds = array_unique($allParticipantIds);
1222
1223 //pull required participants, contacts, events data, if not in hand
1224 static $eventDetails = array();
1225 static $domainValues = array();
1226 static $contactDetails = array();
1227
1228 $contactIds = $eventIds = $participantDetails = array();
1229
1230 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
1231 $participantRoles = CRM_Event_PseudoConstant::participantRole();
1232 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
1233 "class = 'Pending'"
1234 );
1235
1236 //first thing is pull all necessory data from db.
1237 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1238
1239 //get all participants data.
1240 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1241 $dao = CRM_Core_DAO::executeQuery($query);
1242 while ($dao->fetch()) {
1243 $participantDetails[$dao->id] = array(
1244 'id' => $dao->id,
1245 'role' => $participantRoles[$dao->role_id],
1246 'is_test' => $dao->is_test,
1247 'event_id' => $dao->event_id,
1248 'status_id' => $dao->status_id,
1249 'fee_amount' => $dao->fee_amount,
1250 'contact_id' => $dao->contact_id,
1251 'register_date' => $dao->register_date,
1252 'registered_by_id' => $dao->registered_by_id,
1253 );
1254 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1255 $contactIds[$dao->contact_id] = $dao->contact_id;
1256 }
1257
1258 if (!array_key_exists($dao->event_id, $eventDetails)) {
1259 $eventIds[$dao->event_id] = $dao->event_id;
1260 }
1261 }
1262
1263 //get the domain values.
1264 if (empty($domainValues)) {
1265 // making all tokens available to templates.
1266 $domain = CRM_Core_BAO_Domain::getDomain();
1267 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
1268 'contact' => CRM_Core_SelectValues::contactTokens(),
1269 );
1270
1271 foreach ($tokens['domain'] as $token) {
1272 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
1273 }
1274 }
1275
1276 //get all required contacts detail.
1277 if (!empty($contactIds)) {
1278 // get the contact details.
1279 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
1280 FALSE, FALSE, NULL,
1281 array(),
1282 'CRM_Event_BAO_Participant'
1283 );
1284 foreach ($currentContactDetails as $contactId => $contactValues) {
1285 $contactDetails[$contactId] = $contactValues;
1286 }
1287 }
1288
1289 //get all required events detail.
1290 if (!empty($eventIds)) {
1291 foreach ($eventIds as $eventId) {
1292 //retrieve event information
1293 $eventParams = array('id' => $eventId);
1294 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1295
1296 //get default participant role.
1297 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1298
1299 //get the location info
1300 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1301 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1302 }
1303 }
1304
1305 //now we are ready w/ all required data.
1306 //take a decision as per statuses.
1307
1308 $emailType = NULL;
1309 $toStatus = $statusTypes[$toStatusId];
1310 $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes);
1311
1312 switch ($toStatus) {
1313 case 'Pending from waitlist':
1314 case 'Pending from approval':
1315 switch ($fromStatus) {
1316 case 'On waitlist':
1317 case 'Awaiting approval':
1318 $emailType = 'Confirm';
1319 break;
1320 }
1321 break;
1322
1323 case 'Expired':
1324 //no matter from where u come send expired mail.
1325 $emailType = $toStatus;
1326 break;
1327
1328 case 'Cancelled':
1329 //no matter from where u come send cancel mail.
1330 $emailType = $toStatus;
1331 break;
1332 }
1333
1334 //as we process additional w/ primary, there might be case if user
1335 //select primary as well as additionals, so avoid double processing.
1336 $processedParticipantIds = array();
1337 $mailedParticipants = array();
1338
1339 //send mails and update status.
1340 foreach ($participantDetails as $participantId => $participantValues) {
1341 $updateParticipantIds = array();
1342 if (in_array($participantId, $processedParticipantIds)) {
1343 continue;
1344 }
1345
1346 //check is it primary and has additional.
1347 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1348 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1349
1350 if ($emailType) {
1351 $mail = self::sendTransitionParticipantMail($additonalId,
1352 $participantDetails[$additonalId],
1353 $eventDetails[$participantDetails[$additonalId]['event_id']],
1354 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1355 $domainValues,
1356 $emailType
1357 );
1358
1359 //get the mail participant ids
1360 if ($mail) {
1361 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1362 }
1363 }
1364 $updateParticipantIds[] = $additonalId;
1365 $processedParticipantIds[] = $additonalId;
1366 }
1367 }
1368
1369 //now send email appropriate mail to primary.
1370 if ($emailType) {
1371 $mail = self::sendTransitionParticipantMail($participantId,
1372 $participantValues,
1373 $eventDetails[$participantValues['event_id']],
1374 $contactDetails[$participantValues['contact_id']],
1375 $domainValues,
1376 $emailType
1377 );
1378
1379 //get the mail participant ids
1380 if ($mail) {
1381 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1382 }
1383 }
1384
1385 //now update status of group/one at once.
1386 $updateParticipantIds[] = $participantId;
1387
1388 //update the register date only when we,
1389 //move participant to pending class, CRM-6496
1390 $updateRegisterDate = FALSE;
1391 if (array_key_exists($toStatusId, $pendingStatuses)) {
1392 $updateRegisterDate = TRUE;
1393 }
1394 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1395 $processedParticipantIds[] = $participantId;
1396 }
1397
1398 //return result for cron.
1399 if ($returnResult) {
1400 $results = array(
1401 'mailedParticipants' => $mailedParticipants,
1402 'updatedParticipantIds' => $processedParticipantIds,
1403 );
1404
1405 return $results;
1406 }
1407 }
1408
1409 /**
1410 * Function to send mail and create activity
1411 * when participant status changed.
1412 *
1413 * @param int $participantId participant id.
1414 * @param array $participantValues participant detail values. status id for participants
1415 * @param array $eventDetails required event details
1416 * @param array $contactDetails required contact details
1417 * @param array $domainValues required domain values.
1418 * @param string $mailType (eg 'approval', 'confirm', 'expired' )
1419 *
1420 * return void
1421 * @access public
1422 * @static
1423 */
1424 static function sendTransitionParticipantMail(
1425 $participantId,
1426 $participantValues,
1427 $eventDetails,
1428 $contactDetails,
1429 &$domainValues,
1430 $mailType
1431 ) {
1432 //send emails.
1433 $mailSent = FALSE;
1434
1435 //don't send confirmation mail to additional
1436 //since only primary able to confirm registration.
1437 if (CRM_Utils_Array::value('registered_by_id', $participantValues) &&
1438 $mailType == 'Confirm'
1439 ) {
1440 return $mailSent;
1441 }
1442
1443 if ($toEmail = CRM_Utils_Array::value('email', $contactDetails)) {
1444
1445 $contactId = $participantValues['contact_id'];
1446 $participantName = $contactDetails['display_name'];
1447
1448 //calculate the checksum value.
1449 $checksumValue = NULL;
1450 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1451 $checksumLife = 'inf';
1452 if ($endDate = CRM_Utils_Array::value('end_date', $eventDetails)) {
1453 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1454 }
1455 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1456 }
1457
1458 //take a receipt from as event else domain.
1459 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1460 if (CRM_Utils_Array::value('confirm_from_name', $eventDetails) &&
1461 CRM_Utils_Array::value('confirm_from_email', $eventDetails)
1462 ) {
1463 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1464 }
1465
1466 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1467 array(
1468 'groupName' => 'msg_tpl_workflow_event',
1469 'valueName' => 'participant_' . strtolower($mailType),
1470 'contactId' => $contactId,
1471 'tplParams' => array(
1472 'contact' => $contactDetails,
1473 'domain' => $domainValues,
1474 'participant' => $participantValues,
1475 'event' => $eventDetails,
1476 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails),
1477 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails),
1478 'isAdditional' => $participantValues['registered_by_id'],
1479 'isExpired' => $mailType == 'Expired',
1480 'isConfirm' => $mailType == 'Confirm',
1481 'checksumValue' => $checksumValue,
1482 ),
1483 'from' => $receiptFrom,
1484 'toName' => $participantName,
1485 'toEmail' => $toEmail,
1486 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
1487 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
1488 )
1489 );
1490
1491 // 3. create activity record.
1492 if ($mailSent) {
1493 $now = date('YmdHis');
1494 $activityType = 'Event Registration';
1495 $activityParams = array(
1496 'subject' => $subject,
1497 'source_contact_id' => $contactId,
1498 'source_record_id' => $participantId,
1499 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1500 $activityType,
1501 'name'
1502 ),
1503 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1504 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1505 'is_test' => $participantValues['is_test'],
1506 'status_id' => 2,
1507 );
1508
1509 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
1510 CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
1511 }
1512 }
1513 }
1514
1515 return $mailSent;
1516 }
1517
1518 /**
1519 * get participant status change message.
1520 *
1521 * @return string
1522 * @access public
1523 */
1524 function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1525 $statusMsg = NULL;
1526 $results = self::transitionParticipants(array($participantId),
1527 $statusChangeTo, $fromStatusId, TRUE
1528 );
1529
1530 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1531 //give user message only when mail has sent.
1532 if (is_array($results) && !empty($results)) {
1533 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1534 foreach ($results['updatedParticipantIds'] as $processedId) {
1535 if (is_array($results['mailedParticipants']) &&
1536 array_key_exists($processedId, $results['mailedParticipants'])
1537 ) {
1538 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1539 array(
1540 1 => $allStatuses[$statusChangeTo],
1541 2 => $results['mailedParticipants'][$processedId],
1542 )
1543 );
1544 }
1545 }
1546 }
1547 }
1548
1549 return $statusMsg;
1550 }
1551
1552 /**
1553 * get event full and waiting list message.
1554 *
1555 * @return string
1556 * @access public
1557 */
1558 static function eventFullMessage($eventId, $participantId = NULL) {
1559 $eventfullMsg = $dbStatusId = NULL;
1560 $checkEventFull = TRUE;
1561 if ($participantId) {
1562 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1563 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1564 //participant already in counted status no need to check for event full messages.
1565 $checkEventFull = FALSE;
1566 }
1567 }
1568
1569 //early return.
1570 if (!$eventId || !$checkEventFull) {
1571 return $eventfullMsg;
1572 }
1573
1574 //event is truly full.
1575 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1576 if (is_string($emptySeats) && $emptySeats !== NULL) {
1577 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1578 $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(
1579 1 => $maxParticipants)) . '<br />';
1580 }
1581
1582 $hasWaiting = FALSE;
1583 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1584 if (is_numeric($waitListedCount)) {
1585 $hasWaiting = TRUE;
1586 //only current processing participant is on waitlist.
1587 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1588 $hasWaiting = FALSE;
1589 }
1590 }
1591
1592 if ($hasWaiting) {
1593 $waitingStatusId = array_search('On waitlist',
1594 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1595 );
1596 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1597 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1598 );
1599
1600 $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.",
1601 array(
1602 1 => $viewWaitListUrl,
1603 2 => $waitListedCount,
1604 )
1605 );
1606 }
1607
1608 return $eventfullMsg;
1609 }
1610
1611 /**
1612 * check for whether participant is primary or not
1613 *
1614 * @param $participantId
1615 *
1616 * @return true if participant is primary
1617 * @access public
1618 */
1619 static function isPrimaryParticipant($participantId) {
1620
1621 $participant = new CRM_Event_DAO_Participant();
1622 $participant->registered_by_id = $participantId;
1623
1624 if ($participant->find(TRUE)) {
1625 return TRUE;
1626 }
1627 return FALSE;
1628 }
1629
1630 /**
1631 * get additional participant Ids for cascading with primary participant status
1632 *
1633 * @param int $participantId participant id.
1634 * @param int $oldStatusId previous status
1635 * @param int $newStatusId new status
1636 *
1637 * @return true if allowed
1638 * @access public
1639 */
1640 static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1641
1642 $additionalParticipantIds = array();
1643
1644 static $participantStatuses = array();
1645
1646 if (empty($participantStatuses)) {
1647 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1648 }
1649
1650 if (CRM_Utils_Array::value($participantStatuses[$oldStatusId], self::$_statusTransitionsRules) &&
1651 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1652 ) {
1653 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1654 }
1655
1656 return $additionalParticipantIds;
1657 }
1658
1659 /**
1660 * Function to get participant record count for a Contact
1661 *
1662 * @param int $contactId Contact ID
1663 *
1664 * @return int count of participant records
1665 * @access public
1666 * @static
1667 */
1668 static function getContactParticipantCount($contactID) {
1669 $query = "SELECT count(*)
1670 FROM civicrm_participant
1671 WHERE civicrm_participant.contact_id = {$contactID} AND
1672 civicrm_participant.is_test = 0";
1673 return CRM_Core_DAO::singleValueQuery($query);
1674 }
1675
1676 /**
1677 * Function to get participant ids by contribution id
1678 *
1679 * @param int $contributionId Contribution Id
1680 * @param bool $excludeCancelled Exclude cancelled additional participant
1681 *
1682 * @return int $participantsId
1683 * @access public
1684 * @static
1685 */
1686 static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1687
1688 $ids = array();
1689 if (!$contributionId) {
1690 return $ids;
1691 }
1692
1693 // get primary participant id
1694 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1695 $participantId = CRM_Core_DAO::singleValueQuery($query);
1696
1697 // get additional participant ids (including cancelled)
1698 if ($participantId) {
1699 $ids = array_merge(array(
1700 $participantId), self::getAdditionalParticipantIds($participantId,
1701 $excludeCancelled
1702 ));
1703 }
1704
1705 return $ids;
1706 }
1707
1708 /**
1709 * Function to get additional Participant edit & view url .
1710 *
1711 * @param array $paticipantIds an array of additional participant ids.
1712 *
1713 * @return array of Urls.
1714 * @access public
1715 * @static
1716 */
1717 static function getAdditionalParticipantUrl($participantIds) {
1718 foreach ($participantIds as $value) {
1719 $links = array();
1720 $details = self::participantDetails($value);
1721 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1722 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1723 );
1724 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1725 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1726 );
1727 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1728 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1729 return $links;
1730 }
1731 }
1732
1733 /**
1734 * to create trxn entry if an event has discount.
1735 *
1736 * @param int $eventID event id
1737 * @param array $contributionParams contribution params.
1738 *
1739 * @static
1740 */
1741 static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1742 // CRM-11124
1743 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID,'civicrm_event');
1744 if (!empty($checkDiscount)) {
1745 $feeLevel = current($feeLevel);
1746 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
1747 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1748 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1749 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1750 $params = array(1 => array($priceSetId, 'Integer'),
1751 2 => array($feeLevel, 'String'));
1752 $mainAmount = CRM_Core_DAO::singleValueQuery($query, $params);
1753 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1754 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
1755 $contributionParams['contribution']->financial_type_id, $relationTypeId);
1756 if (CRM_Utils_Array::value('from_financial_account_id', $contributionParams['trxnParams'])) {
1757 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1758 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1759 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1760 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1761
1762 CRM_Core_BAO_FinancialTrxn::create($contributionParams['trxnParams']);
1763 }
1764 }
1765 return;
1766 }
1767
1768 /**
1769 * Function to delete participants of contact
1770 *
1771 * CRM-12155
1772 *
1773 * @param integer $contactId contact id
1774 *
1775 * @access public
1776 * @static
1777 */
1778 static function deleteContactParticipant($contactId) {
1779 $participant = new CRM_Event_DAO_Participant();
1780 $participant->contact_id = $contactId;
1781 $participant->find();
1782 while ($participant->fetch()) {
1783 self::deleteParticipant($participant->id);
1784 }
1785 }
1786 }
1787