Merge pull request #7095 from mjwright/online-pledge-payment-fix
[civicrm-core.git] / CRM / Event / BAO / Event.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33 class CRM_Event_BAO_Event extends CRM_Event_DAO_Event {
34
35 /**
36 * Class constructor.
37 */
38 public function __construct() {
39 parent::__construct();
40 }
41
42 /**
43 * Fetch object based on array of properties.
44 *
45 * @param array $params
46 * (reference ) an assoc array of name/value pairs.
47 * @param array $defaults
48 * (reference ) an assoc array to hold the flattened values.
49 *
50 * @return CRM_Event_DAO_Event
51 */
52 public static function retrieve(&$params, &$defaults) {
53 $event = new CRM_Event_DAO_Event();
54 $event->copyValues($params);
55 if ($event->find(TRUE)) {
56 CRM_Core_DAO::storeValues($event, $defaults);
57 return $event;
58 }
59 return NULL;
60 }
61
62 /**
63 * Update the is_active flag in the db.
64 *
65 * @param int $id
66 * Id of the database record.
67 * @param bool $is_active
68 * Value we want to set the is_active field.
69 *
70 * @return Object
71 * DAO object on success, null otherwise
72 */
73 public static function setIsActive($id, $is_active) {
74 return CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
75 }
76
77 /**
78 * Add the event.
79 *
80 * @param array $params
81 * Reference array contains the values submitted by the form.
82 *
83 * @return CRM_Event_DAO_Event
84 */
85 public static function add(&$params) {
86 CRM_Utils_System::flushCache();
87 $financialTypeId = NULL;
88 if (!empty($params['id'])) {
89 CRM_Utils_Hook::pre('edit', 'Event', $params['id'], $params);
90 if (empty($params['skipFinancialType'])) {
91 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
92 }
93 }
94 else {
95 CRM_Utils_Hook::pre('create', 'Event', NULL, $params);
96 }
97
98 $event = new CRM_Event_DAO_Event();
99
100 $event->copyValues($params);
101 $result = $event->save();
102
103 if (!empty($params['id'])) {
104 CRM_Utils_Hook::post('edit', 'Event', $event->id, $event);
105 }
106 else {
107 CRM_Utils_Hook::post('create', 'Event', $event->id, $event);
108 }
109 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
110 CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
111 }
112 return $result;
113 }
114
115 /**
116 * Create the event.
117 *
118 * @param array $params
119 * Reference array contains the values submitted by the form.
120 *
121 * @return object
122 */
123 public static function create(&$params) {
124 $transaction = new CRM_Core_Transaction();
125 if (empty($params['is_template'])) {
126 $params['is_template'] = 0;
127 }
128 // check if new event, if so set the created_id (if not set)
129 // and always set created_date to now
130 if (empty($params['id'])) {
131 if (empty($params['created_id'])) {
132 $session = CRM_Core_Session::singleton();
133 $params['created_id'] = $session->get('userID');
134 }
135 $params['created_date'] = date('YmdHis');
136 }
137
138 $event = self::add($params);
139 CRM_Price_BAO_PriceSet::setPriceSets($params, $event, 'event');
140 if (is_a($event, 'CRM_Core_Error')) {
141 CRM_Core_DAO::transaction('ROLLBACK');
142 return $event;
143 }
144
145 $session = CRM_Core_Session::singleton();
146 $contactId = $session->get('userID');
147 if (!$contactId) {
148 $contactId = CRM_Utils_Array::value('contact_id', $params);
149 }
150
151 // Log the information on successful add/edit of Event
152 $logParams = array(
153 'entity_table' => 'civicrm_event',
154 'entity_id' => $event->id,
155 'modified_id' => $contactId,
156 'modified_date' => date('Ymd'),
157 );
158
159 CRM_Core_BAO_Log::add($logParams);
160
161 if (!empty($params['custom']) &&
162 is_array($params['custom'])
163 ) {
164 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $event->id);
165 }
166
167 $transaction->commit();
168
169 return $event;
170 }
171
172 /**
173 * Delete the event.
174 *
175 * @param int $id
176 * Event id.
177 *
178 * @return mixed|null
179 */
180 public static function del($id) {
181 if (!$id) {
182 return NULL;
183 }
184
185 CRM_Utils_Hook::pre('delete', 'Event', $id, CRM_Core_DAO::$_nullArray);
186
187 $extends = array('event');
188 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
189 foreach ($groupTree as $values) {
190 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
191
192 $params = array(
193 1 => array($values['table_name'], 'string'),
194 2 => array($id, 'integer'),
195 );
196
197 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
198 }
199
200 // price set cleanup, CRM-5527
201 CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $id);
202
203 $event = new CRM_Event_DAO_Event();
204 $event->id = $id;
205
206 if ($event->find(TRUE)) {
207 $locBlockId = $event->loc_block_id;
208 $result = $event->delete();
209
210 if (!is_null($locBlockId)) {
211 self::deleteEventLocBlock($locBlockId, $id);
212 }
213
214 CRM_Utils_Hook::post('delete', 'Event', $id, $event);
215 return $result;
216 }
217
218 return NULL;
219 }
220
221 /**
222 * Delete the location block associated with an event.
223 *
224 * Function checks that it is not being used by any other event.
225 *
226 * @param int $locBlockId
227 * Location block id to be deleted.
228 * @param int $eventId
229 * Event with which loc block is associated.
230 */
231 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
232 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
233
234 if ($eventId) {
235 $query .= " AND ce.id != $eventId;";
236 }
237
238 $locCount = CRM_Core_DAO::singleValueQuery($query);
239
240 if ($locCount == 0) {
241 CRM_Core_BAO_Location::deleteLocBlock($locBlockId);
242 }
243 }
244
245 /**
246 * Get current/future Events.
247 *
248 * @param int $all
249 * 0 returns current and future events.
250 * 1 if events all are required
251 * 2 returns events since 3 months ago
252 * @param int|array $id single int event id or array of multiple event ids to return
253 * @param bool $isActive
254 * true if you need only active events.
255 * @param bool $checkPermission
256 * true if you need to check permission else false.
257 * @param bool $titleOnly
258 * true if you need only title not appended with start date
259 *
260 * @return array
261 */
262 public static function getEvents(
263 $all = 0,
264 $id = NULL,
265 $isActive = TRUE,
266 $checkPermission = TRUE,
267 $titleOnly = FALSE
268 ) {
269 $query = "
270 SELECT `id`, `title`, `start_date`
271 FROM `civicrm_event`
272 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
273
274 if (!empty($id)) {
275 $op = is_array($id) ? 'IN' : '=';
276 $where = CRM_Contact_BAO_Query::buildClause('id', $op, $id);
277 $query .= " AND {$where}";
278 }
279 elseif ($all == 0) {
280 // find only events ending in the future
281 $endDate = date('YmdHis');
282 $query .= "
283 AND ( `end_date` >= {$endDate} OR
284 (
285 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
286 )
287 )";
288 }
289 elseif ($all == 2) {
290 // find only events starting in the last 3 months
291 $startDate = date('YmdHis', strtotime('3 months ago'));
292 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
293 }
294 if ($isActive) {
295 $query .= " AND civicrm_event.is_active = 1";
296 }
297
298 $query .= " ORDER BY title asc";
299 $events = array();
300
301 $dao = CRM_Core_DAO::executeQuery($query);
302 while ($dao->fetch()) {
303 if ((!$checkPermission ||
304 CRM_Event_BAO_Event::checkPermission($dao->id)
305 ) &&
306 $dao->title
307 ) {
308 $events[$dao->id] = $dao->title;
309 if (!$titleOnly) {
310 $events[$dao->id] .= ' - ' . CRM_Utils_Date::customFormat($dao->start_date);
311 }
312 }
313 }
314
315 return $events;
316 }
317
318 /**
319 * Get events Summary.
320 *
321 * @return array
322 * Array of event summary values
323 */
324 public static function getEventSummary() {
325 $eventSummary = $eventIds = array();
326 $config = CRM_Core_Config::singleton();
327
328 // get permission and include them here
329 // does not scale, but rearranging code for now
330 // FIXME in a future release
331 $permissions = CRM_Event_BAO_Event::checkPermission();
332 $validEventIDs = '';
333 if (empty($permissions[CRM_Core_Permission::VIEW])) {
334 $eventSummary['total_events'] = 0;
335 return $eventSummary;
336 }
337 else {
338 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission::VIEW])) . " ) ";
339 }
340
341 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
342 $query = "
343 SELECT count(id) as total_events
344 FROM civicrm_event
345 WHERE civicrm_event.is_active = 1 AND
346 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
347 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
348 $validEventIDs";
349
350 $dao = CRM_Core_DAO::executeQuery($query);
351
352 if ($dao->fetch()) {
353 $eventSummary['total_events'] = $dao->total_events;
354 }
355
356 if (empty($eventSummary) ||
357 $dao->total_events == 0
358 ) {
359 return $eventSummary;
360 }
361
362 //get the participant status type values.
363 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
364 $cpst = $cpstObject->getTableName();
365 $query = "SELECT id, name, label, class FROM $cpst";
366 $status = CRM_Core_DAO::executeQuery($query);
367 $statusValues = array();
368 while ($status->fetch()) {
369 $statusValues[$status->id]['id'] = $status->id;
370 $statusValues[$status->id]['name'] = $status->name;
371 $statusValues[$status->id]['label'] = $status->label;
372 $statusValues[$status->id]['class'] = $status->class;
373 }
374
375 // Get the Id of Option Group for Event Types
376 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
377 $optionGroupDAO->name = 'event_type';
378 $optionGroupId = NULL;
379 if ($optionGroupDAO->find(TRUE)) {
380 $optionGroupId = $optionGroupDAO->id;
381 }
382 // Get the event summary display preferences
383 $show_max_events = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME,
384 'show_events'
385 );
386 // default to 10 if no option is set
387 if (is_null($show_max_events)) {
388 $show_max_events = 10;
389 }
390 // show all events if show_events is set to a negative value
391 if ($show_max_events >= 0) {
392 $event_summary_limit = "LIMIT 0, $show_max_events";
393 }
394 else {
395 $event_summary_limit = "";
396 }
397
398 $query = "
399 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
400 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
401 civicrm_event.end_date as end_date, civicrm_event.is_online_registration, civicrm_event.is_monetary, civicrm_event.is_show_location,civicrm_event.is_map as is_map, civicrm_option_value.label as event_type, civicrm_tell_friend.is_active as is_friend_active,
402 civicrm_event.slot_label_id,
403 civicrm_event.summary as summary,
404 civicrm_pcp_block.id as is_pcp_enabled,
405 civicrm_recurring_entity.parent_id as is_repeating_event
406 FROM civicrm_event
407 LEFT JOIN civicrm_option_value ON (
408 civicrm_event.event_type_id = civicrm_option_value.value AND
409 civicrm_option_value.option_group_id = %1 )
410 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
411 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
412 LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
413 WHERE civicrm_event.is_active = 1 AND
414 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
415 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
416 $validEventIDs
417 GROUP BY civicrm_event.id
418 ORDER BY civicrm_event.start_date ASC
419 $event_summary_limit
420 ";
421 $eventParticipant = array();
422
423 $properties = array(
424 'id' => 'id',
425 'eventTitle' => 'event_title',
426 'isPublic' => 'is_public',
427 'maxParticipants' => 'max_participants',
428 'startDate' => 'start_date',
429 'endDate' => 'end_date',
430 'eventType' => 'event_type',
431 'isMap' => 'is_map',
432 'participants' => 'participants',
433 'notCountedDueToRole' => 'notCountedDueToRole',
434 'notCountedDueToStatus' => 'notCountedDueToStatus',
435 'notCountedParticipants' => 'notCountedParticipants',
436 );
437
438 $params = array(1 => array($optionGroupId, 'Integer'));
439 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
440 'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
441 )));
442 $dao = CRM_Core_DAO::executeQuery($query, $params);
443 while ($dao->fetch()) {
444 foreach ($properties as $property => $name) {
445 $set = NULL;
446 switch ($name) {
447 case 'is_public':
448 if ($dao->$name) {
449 $set = 'Yes';
450 }
451 else {
452 $set = 'No';
453 }
454 $eventSummary['events'][$dao->id][$property] = $set;
455 break;
456
457 case 'is_map':
458 if ($dao->$name && $config->mapAPIKey) {
459 $values = array();
460 $ids = array();
461 $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_event');
462 $values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
463 if (is_numeric(CRM_Utils_Array::value('geo_code_1', $values['location']['address'][1])) ||
464 (
465 !empty($values['location']['address'][1]['city']) &&
466 !empty($values['location']['address'][1]['state_province_id'])
467 )
468 ) {
469 $set = CRM_Utils_System::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
470 }
471 }
472
473 $eventSummary['events'][$dao->id][$property] = $set;
474 if (is_array($permissions[CRM_Core_Permission::EDIT])
475 && in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
476 $eventSummary['events'][$dao->id]['configure'] = CRM_Utils_System::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
477 }
478 break;
479
480 case 'end_date':
481 case 'start_date':
482 $eventSummary['events'][$dao->id][$property] = CRM_Utils_Date::customFormat($dao->$name,
483 NULL, array('d')
484 );
485 break;
486
487 case 'participants':
488 case 'notCountedDueToRole':
489 case 'notCountedDueToStatus':
490 case 'notCountedParticipants':
491 $set = NULL;
492 $propertyCnt = 0;
493 if ($name == 'participants') {
494 $propertyCnt = self::getParticipantCount($dao->id);
495 if ($propertyCnt) {
496 $set = CRM_Utils_System::url('civicrm/event/search',
497 "reset=1&force=1&event=$dao->id&status=true&role=true"
498 );
499 }
500 }
501 elseif ($name == 'notCountedParticipants') {
502 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, TRUE, FALSE);
503 if ($propertyCnt) {
504 // FIXME : selector fail to search w/ OR operator.
505 // $set = CRM_Utils_System::url( 'civicrm/event/search',
506 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
507 }
508 }
509 elseif ($name == 'notCountedDueToStatus') {
510 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, FALSE, FALSE);
511 if ($propertyCnt) {
512 $set = CRM_Utils_System::url('civicrm/event/search',
513 "reset=1&force=1&event=$dao->id&status=false"
514 );
515 }
516 }
517 else {
518 $propertyCnt = self::getParticipantCount($dao->id, FALSE, FALSE, TRUE, FALSE);
519 if ($propertyCnt) {
520 $set = CRM_Utils_System::url('civicrm/event/search',
521 "reset=1&force=1&event=$dao->id&role=false"
522 );
523 }
524 }
525
526 $eventSummary['events'][$dao->id][$property] = $propertyCnt;
527 $eventSummary['events'][$dao->id][$name . '_url'] = $set;
528 break;
529
530 default:
531 $eventSummary['events'][$dao->id][$property] = $dao->$name;
532 break;
533 }
534 }
535
536 // prepare the area for per-status participant counts
537 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
538 $eventSummary['events'][$dao->id]['statuses'] = array_fill_keys($statusClasses, array());
539
540 $eventSummary['events'][$dao->id]['friend'] = $dao->is_friend_active;
541 $eventSummary['events'][$dao->id]['is_monetary'] = $dao->is_monetary;
542 $eventSummary['events'][$dao->id]['is_online_registration'] = $dao->is_online_registration;
543 $eventSummary['events'][$dao->id]['is_show_location'] = $dao->is_show_location;
544 $eventSummary['events'][$dao->id]['is_subevent'] = $dao->slot_label_id;
545 $eventSummary['events'][$dao->id]['is_pcp_enabled'] = $dao->is_pcp_enabled;
546 $eventSummary['events'][$dao->id]['reminder'] = CRM_Core_BAO_ActionSchedule::isConfigured($dao->id, $mapping->getId());
547 $eventSummary['events'][$dao->id]['is_repeating_event'] = $dao->is_repeating_event;
548
549 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
550 foreach ($statusValues as $statusId => $statusValue) {
551 if (!array_key_exists($statusId, $statusTypes)) {
552 continue;
553 }
554 $class = $statusValue['class'];
555 $statusCount = self::eventTotalSeats($dao->id, "( participant.status_id = {$statusId} )");
556 if ($statusCount) {
557 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
558 $statusInfo = array(
559 'url' => CRM_Utils_System::url('civicrm/event/search', $urlString),
560 'name' => $statusValue['name'],
561 'label' => $statusValue['label'],
562 'count' => $statusCount,
563 );
564 $eventSummary['events'][$dao->id]['statuses'][$class][] = $statusInfo;
565 }
566 }
567 }
568
569 $countedRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
570 $nonCountedRoles = CRM_Event_PseudoConstant::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
571 $countedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
572 $nonCountedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
573
574 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
575 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
576
577 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
578 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
579 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
580 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
581
582 return $eventSummary;
583 }
584
585 /**
586 * Get participant count.
587 *
588 * @param int $eventId
589 * @param bool $considerStatus consider status for participant count.
590 * Consider status for participant count.
591 * @param bool $status counted participant.
592 * Consider counted participant.
593 * @param bool $considerRole consider role for participant count.
594 * Consider role for participant count.
595 * @param bool $role consider counted( is filter role) participant.
596 * Consider counted( is filter role) participant.
597 *
598 * @return array
599 * array with count of participants for each event based on status/role
600 */
601 public static function getParticipantCount(
602 $eventId,
603 $considerStatus = TRUE,
604 $status = TRUE,
605 $considerRole = TRUE,
606 $role = TRUE
607 ) {
608
609 // consider both role and status for counted participants, CRM-4924.
610 $operator = " AND ";
611 // not counted participant.
612 if ($considerStatus && $considerRole && !$status && !$role) {
613 $operator = " OR ";
614 }
615 $clause = array();
616 if ($considerStatus) {
617 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
618 $statusClause = 'NOT IN';
619 if ($status) {
620 $statusClause = 'IN';
621 }
622 $status = implode(',', array_keys($statusTypes));
623 if (empty($status)) {
624 $status = 0;
625 }
626 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
627 }
628
629 if ($considerRole) {
630 $roleTypes = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
631 $roleClause = 'NOT IN';
632 if ($role) {
633 $roleClause = 'IN';
634 }
635
636 if (!empty($roleTypes)) {
637 $escapedRoles = array();
638 foreach (array_keys($roleTypes) as $roleType) {
639 $escapedRoles[] = CRM_Utils_Type::escape($roleType, 'String');
640 }
641
642 $clause[] = "participant.role_id {$roleClause} ( '" . implode("', '", $escapedRoles) . "' ) ";
643 }
644 }
645
646 $sqlClause = '';
647 if (!empty($clause)) {
648 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
649 }
650
651 return self::eventTotalSeats($eventId, $sqlClause);
652 }
653
654 /**
655 * Get the information to map a event.
656 *
657 * @param int $id
658 * For which we want map info.
659 *
660 * @return null|string
661 * title of the event
662 */
663 public static function &getMapInfo(&$id) {
664
665 $sql = "
666 SELECT
667 civicrm_event.id AS event_id,
668 civicrm_event.title AS display_name,
669 civicrm_address.street_address AS street_address,
670 civicrm_address.city AS city,
671 civicrm_address.postal_code AS postal_code,
672 civicrm_address.postal_code_suffix AS postal_code_suffix,
673 civicrm_address.geo_code_1 AS latitude,
674 civicrm_address.geo_code_2 AS longitude,
675 civicrm_state_province.abbreviation AS state,
676 civicrm_country.name AS country,
677 civicrm_location_type.name AS location_type
678 FROM
679 civicrm_event
680 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
681 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
682 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
683 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
684 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
685 WHERE civicrm_address.geo_code_1 IS NOT NULL
686 AND civicrm_address.geo_code_2 IS NOT NULL
687 AND civicrm_event.id = " . CRM_Utils_Type::escape($id, 'Integer');
688
689 $dao = new CRM_Core_DAO();
690 $dao->query($sql);
691
692 $locations = array();
693
694 $config = CRM_Core_Config::singleton();
695
696 while ($dao->fetch()) {
697
698 $location = array();
699 $location['displayName'] = addslashes($dao->display_name);
700 $location['lat'] = $dao->latitude;
701 $location['marker_class'] = 'Event';
702 $location['lng'] = $dao->longitude;
703
704 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
705 $addressValues = CRM_Core_BAO_Location::getValues($params, TRUE);
706 $location['address'] = str_replace(array(
707 "\r",
708 "\n",
709 ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
710
711 $location['url'] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id);
712 $location['location_type'] = $dao->location_type;
713 $eventImage = '<img src="' . $config->resourceBase . 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
714 $location['image'] = $eventImage;
715 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
716 $locations[] = $location;
717 }
718 return $locations;
719 }
720
721 /**
722 * Get the complete information for one or more events.
723 *
724 * @param date $start
725 * Get events with start date >= this date.
726 * @param int $type Get events on the a specific event type (by event_type_id).
727 * Get events on the a specific event type (by event_type_id).
728 * @param int $eventId Return a single event - by event id.
729 * Return a single event - by event id.
730 * @param date $end
731 * Also get events with end date >= this date.
732 * @param bool $onlyPublic Include public events only, default TRUE.
733 * Include public events only, default TRUE.
734 *
735 * @return array
736 * array of all the events that are searched
737 */
738 public static function &getCompleteInfo(
739 $start = NULL,
740 $type = NULL,
741 $eventId = NULL,
742 $end = NULL,
743 $onlyPublic = TRUE
744 ) {
745 $publicCondition = NULL;
746 if ($onlyPublic) {
747 $publicCondition = " AND civicrm_event.is_public = 1";
748 }
749
750 $dateCondition = '';
751 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
752 if ($start) {
753 // get events with start_date >= requested start
754 $startDate = CRM_Utils_Type::escape($start, 'Date');
755 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
756 }
757
758 if ($end) {
759 // also get events with end_date <= requested end
760 $endDate = CRM_Utils_Type::escape($end, 'Date');
761 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
762 }
763
764 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
765 // Need to exclude old events with only start date
766 // and not exclude events in progress (start <= today and end >= today). DGG
767 if (empty($start) && empty($end)) {
768 // get events with end date >= today, not sure of this logic
769 // but keeping this for backward compatibility as per issue CRM-5133
770 $today = date("Y-m-d G:i:s");
771 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
772 }
773
774 if ($type) {
775 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
776 }
777
778 // Get the Id of Option Group for Event Types
779 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
780 $optionGroupDAO->name = 'event_type';
781 $optionGroupId = NULL;
782 if ($optionGroupDAO->find(TRUE)) {
783 $optionGroupId = $optionGroupDAO->id;
784 }
785
786 $query = "
787 SELECT
788 civicrm_event.id as event_id,
789 civicrm_email.email as email,
790 civicrm_event.title as title,
791 civicrm_event.summary as summary,
792 civicrm_event.start_date as start,
793 civicrm_event.end_date as end,
794 civicrm_event.description as description,
795 civicrm_event.is_show_location as is_show_location,
796 civicrm_event.is_online_registration as is_online_registration,
797 civicrm_event.registration_link_text as registration_link_text,
798 civicrm_event.registration_start_date as registration_start_date,
799 civicrm_event.registration_end_date as registration_end_date,
800 civicrm_option_value.label as event_type,
801 civicrm_address.name as address_name,
802 civicrm_address.street_address as street_address,
803 civicrm_address.supplemental_address_1 as supplemental_address_1,
804 civicrm_address.supplemental_address_2 as supplemental_address_2,
805 civicrm_address.city as city,
806 civicrm_address.postal_code as postal_code,
807 civicrm_address.postal_code_suffix as postal_code_suffix,
808 civicrm_state_province.abbreviation as state,
809 civicrm_country.name AS country
810 FROM civicrm_event
811 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
812 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
813 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
814 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
815 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
816 LEFT JOIN civicrm_option_value ON (
817 civicrm_event.event_type_id = civicrm_option_value.value AND
818 civicrm_option_value.option_group_id = %1 )
819 WHERE civicrm_event.is_active = 1
820 AND (is_template = 0 OR is_template IS NULL)
821 {$publicCondition}
822 {$dateCondition}";
823
824 if (isset($typeCondition)) {
825 $query .= $typeCondition;
826 }
827
828 if (isset($eventId)) {
829 $query .= " AND civicrm_event.id =$eventId ";
830 }
831 $query .= " ORDER BY civicrm_event.start_date ASC";
832
833 $params = array(1 => array($optionGroupId, 'Integer'));
834 $dao = CRM_Core_DAO::executeQuery($query, $params);
835 $all = array();
836 $config = CRM_Core_Config::singleton();
837
838 $baseURL = parse_url($config->userFrameworkBaseURL);
839 $url = "@" . $baseURL['host'];
840 if (!empty($baseURL['path'])) {
841 $url .= substr($baseURL['path'], 0, -1);
842 }
843
844 // check 'view event info' permission
845 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
846 // and passing in the specific permission here will short-circuit the evaluation of permission to
847 // see specific events (doesn't seem relevant to this call
848 // however, since this function is accessed only by a convoluted call from a joomla block function
849 // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would
850 // be clearer & safer here
851 $permissions = CRM_Core_Permission::event(CRM_Core_Permission::VIEW);
852
853 // check if we're in shopping cart mode for events
854 $enable_cart = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME,
855 'enable_cart'
856 );
857 if ($enable_cart) {
858 }
859 while ($dao->fetch()) {
860 if (!empty($permissions) && in_array($dao->event_id, $permissions)) {
861 $info = array();
862 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL) . $url;
863
864 $info['title'] = $dao->title;
865 $info['event_id'] = $dao->event_id;
866 $info['summary'] = $dao->summary;
867 $info['description'] = $dao->description;
868 $info['start_date'] = $dao->start;
869 $info['end_date'] = $dao->end;
870 $info['contact_email'] = $dao->email;
871 $info['event_type'] = $dao->event_type;
872 $info['is_show_location'] = $dao->is_show_location;
873 $info['is_online_registration'] = $dao->is_online_registration;
874 $info['registration_link_text'] = $dao->registration_link_text;
875 $info['registration_start_date'] = $dao->registration_start_date;
876 $info['registration_end_date'] = $dao->registration_end_date;
877
878 $address = '';
879
880 $addrFields = array(
881 'address_name' => $dao->address_name,
882 'street_address' => $dao->street_address,
883 'supplemental_address_1' => $dao->supplemental_address_1,
884 'supplemental_address_2' => $dao->supplemental_address_2,
885 'city' => $dao->city,
886 'state_province' => $dao->state,
887 'postal_code' => $dao->postal_code,
888 'postal_code_suffix' => $dao->postal_code_suffix,
889 'country' => $dao->country,
890 'county' => NULL,
891 );
892
893 CRM_Utils_String::append($address, ', ',
894 CRM_Utils_Address::format($addrFields)
895 );
896 $info['location'] = $address;
897 $info['url'] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
898
899 if ($enable_cart) {
900 $reg = CRM_Event_Cart_BAO_EventInCart::get_registration_link($dao->event_id);
901 $info['registration_link'] = CRM_Utils_System::url($reg['path'], $reg['query'], TRUE);
902 $info['registration_link_text'] = $reg['label'];
903 }
904
905 $all[] = $info;
906 }
907 }
908
909 return $all;
910 }
911
912 /**
913 * Make a copy of a Event.
914 *
915 * Include all the fields in the event Wizard.
916 *
917 * @param int $id
918 * The event id to copy.
919 * boolean $afterCreate call to copy after the create function
920 * @param null $newEvent
921 * @param bool $afterCreate
922 *
923 * @return CRM_Event_DAO_Event
924 */
925 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
926
927 $eventValues = array();
928
929 //get the require event values.
930 $eventParams = array('id' => $id);
931 $returnProperties = array(
932 'loc_block_id',
933 'is_show_location',
934 'default_fee_id',
935 'default_discount_fee_id',
936 'is_template',
937 );
938
939 CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
940
941 // since the location is sharable, lets use the same loc_block_id.
942 $locBlockId = CRM_Utils_Array::value('loc_block_id', $eventValues);
943
944 $fieldsFix = ($afterCreate) ? array() : array('prefix' => array('title' => ts('Copy of') . ' '));
945 if (empty($eventValues['is_show_location'])) {
946 $fieldsFix['prefix']['is_show_location'] = 0;
947 }
948
949 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
950 $copyEvent = $newEvent;
951 }
952
953 if (!isset($copyEvent)) {
954 $copyEvent = &CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event',
955 array('id' => $id),
956 array(
957 'loc_block_id' =>
958 ($locBlockId) ? $locBlockId : NULL,
959 ),
960 $fieldsFix
961 );
962 }
963 CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_event', $id, $copyEvent->id);
964 $copyUF = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin',
965 array(
966 'entity_id' => $id,
967 'entity_table' => 'civicrm_event',
968 ),
969 array('entity_id' => $copyEvent->id)
970 );
971
972 $copyTellFriend = &CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend',
973 array(
974 'entity_id' => $id,
975 'entity_table' => 'civicrm_event',
976 ),
977 array('entity_id' => $copyEvent->id)
978 );
979
980 $copyPCP = &CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock',
981 array(
982 'entity_id' => $id,
983 'entity_table' => 'civicrm_event',
984 ),
985 array('entity_id' => $copyEvent->id),
986 array('replace' => array('target_entity_id' => $copyEvent->id))
987 );
988
989 $oldMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
990 'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
991 )));
992 $copyMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
993 'id' => ($copyEvent->is_template == 1 ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
994 )));
995 $copyReminder = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule',
996 array('entity_value' => $id, 'mapping_id' => $oldMapping->getId()),
997 array('entity_value' => $copyEvent->id, 'mapping_id' => $copyMapping->getId())
998 );
999
1000 if (!$afterCreate) {
1001 //copy custom data
1002 $extends = array('event');
1003 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
1004 if ($groupTree) {
1005 foreach ($groupTree as $groupID => $group) {
1006 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1007 foreach ($group['fields'] as $fieldID => $field) {
1008 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1009 }
1010 }
1011
1012 foreach ($table as $tableName => $tableColumns) {
1013 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1014 $tableColumns[0] = $copyEvent->id;
1015 $select = 'SELECT ' . implode(', ', $tableColumns);
1016 $from = ' FROM ' . $tableName;
1017 $where = " WHERE {$tableName}.entity_id = {$id}";
1018 $query = $insert . $select . $from . $where;
1019 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1020 }
1021 }
1022 }
1023 $copyEvent->save();
1024
1025 CRM_Utils_System::flushCache();
1026 if (!$afterCreate) {
1027 CRM_Utils_Hook::copy('Event', $copyEvent);
1028 }
1029 return $copyEvent;
1030 }
1031
1032 /**
1033 * This is sometimes called in a loop (during event search).
1034 *
1035 * We cache the values to prevent repeated calls to the db.
1036 *
1037 * @param int $id
1038 *
1039 * @return bool
1040 */
1041 public static function isMonetary($id) {
1042 static $isMonetary = array();
1043 if (!array_key_exists($id, $isMonetary)) {
1044 $isMonetary[$id] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1045 $id,
1046 'is_monetary'
1047 );
1048 }
1049 return $isMonetary[$id];
1050 }
1051
1052 /**
1053 * This is sometimes called in a loop (during event search).
1054 *
1055 * We cache the values to prevent repeated calls to the db.
1056 *
1057 * @param int $id
1058 *
1059 * @return bool
1060 */
1061 public static function usesPriceSet($id) {
1062 static $usesPriceSet = array();
1063 if (!array_key_exists($id, $usesPriceSet)) {
1064 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $id);
1065 }
1066 return $usesPriceSet[$id];
1067 }
1068
1069 /**
1070 * Send e-mails.
1071 *
1072 * @param int $contactID
1073 * @param array $values
1074 * @param int $participantId
1075 * @param bool $isTest
1076 * @param bool $returnMessageText
1077 */
1078 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1079
1080 $template = CRM_Core_Smarty::singleton();
1081 $gIds = array(
1082 'custom_pre_id' => $values['custom_pre_id'],
1083 'custom_post_id' => $values['custom_post_id'],
1084 );
1085
1086 //get the params submitted by participant.
1087 $participantParams = CRM_Utils_Array::value($participantId, $values['params'], array());
1088
1089 if (!$returnMessageText) {
1090 //send notification email if field values are set (CRM-1941)
1091 foreach ($gIds as $key => $gIdValues) {
1092 if ($gIdValues) {
1093 if (!is_array($gIdValues)) {
1094 $gIdValues = array($gIdValues);
1095 }
1096
1097 foreach ($gIdValues as $gId) {
1098 $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1099 if ($email) {
1100 //get values of corresponding profile fields for notification
1101 list($profileValues) = self::buildCustomDisplay($gId,
1102 NULL,
1103 $contactID,
1104 $template,
1105 $participantId,
1106 $isTest,
1107 TRUE,
1108 $participantParams
1109 );
1110 list($profileValues) = $profileValues;
1111 $val = array(
1112 'id' => $gId,
1113 'values' => $profileValues,
1114 'email' => $email,
1115 );
1116 CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
1117 }
1118 }
1119 }
1120 }
1121 }
1122
1123 if ($values['event']['is_email_confirm'] || $returnMessageText) {
1124 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
1125
1126 //send email only when email is present
1127 if (isset($email) || $returnMessageText) {
1128 $preProfileID = CRM_Utils_Array::value('custom_pre_id', $values);
1129 $postProfileID = CRM_Utils_Array::value('custom_post_id', $values);
1130
1131 if (!empty($values['params']['additionalParticipant'])) {
1132 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values, $preProfileID);
1133 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values, $postProfileID);
1134 }
1135
1136 self::buildCustomDisplay($preProfileID,
1137 'customPre',
1138 $contactID,
1139 $template,
1140 $participantId,
1141 $isTest,
1142 NULL,
1143 $participantParams
1144 );
1145
1146 self::buildCustomDisplay($postProfileID,
1147 'customPost',
1148 $contactID,
1149 $template,
1150 $participantId,
1151 $isTest,
1152 NULL,
1153 $participantParams
1154 );
1155
1156 $sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId);
1157
1158 $tplParams = array_merge($values, $participantParams, array(
1159 'email' => $email,
1160 'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $values['event']),
1161 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $values['event']),
1162 // The concept of contributeMode is deprecated.
1163 'contributeMode' => CRM_Utils_Array::value('contributeMode', $template->_tpl_vars),
1164 'participantID' => $participantId,
1165 'conference_sessions' => $sessions,
1166 'credit_card_number' =>
1167 CRM_Utils_System::mungeCreditCard(
1168 CRM_Utils_Array::value('credit_card_number', $participantParams)),
1169 'credit_card_exp_date' =>
1170 CRM_Utils_Date::mysqlToIso(
1171 CRM_Utils_Date::format(
1172 CRM_Utils_Array::value('credit_card_exp_date', $participantParams))),
1173 ));
1174
1175 // CRM-13890 : NOTE wait list condition need to be given so that
1176 // wait list message is shown properly in email i.e. WRT online event registration template
1177 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1178 $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
1179 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($statusId, NULL, 'label');
1180 }
1181 //CRM-15754 - if participant_status contains status ID
1182 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule::integer($tplParams['participant_status'])) {
1183 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($tplParams['participant_status'], NULL, 'label');
1184 }
1185
1186 $sendTemplateParams = array(
1187 'groupName' => 'msg_tpl_workflow_event',
1188 'valueName' => 'event_online_receipt',
1189 'contactId' => $contactID,
1190 'isTest' => $isTest,
1191 'tplParams' => $tplParams,
1192 'PDFFilename' => ts('confirmation') . '.pdf',
1193 );
1194
1195 // address required during receipt processing (pdf and email receipt)
1196 if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
1197 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1198 // The concept of contributeMode is deprecated.
1199 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1200 }
1201
1202 // set lineItem details
1203 if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) {
1204 // check if additional participant, if so filter only to relevant ones
1205 // CRM-9902
1206 if (!empty($values['params']['additionalParticipant'])) {
1207 $ownLineItems = array();
1208 foreach ($lineItem as $liKey => $liValue) {
1209 $firstElement = array_pop($liValue);
1210 if ($firstElement['entity_id'] == $participantId) {
1211 $ownLineItems[0] = $lineItem[$liKey];
1212 break;
1213 }
1214 }
1215 if (!empty($ownLineItems)) {
1216 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1217 }
1218 }
1219 else {
1220 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1221 }
1222 }
1223
1224 if ($returnMessageText) {
1225 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1226 return array(
1227 'subject' => $subject,
1228 'body' => $message,
1229 'to' => $displayName,
1230 'html' => $html,
1231 );
1232 }
1233 else {
1234 $sendTemplateParams['from'] = CRM_Utils_Array::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array::value('confirm_from_email', $values['event']) . ">";
1235 $sendTemplateParams['toName'] = $displayName;
1236 $sendTemplateParams['toEmail'] = $email;
1237 $sendTemplateParams['autoSubmitted'] = TRUE;
1238 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm',
1239 $values['event']
1240 );
1241 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm',
1242 $values['event']
1243 );
1244 // append invoice pdf to email
1245 $template = CRM_Core_Smarty::singleton();
1246 $taxAmt = $template->get_template_vars('totalTaxAmount');
1247 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1248 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1249 if (isset($invoicing) && isset($prefixValue['is_email_pdf']) && !empty($values['contributionId'])) {
1250 $sendTemplateParams['isEmailPdf'] = TRUE;
1251 $sendTemplateParams['contributionId'] = $values['contributionId'];
1252 }
1253 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1254 }
1255 }
1256 }
1257 }
1258
1259 /**
1260 * Add the custom fields OR array of participant's profile info.
1261 *
1262 * @param int $id
1263 * @param string $name
1264 * @param int $cid
1265 * @param string $template
1266 * @param int $participantId
1267 * @param bool $isTest
1268 * @param bool $isCustomProfile
1269 * @param array $participantParams
1270 *
1271 * @return array|null
1272 */
1273 public static function buildCustomDisplay(
1274 $id,
1275 $name,
1276 $cid,
1277 &$template,
1278 $participantId,
1279 $isTest,
1280 $isCustomProfile = FALSE,
1281 $participantParams = array()
1282 ) {
1283 if (!$id) {
1284 return array(NULL, NULL);
1285 }
1286
1287 if (!is_array($id)) {
1288 $id = CRM_Utils_Type::escape($id, 'Positive');
1289 $profileIds = array($id);
1290 }
1291 else {
1292 $profileIds = $id;
1293 }
1294
1295 $val = $groupTitles = NULL;
1296 foreach ($profileIds as $gid) {
1297 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
1298 $values = array();
1299 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW,
1300 NULL, NULL, FALSE, NULL,
1301 FALSE, NULL, CRM_Core_Permission::CREATE,
1302 'field_name', TRUE
1303 );
1304
1305 //this condition is added, since same contact can have multiple event registrations..
1306 $params = array(array('participant_id', '=', $participantId, 0, 0));
1307
1308 //add participant id
1309 $fields['participant_id'] = array(
1310 'name' => 'participant_id',
1311 'title' => ts('Participant ID'),
1312 );
1313 //check whether its a text drive
1314 if ($isTest) {
1315 $params[] = array('participant_test', '=', 1, 0, 0);
1316 }
1317
1318 //display campaign on thankyou page.
1319 if (array_key_exists('participant_campaign_id', $fields)) {
1320 if ($participantId) {
1321 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1322 $participantId,
1323 'campaign_id'
1324 );
1325 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1326 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array::value($campaignId,
1327 $campaigns
1328 );
1329 }
1330 unset($fields['participant_campaign_id']);
1331 }
1332
1333 $groupTitle = NULL;
1334 foreach ($fields as $k => $v) {
1335 if (!$groupTitle) {
1336 $groupTitle = $v['groupTitle'];
1337 }
1338 // suppress all file fields from display
1339 if (
1340 CRM_Utils_Array::value('data_type', $v, '') == 'File' ||
1341 CRM_Utils_Array::value('name', $v, '') == 'image_URL' ||
1342 CRM_Utils_Array::value('field_type', $v) == 'Formatting'
1343 ) {
1344 unset($fields[$k]);
1345 }
1346 }
1347
1348 if ($groupTitle) {
1349 $groupTitles[] = $groupTitle;
1350 }
1351 //display profile groups those are subscribed by participant.
1352 if (($groups = CRM_Utils_Array::value('group', $participantParams)) &&
1353 is_array($groups)
1354 ) {
1355 $grpIds = array();
1356 foreach ($groups as $grpId => $isSelected) {
1357 if ($isSelected) {
1358 $grpIds[] = $grpId;
1359 }
1360 }
1361 if (!empty($grpIds)) {
1362 //get the group titles.
1363 $grpTitles = array();
1364 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1365 $grp = CRM_Core_DAO::executeQuery($query);
1366 while ($grp->fetch()) {
1367 $grpTitles[] = $grp->title;
1368 }
1369 if (!empty($grpTitles) &&
1370 CRM_Utils_Array::value('title', CRM_Utils_Array::value('group', $fields))
1371 ) {
1372 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1373 }
1374 unset($fields['group']);
1375 }
1376 }
1377
1378 CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
1379
1380 if (isset($fields['participant_status_id']['title']) &&
1381 isset($values[$fields['participant_status_id']['title']]) &&
1382 is_numeric($values[$fields['participant_status_id']['title']])
1383 ) {
1384 $status = array();
1385 $status = CRM_Event_PseudoConstant::participantStatus();
1386 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1387 }
1388
1389 if (isset($fields['participant_role_id']['title']) &&
1390 isset($values[$fields['participant_role_id']['title']]) &&
1391 is_numeric($values[$fields['participant_role_id']['title']])
1392 ) {
1393 $roles = array();
1394 $roles = CRM_Event_PseudoConstant::participantRole();
1395 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1396 }
1397
1398 if (isset($fields['participant_register_date']['title']) &&
1399 isset($values[$fields['participant_register_date']['title']])
1400 ) {
1401 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date::customFormat($values[$fields['participant_register_date']['title']]);
1402 }
1403
1404 //handle fee_level for price set
1405 if (isset($fields['participant_fee_level']['title']) &&
1406 isset($values[$fields['participant_fee_level']['title']])
1407 ) {
1408 $feeLevel = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1409 $values[$fields['participant_fee_level']['title']]
1410 );
1411 foreach ($feeLevel as $key => $value) {
1412 if (!$value) {
1413 unset($feeLevel[$key]);
1414 }
1415 }
1416 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1417 }
1418
1419 unset($values[$fields['participant_id']['title']]);
1420
1421 $val[] = $values;
1422 }
1423 }
1424
1425 if (count($val)) {
1426 $template->assign($name, $val);
1427 }
1428
1429 if (count($groupTitles)) {
1430 $template->assign($name . '_grouptitle', $groupTitles);
1431 }
1432
1433 //return if we only require array of participant's info.
1434 if ($isCustomProfile) {
1435 if (count($val)) {
1436 return array($val, $groupTitles);
1437 }
1438 else {
1439 return NULL;
1440 }
1441 }
1442 }
1443
1444 /**
1445 * Build the array for display the profile fields.
1446 *
1447 * @param array $params
1448 * Key value.
1449 * @param int $gid
1450 * Profile Id.
1451 * @param array $groupTitle
1452 * Profile Group Title.
1453 * @param array $values
1454 * Formatted array of key value.
1455 *
1456 * @param array $profileFields
1457 */
1458 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1459 if ($gid) {
1460 $config = CRM_Core_Config::singleton();
1461 $session = CRM_Core_Session::singleton();
1462 $contactID = $session->get('userID');
1463 if ($contactID) {
1464 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
1465 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW);
1466 }
1467 }
1468 else {
1469 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD);
1470 }
1471
1472 foreach ($fields as $v) {
1473 if (!empty($v['groupTitle'])) {
1474 $groupTitle['groupTitle'] = $v['groupTitle'];
1475 break;
1476 }
1477 }
1478 $customVal = '';
1479 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1480 //start of code to set the default values
1481 foreach ($fields as $name => $field) {
1482 $skip = FALSE;
1483 // skip fields that should not be displayed separately
1484 if ($field['skipDisplay']) {
1485 continue;
1486 }
1487
1488 $index = $field['title'];
1489 if ($name === 'organization_name') {
1490 $values[$index] = $params[$name];
1491 }
1492
1493 if ('state_province' == substr($name, 0, 14)) {
1494 if ($params[$name]) {
1495 $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
1496 }
1497 else {
1498 $values[$index] = '';
1499 }
1500 }
1501 elseif ('date' == substr($name, -4)) {
1502 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]),
1503 $config->dateformatFull);
1504 }
1505 elseif ('country' == substr($name, 0, 7)) {
1506 if ($params[$name]) {
1507 $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
1508 }
1509 else {
1510 $values[$index] = '';
1511 }
1512 }
1513 elseif ('county' == substr($name, 0, 6)) {
1514 if ($params[$name]) {
1515 $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
1516 }
1517 else {
1518 $values[$index] = '';
1519 }
1520 }
1521 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1522 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1523 }
1524 elseif (in_array($name, array(
1525 'addressee',
1526 'email_greeting',
1527 'postal_greeting',
1528 ))) {
1529 $filterCondition = array('greeting_type' => $name);
1530 $greeting = CRM_Core_PseudoConstant::greeting($filterCondition);
1531 $values[$index] = $greeting[$params[$name]];
1532 }
1533 elseif ($name === 'preferred_communication_method') {
1534 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1535 $compref = array();
1536 $pref = $params[$name];
1537 if (is_array($pref)) {
1538 foreach ($pref as $k => $v) {
1539 if ($v) {
1540 $compref[] = $communicationFields[$k];
1541 }
1542 }
1543 }
1544 $values[$index] = implode(',', $compref);
1545 }
1546 elseif ($name == 'contact_sub_type') {
1547 $values[$index] = implode(', ', $params[$name]);
1548 }
1549 elseif ($name == 'group') {
1550 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
1551 $title = array();
1552 foreach ($params[$name] as $gId => $dontCare) {
1553 if ($dontCare) {
1554 $title[] = $groups[$gId];
1555 }
1556 }
1557 $values[$index] = implode(', ', $title);
1558 }
1559 elseif ($name == 'tag') {
1560 $entityTags = $params[$name];
1561 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1562 $title = array();
1563 if (is_array($entityTags)) {
1564 foreach ($entityTags as $tagId => $dontCare) {
1565 $title[] = $allTags[$tagId];
1566 }
1567 }
1568 $values[$index] = implode(', ', $title);
1569 }
1570 elseif ('participant_role_id' == $name OR
1571 'participant_role' == $name
1572 ) {
1573 $roles = CRM_Event_PseudoConstant::participantRole();
1574 $values[$index] = $roles[$params[$name]];
1575 }
1576 elseif ('participant_status_id' == $name OR
1577 'participant_status' == $name
1578 ) {
1579 $status = CRM_Event_PseudoConstant::participantStatus();
1580 $values[$index] = $status[$params[$name]];
1581 }
1582 elseif (substr($name, -11) == 'campaign_id') {
1583 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($params[$name]);
1584 $values[$index] = CRM_Utils_Array::value($params[$name], $campaigns);
1585 }
1586 elseif (strpos($name, '-') !== FALSE) {
1587 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
1588 $detailName = str_replace(' ', '_', $name);
1589 if (in_array($fieldName, array(
1590 'state_province',
1591 'country',
1592 'county',
1593 ))) {
1594 $values[$index] = $params[$detailName];
1595 $idx = $detailName . '_id';
1596 $values[$index] = $params[$idx];
1597 }
1598 elseif ($fieldName == 'im') {
1599 $providerName = NULL;
1600 if ($providerId = $detailName . '-provider_id') {
1601 $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
1602 }
1603 if ($providerName) {
1604 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1605 }
1606 else {
1607 $values[$index] = $params[$detailName];
1608 }
1609 }
1610 elseif ($fieldName == 'phone') {
1611 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1612 if (isset($params[$phoneExtField])) {
1613 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1614 }
1615 else {
1616 $values[$index] = $params[$detailName];
1617 }
1618 }
1619 else {
1620 $values[$index] = $params[$detailName];
1621 }
1622 }
1623 else {
1624 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1625 if ($params[$name]) {
1626 $values[$index] = '[ x ]';
1627 }
1628 }
1629 else {
1630 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
1631 $query = "
1632 SELECT html_type, data_type
1633 FROM civicrm_custom_field
1634 WHERE id = $cfID
1635 ";
1636 $dao = CRM_Core_DAO::executeQuery($query);
1637 $dao->fetch();
1638 $htmlType = $dao->html_type;
1639
1640 if ($htmlType == 'File') {
1641 $values[$index] = $params[$index];
1642 }
1643 else {
1644 if ($dao->data_type == 'Int' ||
1645 $dao->data_type == 'Boolean'
1646 ) {
1647 $v = $params[$name];
1648 if (!CRM_Utils_System::isNull($v)) {
1649 $customVal = (int) $v;
1650 }
1651 }
1652 elseif ($dao->data_type == 'Float') {
1653 $customVal = (float ) ($params[$name]);
1654 }
1655 elseif ($dao->data_type == 'Date') {
1656 //@todo note the currently we are using default date time formatting. Since you can select/set
1657 // different date and time format specific to custom field we should consider fixing this
1658 // sometime in the future
1659 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1660 CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
1661
1662 if (!empty($params[$name . '_time'])) {
1663 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1664 CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']),
1665 $config->dateformatDatetime);
1666 }
1667 $skip = TRUE;
1668 }
1669 else {
1670 $customVal = $params[$name];
1671 }
1672 //take the custom field options
1673 $returnProperties = array($name => 1);
1674 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1675 $options = &$query->_options;
1676 if (!$skip) {
1677 $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
1678 }
1679 //Hack since we dont have function to check empty.
1680 //FIXME in 2.3 using crmIsEmptyArray()
1681 $customValue = TRUE;
1682 if (is_array($customVal) && is_array($displayValue)) {
1683 $customValue = array_diff($customVal, $displayValue);
1684 }
1685 //use difference of arrays
1686 if (empty($customValue) || !$customValue) {
1687 $values[$index] = '';
1688 }
1689 else {
1690 $values[$index] = $displayValue;
1691 }
1692 }
1693 }
1694 elseif ($name == 'home_URL' &&
1695 !empty($params[$name])
1696 ) {
1697 $url = CRM_Utils_System::fixURL($params[$name]);
1698 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1699 }
1700 elseif (in_array($name, array(
1701 'birth_date',
1702 'deceased_date',
1703 'participant_register_date',
1704 ))) {
1705 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
1706 }
1707 else {
1708 $values[$index] = CRM_Utils_Array::value($name, $params);
1709 }
1710 }
1711 }
1712 $profileFields[$name] = $field;
1713 }
1714 }
1715 }
1716
1717 /**
1718 * Build the array for Additional participant's information array of primary and additional Ids.
1719 *
1720 * @param int $participantId
1721 * Id of Primary participant.
1722 * @param array $values
1723 * Key/value event info.
1724 * @param int $contactId
1725 * Contact id of Primary participant.
1726 * @param bool $isTest
1727 * Whether test or live transaction.
1728 * @param bool $isIdsArray
1729 * To return an array of Ids.
1730 *
1731 * @param bool $skipCancel
1732 *
1733 * @return array
1734 * array of Additional participant's info OR array of Ids.
1735 */
1736 public static function buildCustomProfile(
1737 $participantId,
1738 $values,
1739 $contactId = NULL,
1740 $isTest = FALSE,
1741 $isIdsArray = FALSE,
1742 $skipCancel = TRUE
1743 ) {
1744
1745 $customProfile = $additionalIDs = array();
1746 if (!$participantId) {
1747 CRM_Core_Error::fatal(ts('Cannot find participant ID'));
1748 }
1749
1750 //set Ids of Primary Participant also.
1751 if ($isIdsArray && $contactId) {
1752 $additionalIDs[$participantId] = $contactId;
1753 }
1754
1755 //hack to skip cancelled participants, CRM-4320
1756 $where = "participant.registered_by_id={$participantId}";
1757 if ($skipCancel) {
1758 $cancelStatusId = 0;
1759 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
1760 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1761 $where .= " AND participant.status_id != {$cancelStatusId}";
1762 }
1763 $query = "
1764 SELECT participant.id, participant.contact_id
1765 FROM civicrm_participant participant
1766 WHERE {$where}";
1767
1768 $dao = CRM_Core_DAO::executeQuery($query);
1769 while ($dao->fetch()) {
1770 $additionalIDs[$dao->id] = $dao->contact_id;
1771 }
1772
1773 //return if only array is required.
1774 if ($isIdsArray && $contactId) {
1775 return $additionalIDs;
1776 }
1777
1778 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values);
1779 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values);
1780 //else build array of Additional participant's information.
1781 if (count($additionalIDs)) {
1782 if ($preProfileID || $postProfileID) {
1783 $template = CRM_Core_Smarty::singleton();
1784
1785 $isCustomProfile = TRUE;
1786 $i = 1;
1787 $title = $groupTitles = array();
1788 foreach ($additionalIDs as $pId => $cId) {
1789 //get the params submitted by participant.
1790 $participantParams = CRM_Utils_Array::value($pId, $values['params'], array());
1791
1792 list($profilePre, $groupTitles) = self::buildCustomDisplay($preProfileID,
1793 'additionalCustomPre',
1794 $cId,
1795 $template,
1796 $pId,
1797 $isTest,
1798 $isCustomProfile,
1799 $participantParams
1800 );
1801
1802 if ($profilePre) {
1803 $profile = $profilePre;
1804 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1805 if ($i === 1) {
1806 $title = $groupTitles;
1807 }
1808 }
1809
1810 list($profilePost, $groupTitles) = self::buildCustomDisplay($postProfileID,
1811 'additionalCustomPost',
1812 $cId,
1813 $template,
1814 $pId,
1815 $isTest,
1816 $isCustomProfile,
1817 $participantParams
1818 );
1819
1820 if ($profilePost) {
1821 if (isset($profilePre)) {
1822 $profile = array_merge($profilePre, $profilePost);
1823 if ($i === 1) {
1824 $title = array_merge($title, $groupTitles);
1825 }
1826 }
1827 else {
1828 $profile = $profilePost;
1829 if ($i === 1) {
1830 $title = $groupTitles;
1831 }
1832 }
1833 }
1834 $profiles[] = $profile;
1835 $i++;
1836 }
1837 $customProfile['title'] = $title;
1838 $customProfile['profile'] = $profiles;
1839 }
1840 }
1841
1842 return $customProfile;
1843 }
1844
1845 /* Function to retrieve all events those having location block set.
1846 *
1847 * @return array
1848 * array of all events.
1849 */
1850 /**
1851 * @return array
1852 */
1853 public static function getLocationEvents() {
1854 $events = array();
1855
1856 $query = "
1857 SELECT CONCAT_WS(' :: ' , ca.name, ca.street_address, ca.city, sp.name, ca.supplemental_address_1, ca.supplemental_address_2) title, ce.loc_block_id
1858 FROM civicrm_event ce
1859 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1860 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1861 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1862 ORDER BY sp.name, ca.city, ca.street_address ASC
1863 ";
1864
1865 $dao = CRM_Core_DAO::executeQuery($query);
1866 while ($dao->fetch()) {
1867 $events[$dao->loc_block_id] = $dao->title;
1868 }
1869
1870 return $events;
1871 }
1872
1873 /**
1874 * @param int $locBlockId
1875 *
1876 * @return int|null|string
1877 */
1878 public static function countEventsUsingLocBlockId($locBlockId) {
1879 if (!$locBlockId) {
1880 return 0;
1881 }
1882
1883 $locBlockId = CRM_Utils_Type::escape($locBlockId, 'Integer');
1884
1885 $query = "
1886 SELECT count(*) FROM civicrm_event ce
1887 WHERE ce.loc_block_id = $locBlockId";
1888
1889 return CRM_Core_DAO::singleValueQuery($query);
1890 }
1891
1892 /**
1893 * Check if event registration is valid according to permissions AND Dates.
1894 *
1895 * @param array $values
1896 * @param int $eventID
1897 * @return bool
1898 */
1899 public static function validRegistrationRequest($values, $eventID) {
1900 // check that the user has permission to register for this event
1901 $hasPermission = CRM_Core_Permission::event(CRM_Core_Permission::EDIT,
1902 $eventID, 'register for events'
1903 );
1904
1905 return $hasPermission && self::validRegistrationDate($values);
1906 }
1907
1908 /**
1909 * @param $values
1910 *
1911 * @return bool
1912 */
1913 public static function validRegistrationDate(&$values) {
1914 // make sure that we are between registration start date and registration end date
1915 $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_start_date', $values));
1916 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_end_date', $values));
1917 $eventEnd = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $values));
1918 $now = time();
1919 $validDate = TRUE;
1920 if ($startDate && $startDate >= $now) {
1921 $validDate = FALSE;
1922 }
1923 if ($endDate && $endDate < $now && $eventEnd && $eventEnd < $now) {
1924 $validDate = FALSE;
1925 }
1926
1927 return $validDate;
1928 }
1929
1930 /* Function to Show - Hide the Registration Link.
1931 *
1932 * @param array $values
1933 * Key/value event info.
1934 * @return boolean
1935 * true if allow registration otherwise false
1936 */
1937 /**
1938 * @param $values
1939 *
1940 * @return bool
1941 */
1942 public static function showHideRegistrationLink($values) {
1943
1944 $session = CRM_Core_Session::singleton();
1945 $contactID = $session->get('userID');
1946 $alreadyRegistered = FALSE;
1947
1948 if ($contactID) {
1949 $params = array('contact_id' => $contactID);
1950
1951 if ($eventId = CRM_Utils_Array::value('id', $values['event'])) {
1952 $params['event_id'] = $eventId;
1953 }
1954 if ($roleId = CRM_Utils_Array::value('default_role_id', $values['event'])) {
1955 $params['role_id'] = $roleId;
1956 }
1957 $alreadyRegistered = self::checkRegistration($params);
1958 }
1959
1960 if (!empty($values['event']['allow_same_participant_emails']) ||
1961 !$alreadyRegistered
1962 ) {
1963 return TRUE;
1964 }
1965 return FALSE;
1966 }
1967
1968 /* Function to check if given contact is already registered.
1969 *
1970 * @param array $params
1971 * Key/value participant info.
1972 * @return boolean
1973 */
1974 /**
1975 * @param array $params
1976 *
1977 * @return bool
1978 */
1979 public static function checkRegistration($params) {
1980 $alreadyRegistered = FALSE;
1981 if (empty($params['contact_id'])) {
1982 return $alreadyRegistered;
1983 }
1984
1985 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
1986
1987 $participant = new CRM_Event_DAO_Participant();
1988 $participant->copyValues($params);
1989
1990 $participant->is_test = CRM_Utils_Array::value('is_test', $params, 0);
1991 $participant->selectAdd();
1992 $participant->selectAdd('status_id');
1993 if ($participant->find(TRUE) && array_key_exists($participant->status_id, $statusTypes)) {
1994 $alreadyRegistered = TRUE;
1995 }
1996
1997 return $alreadyRegistered;
1998 }
1999
2000 /**
2001 * Make sure that the user has permission to access this event.
2002 *
2003 * @param int $eventId
2004 * @param int $type
2005 *
2006 * @return string
2007 * the permission that the user has (or null)
2008 */
2009 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission::VIEW) {
2010 static $permissions = NULL;
2011
2012 if (empty($permissions)) {
2013 $allEvents = CRM_Event_PseudoConstant::event(NULL, TRUE);
2014 $createdEvents = array();
2015
2016 $session = CRM_Core_Session::singleton();
2017 if ($userID = $session->get('userID')) {
2018 $createdEvents = array_keys(CRM_Event_PseudoConstant::event(NULL, TRUE, "created_id={$userID}"));
2019 }
2020
2021 // Note: for a multisite setup, a user with edit all events, can edit all events
2022 // including those from other sites
2023 if (CRM_Core_Permission::check('edit all events')) {
2024 $permissions[CRM_Core_Permission::EDIT] = array_keys($allEvents);
2025 }
2026 else {
2027 $permissions[CRM_Core_Permission::EDIT] = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents);
2028 }
2029
2030 if (CRM_Core_Permission::check('edit all events')) {
2031 $permissions[CRM_Core_Permission::VIEW] = array_keys($allEvents);
2032 }
2033 else {
2034 if (CRM_Core_Permission::check('access CiviEvent') &&
2035 CRM_Core_Permission::check('view event participants')
2036 ) {
2037 // use case: allow "view all events" but NOT "edit all events"
2038 // so for a normal site allow users with these two permissions to view all events AND
2039 // at the same time also allow any hook to override if needed.
2040 $createdEvents = array_keys($allEvents);
2041 }
2042 $permissions[CRM_Core_Permission::VIEW] = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, $createdEvents);
2043 }
2044
2045 $permissions[CRM_Core_Permission::DELETE] = array();
2046 if (CRM_Core_Permission::check('delete in CiviEvent')) {
2047 // Note: we want to restrict the scope of delete permission to
2048 // events that are editable/viewable (usecase multisite).
2049 // We can remove array_intersect once we have ACL support for delete functionality.
2050 $permissions[CRM_Core_Permission::DELETE] = array_intersect($permissions[CRM_Core_Permission::EDIT],
2051 $permissions[CRM_Core_Permission::VIEW]
2052 );
2053 }
2054 }
2055
2056 if ($eventId) {
2057 return in_array($eventId, $permissions[$type]) ? TRUE : FALSE;
2058 }
2059
2060 return $permissions;
2061 }
2062
2063 /**
2064 * Build From Email as the combination of all the email ids of the logged in user,
2065 * the domain email id and the email id configured for the event
2066 *
2067 * @param int $eventId
2068 * The id of the event.
2069 *
2070 * @return array
2071 * an array of email ids
2072 */
2073 public static function getFromEmailIds($eventId = NULL) {
2074 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
2075
2076 if ($eventId) {
2077 // add the email id configured for the event
2078 $params = array('id' => $eventId);
2079 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
2080 $eventEmail = array();
2081
2082 CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2083 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2084 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2085
2086 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2087 $fromEmailId = array(
2088 'cc' => CRM_Utils_Array::value('cc_confirm', $eventEmail),
2089 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventEmail),
2090 );
2091 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2092 }
2093 }
2094
2095 return $fromEmailValues;
2096 }
2097
2098 /**
2099 * Calculate event total seats occupied.
2100 *
2101 * @param int $eventId
2102 * Event id.
2103 * @param sting $extraWhereClause
2104 * Extra filter on participants.
2105 *
2106 * @return int
2107 * event total seats w/ given criteria.
2108 */
2109 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2110 if (empty($eventId)) {
2111 return 0;
2112 }
2113
2114 $extraWhereClause = trim($extraWhereClause);
2115 if (!empty($extraWhereClause)) {
2116 $extraWhereClause = " AND ( {$extraWhereClause} )";
2117 }
2118
2119 //event seats calculation :
2120 //1. consider event seat as a single when participant does not have line item.
2121 //2. consider event seat as a single when participant has line items but does not
2122 // have count for corresponding price field value ( ie price field value does not carry any seat )
2123 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2124
2125 $query = "
2126 SELECT IF ( SUM( value.count*lineItem.qty ),
2127 SUM( value.count*lineItem.qty ) +
2128 COUNT( DISTINCT participant.id ) -
2129 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2130 COUNT( DISTINCT participant.id ) )
2131 FROM civicrm_participant participant
2132 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2133 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2134 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2135 AND lineItem.entity_table = 'civicrm_participant' )
2136 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2137 WHERE ( participant.event_id = %1 )
2138 AND participant.is_test = 0
2139 {$extraWhereClause}
2140 GROUP BY participant.event_id";
2141
2142 return (int) CRM_Core_DAO::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2143 }
2144
2145 /**
2146 * Retrieve event template default values to be set.
2147 * as default values for current new event.
2148 *
2149 * @param int $templateId
2150 * Event template id.
2151 *
2152 * @return array
2153 * Array of custom data defaults.
2154 */
2155 public static function getTemplateDefaultValues($templateId) {
2156 $defaults = array();
2157 if (!$templateId) {
2158 return $defaults;
2159 }
2160
2161 $templateParams = array('id' => $templateId);
2162 CRM_Event_BAO_Event::retrieve($templateParams, $defaults);
2163 $fieldsToExclude = array(
2164 'id',
2165 'default_fee_id',
2166 'default_discount_fee_id',
2167 'created_date',
2168 'created_id',
2169 'is_template',
2170 'template_title',
2171 );
2172 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2173 return $defaults;
2174 }
2175
2176 /**
2177 * @param int $event_id
2178 *
2179 * @return object
2180 */
2181 public static function get_sub_events($event_id) {
2182 $params = array('parent_event_id' => $event_id);
2183 $defaults = array();
2184 return CRM_Event_BAO_Event::retrieve($params, $defaults);
2185 }
2186
2187 /**
2188 * Update the Campaign Id of all the participants of the given event.
2189 *
2190 * @param int $eventID
2191 * Event id.
2192 * @param int $eventCampaignID
2193 * Campaign id of that event.
2194 */
2195 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2196 $params = array();
2197 $params[1] = array($eventID, 'Integer');
2198
2199 if (empty($eventCampaignID)) {
2200 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2201 }
2202 else {
2203 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2204 $params[2] = array($eventCampaignID, 'Integer');
2205 }
2206 CRM_Core_DAO::executeQuery($query, $params);
2207 }
2208
2209 /**
2210 * Get options for a given field.
2211 * @see CRM_Core_DAO::buildOptions
2212 *
2213 * @param string $fieldName
2214 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2215 * @param array $props : whatever is known about this dao object
2216 *
2217 * @return array|bool
2218 */
2219 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2220 $params = array();
2221 // Special logic for fields whose options depend on context or properties
2222 switch ($fieldName) {
2223 case 'financial_type_id':
2224 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2225 return CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
2226
2227 break;
2228 }
2229 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
2230 }
2231
2232 }