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