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