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