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