fix some spelling:
[civicrm-core.git] / CRM / Event / BAO / Event.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * @static
54 */
55 public static function retrieve(&$params, &$defaults) {
56 $event = new CRM_Event_DAO_Event();
57 $event->copyValues($params);
58 if ($event->find(TRUE)) {
59 CRM_Core_DAO::storeValues($event, $defaults);
60 return $event;
61 }
62 return NULL;
63 }
64
65 /**
66 * Update the is_active flag in the db
67 *
68 * @param int $id
69 * Id of the database record.
70 * @param bool $is_active
71 * Value we want to set the is_active field.
72 *
73 * @return Object
74 * DAO object on sucess, null otherwise
75 * @static
76 */
77 public static function setIsActive($id, $is_active) {
78 return CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
79 }
80
81 /**
82 * Add the event
83 *
84 * @param array $params
85 * Reference array contains the values submitted by the form.
86 *
87 * @static
88 *
89 * @return object
90 */
91 public static function add(&$params) {
92 CRM_Utils_System::flushCache();
93 $financialTypeId = NULL;
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook::pre('edit', 'Event', $params['id'], $params);
96 if (empty($params['skipFinancialType'])) {
97 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
98 }
99 }
100 else {
101 CRM_Utils_Hook::pre('create', 'Event', NULL, $params);
102 }
103
104 $event = new CRM_Event_DAO_Event();
105
106 $event->copyValues($params);
107 $result = $event->save();
108
109 if (!empty($params['id'])) {
110 CRM_Utils_Hook::post('edit', 'Event', $event->id, $event);
111 }
112 else {
113 CRM_Utils_Hook::post('create', 'Event', $event->id, $event);
114 }
115 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
116 CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
117 }
118 return $result;
119 }
120
121 /**
122 * Create the event
123 *
124 * @param array $params
125 * Reference array contains the values submitted by the form.
126 *
127 * @return object
128 * @static
129 */
130 public static function create(&$params) {
131 $transaction = new CRM_Core_Transaction();
132 if (empty($params['is_template'])) {
133 $params['is_template'] = 0;
134 }
135 // check if new event, if so set the created_id (if not set)
136 // and always set created_date to now
137 if (empty($params['id'])) {
138 if (empty($params['created_id'])) {
139 $session = CRM_Core_Session::singleton();
140 $params['created_id'] = $session->get('userID');
141 }
142 $params['created_date'] = date('YmdHis');
143 }
144
145 $event = self::add($params);
146 CRM_Price_BAO_PriceSet::setPriceSets($params, $event, 'event');
147 if (is_a($event, 'CRM_Core_Error')) {
148 CRM_Core_DAO::transaction('ROLLBACK');
149 return $event;
150 }
151
152 $session = CRM_Core_Session::singleton();
153 $contactId = $session->get('userID');
154 if (!$contactId) {
155 $contactId = CRM_Utils_Array::value('contact_id', $params);
156 }
157
158 // Log the information on successful add/edit of Event
159 $logParams = array(
160 'entity_table' => 'civicrm_event',
161 'entity_id' => $event->id,
162 'modified_id' => $contactId,
163 'modified_date' => date('Ymd'),
164 );
165
166 CRM_Core_BAO_Log::add($logParams);
167
168 if (!empty($params['custom']) &&
169 is_array($params['custom'])
170 ) {
171 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $event->id);
172 }
173
174 $transaction->commit();
175
176 return $event;
177 }
178
179 /**
180 * Delete the event
181 *
182 * @param int $id
183 * Event id.
184 *
185 * @return mixed|null
186 * @static
187 */
188 public static function del($id) {
189 if (!$id) {
190 return NULL;
191 }
192
193 CRM_Utils_Hook::pre('delete', 'Event', $id, CRM_Core_DAO::$_nullArray);
194
195 $extends = array('event');
196 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
197 foreach ($groupTree as $values) {
198 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
199
200 $params = array(
201 1 => array($values['table_name'], 'string'),
202 2 => array($id, 'integer'),
203 );
204
205 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
206 }
207
208 // price set cleanup, CRM-5527
209 CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $id);
210
211 $event = new CRM_Event_DAO_Event();
212 $event->id = $id;
213
214 if ($event->find(TRUE)) {
215 $locBlockId = $event->loc_block_id;
216 $result = $event->delete();
217
218 if (!is_null($locBlockId)) {
219 self::deleteEventLocBlock($locBlockId, $id);
220 }
221
222 CRM_Utils_Hook::post('delete', 'Event', $id, $event);
223 return $result;
224 }
225
226 return NULL;
227 }
228
229 /**
230 * Delete the location block associated with an event,
231 * if not being used by any other event.
232 *
233 * @param $locBlockId
234 * Location block id to be deleted.
235 * @param int $eventId
236 * Event with which loc block is associated.
237 *
238 * @static
239 */
240 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
241 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
242
243 if ($eventId) {
244 $query .= " AND ce.id != $eventId;";
245 }
246
247 $locCount = CRM_Core_DAO::singleValueQuery($query);
248
249 if ($locCount == 0) {
250 CRM_Core_BAO_Location::deleteLocBlock($locBlockId);
251 }
252 }
253
254 /**
255 * Get current/future Events
256 *
257 * @param int $all
258 * 0 returns current and future events.
259 * 1 if events all are required
260 * 2 returns events since 3 months ago
261 * @param bool|int $id int id of a specific event to return
262 * @param bool $isActive
263 * true if you need only active events.
264 * @param bool $checkPermission
265 * true if you need to check permission else false.
266 *
267 * @return array
268 * @static
269 */
270 static function getEvents(
271 $all = 0,
272 $id = FALSE,
273 $isActive = TRUE,
274 $checkPermission = TRUE
275 ) {
276 $query = "
277 SELECT `id`, `title`, `start_date`
278 FROM `civicrm_event`
279 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
280
281 if ($id) {
282 $query .= " AND `id` = {$id}";
283 }
284 elseif ($all == 0) {
285 // find only events ending in the future
286 $endDate = date('YmdHis');
287 $query .= "
288 AND ( `end_date` >= {$endDate} OR
289 (
290 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
291 )
292 )";
293 }
294 elseif ($all == 2) {
295 // find only events starting in the last 3 months
296 $startDate = date('YmdHis', strtotime('3 months ago'));
297 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
298 }
299 if ($isActive) {
300 $query .= " AND civicrm_event.is_active = 1";
301 }
302
303 $query .= " ORDER BY title asc";
304 $events = array();
305
306 $dao = CRM_Core_DAO::executeQuery($query);
307 while ($dao->fetch()) {
308 if ((!$checkPermission ||
309 CRM_Event_BAO_Event::checkPermission($dao->id)
310 ) &&
311 $dao->title
312 ) {
313 $events[$dao->id] = $dao->title . ' - ' . CRM_Utils_Date::customFormat($dao->start_date);
314 }
315 }
316
317 return $events;
318 }
319
320 /**
321 * Get events Summary
322 *
323 * @static
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 $mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', 'civicrm_event', 'id', 'entity_value');
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 ($config->mapGeoCoding &&
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 (in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
477 $eventSummary['events'][$dao->id]['configure'] = CRM_Utils_System::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
478 }
479 break;
480
481 case 'end_date':
482 case 'start_date':
483 $eventSummary['events'][$dao->id][$property] = CRM_Utils_Date::customFormat($dao->$name,
484 NULL, array('d')
485 );
486 break;
487
488 case 'participants':
489 case 'notCountedDueToRole':
490 case 'notCountedDueToStatus':
491 case 'notCountedParticipants':
492 $set = NULL;
493 $propertyCnt = 0;
494 if ($name == 'participants') {
495 $propertyCnt = self::getParticipantCount($dao->id);
496 if ($propertyCnt) {
497 $set = CRM_Utils_System::url('civicrm/event/search',
498 "reset=1&force=1&event=$dao->id&status=true&role=true"
499 );
500 }
501 }
502 elseif ($name == 'notCountedParticipants') {
503 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, TRUE, FALSE);
504 if ($propertyCnt) {
505 // FIXME : selector fail to search w/ OR operator.
506 // $set = CRM_Utils_System::url( 'civicrm/event/search',
507 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
508 }
509 }
510 elseif ($name == 'notCountedDueToStatus') {
511 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, FALSE, FALSE);
512 if ($propertyCnt) {
513 $set = CRM_Utils_System::url('civicrm/event/search',
514 "reset=1&force=1&event=$dao->id&status=false"
515 );
516 }
517 }
518 else {
519 $propertyCnt = self::getParticipantCount($dao->id, FALSE, FALSE, TRUE, FALSE);
520 if ($propertyCnt) {
521 $set = CRM_Utils_System::url('civicrm/event/search',
522 "reset=1&force=1&event=$dao->id&role=false"
523 );
524 }
525 }
526
527 $eventSummary['events'][$dao->id][$property] = $propertyCnt;
528 $eventSummary['events'][$dao->id][$name . '_url'] = $set;
529 break;
530
531 default:
532 $eventSummary['events'][$dao->id][$property] = $dao->$name;
533 break;
534 }
535 }
536
537 // prepare the area for per-status participant counts
538 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
539 $eventSummary['events'][$dao->id]['statuses'] = array_fill_keys($statusClasses, array());
540
541 $eventSummary['events'][$dao->id]['friend'] = $dao->is_friend_active;
542 $eventSummary['events'][$dao->id]['is_monetary'] = $dao->is_monetary;
543 $eventSummary['events'][$dao->id]['is_online_registration'] = $dao->is_online_registration;
544 $eventSummary['events'][$dao->id]['is_show_location'] = $dao->is_show_location;
545 $eventSummary['events'][$dao->id]['is_subevent'] = $dao->slot_label_id;
546 $eventSummary['events'][$dao->id]['is_pcp_enabled'] = $dao->is_pcp_enabled;
547 $eventSummary['events'][$dao->id]['reminder'] = CRM_Core_BAO_ActionSchedule::isConfigured($dao->id, $mappingID);
548 $eventSummary['events'][$dao->id]['is_repeating_event'] = $dao->is_repeating_event;
549
550 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
551 foreach ($statusValues as $statusId => $statusValue) {
552 if (!array_key_exists($statusId, $statusTypes)) {
553 continue;
554 }
555 $class = $statusValue['class'];
556 $statusCount = self::eventTotalSeats($dao->id, "( participant.status_id = {$statusId} )");
557 if ($statusCount) {
558 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
559 $statusInfo = array(
560 'url' => CRM_Utils_System::url('civicrm/event/search', $urlString),
561 'name' => $statusValue['name'],
562 'label' => $statusValue['label'],
563 'count' => $statusCount,
564 );
565 $eventSummary['events'][$dao->id]['statuses'][$class][] = $statusInfo;
566 }
567 }
568 }
569
570 $countedRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
571 $nonCountedRoles = CRM_Event_PseudoConstant::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
572 $countedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
573 $nonCountedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
574
575 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
576 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
577
578 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
579 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
580 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
581 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
582
583 return $eventSummary;
584 }
585
586 /**
587 * Get participant count
588 *
589 * @param int $eventId
590 * @param bool $considerStatusConsider status for participant count.
591 * Consider status for participant count.
592 * @param bool $statusConsider counted participant.
593 * Consider counted participant.
594 * @param bool $considerRoleConsider role for participant count.
595 * Consider role for participant count.
596 * @param bool $roleConsider counted( is filter role) participant.
597 * Consider counted( is filter role) participant.
598 *
599 *
600 * @return array
601 * array with count of participants for each event based on status/role
602 */
603 public static function getParticipantCount(
604 $eventId,
605 $considerStatus = TRUE,
606 $status = TRUE,
607 $considerRole = TRUE,
608 $role = TRUE
609 ) {
610
611 // consider both role and status for counted participants, CRM-4924.
612 $operator = " AND ";
613 // not counted participant.
614 if ($considerStatus && $considerRole && !$status && !$role) {
615 $operator = " OR ";
616 }
617 $clause = array();
618 if ($considerStatus) {
619 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
620 $statusClause = 'NOT IN';
621 if ($status) {
622 $statusClause = 'IN';
623 }
624 $status = implode(',', array_keys($statusTypes));
625 if (empty($status)) {
626 $status = 0;
627 }
628 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
629 }
630
631 if ($considerRole) {
632 $roleTypes = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
633 $roleClause = 'NOT IN';
634 if ($role) {
635 $roleClause = 'IN';
636 }
637 $roles = implode(',', array_keys($roleTypes));
638 if (empty($roles)) {
639 $roles = 0;
640 }
641 $clause[] = "participant.role_id {$roleClause} ( $roles )";
642 }
643
644 $sqlClause = '';
645 if (!empty($clause)) {
646 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
647 }
648
649 return self::eventTotalSeats($eventId, $sqlClause);
650 }
651
652 /**
653 * Get the information to map a event
654 *
655 * @param int $id
656 * For which we want map info.
657 *
658 * @return null|string
659 * title of the event
660 * @static
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 $typeGet 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 $eventIdReturn 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 $onlyPublicInclude 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 * @static
737 */
738 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 if ($eventValues['is_template']) {
989 $field = 'event_template';
990 }
991 else {
992 $field = 'civicrm_event';
993 }
994 $mappingId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
995 $oldData = array('entity_value' => $id, 'mapping_id' => $mappingId);
996 if ($copyEvent->is_template == 1) {
997 $field = 'event_template';
998 }
999 else {
1000 $field = 'civicrm_event';
1001 }
1002 $copyMappingId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
1003 $newData = array('entity_value' => $copyEvent->id, 'mapping_id' => $copyMappingId);
1004 $copyReminder = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule',
1005 $oldData,
1006 $newData
1007 );
1008
1009 if (!$afterCreate) {
1010 //copy custom data
1011 $extends = array('event');
1012 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
1013 if ($groupTree) {
1014 foreach ($groupTree as $groupID => $group) {
1015 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1016 foreach ($group['fields'] as $fieldID => $field) {
1017 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1018 }
1019 }
1020
1021 foreach ($table as $tableName => $tableColumns) {
1022 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1023 $tableColumns[0] = $copyEvent->id;
1024 $select = 'SELECT ' . implode(', ', $tableColumns);
1025 $from = ' FROM ' . $tableName;
1026 $where = " WHERE {$tableName}.entity_id = {$id}";
1027 $query = $insert . $select . $from . $where;
1028 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1029 }
1030 }
1031 }
1032 $copyEvent->save();
1033
1034 CRM_Utils_System::flushCache();
1035 if (!$afterCreate) {
1036 CRM_Utils_Hook::copy('Event', $copyEvent);
1037 }
1038 return $copyEvent;
1039 }
1040
1041 /**
1042 * This is sometimes called in a loop (during event search)
1043 * hence we cache the values to prevent repeated calls to the db
1044 */
1045 public static function isMonetary($id) {
1046 static $isMonetary = array();
1047 if (!array_key_exists($id, $isMonetary)) {
1048 $isMonetary[$id] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1049 $id,
1050 'is_monetary'
1051 );
1052 }
1053 return $isMonetary[$id];
1054 }
1055
1056 /**
1057 * This is sometimes called in a loop (during event search)
1058 * hence we cache the values to prevent repeated calls to the db
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 * Process that send e-mails
1070 *
1071 * @param int $contactID
1072 * @param $values
1073 * @param int $participantId
1074 * @param bool $isTest
1075 * @param bool $returnMessageText
1076 *
1077 * @return void
1078 */
1079 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1080
1081 $template = CRM_Core_Smarty::singleton();
1082 $gIds = array(
1083 'custom_pre_id' => $values['custom_pre_id'],
1084 'custom_post_id' => $values['custom_post_id'],
1085 );
1086
1087 //get the params submitted by participant.
1088 $participantParams = CRM_Utils_Array::value($participantId, $values['params'], array());
1089
1090 if (!$returnMessageText) {
1091 //send notification email if field values are set (CRM-1941)
1092 foreach ($gIds as $key => $gIdValues) {
1093 if ($gIdValues) {
1094 if (!is_array($gIdValues)) {
1095 $gIdValues = array($gIdValues);
1096 }
1097
1098 foreach ($gIdValues as $gId) {
1099 $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1100 if ($email) {
1101 //get values of corresponding profile fields for notification
1102 list($profileValues) = self::buildCustomDisplay($gId,
1103 NULL,
1104 $contactID,
1105 $template,
1106 $participantId,
1107 $isTest,
1108 TRUE,
1109 $participantParams
1110 );
1111 list($profileValues) = $profileValues;
1112 $val = array(
1113 'id' => $gId,
1114 'values' => $profileValues,
1115 'email' => $email,
1116 );
1117 CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
1118 }
1119 }
1120 }
1121 }
1122 }
1123
1124 if ($values['event']['is_email_confirm'] || $returnMessageText) {
1125 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
1126
1127 //send email only when email is present
1128 if (isset($email) || $returnMessageText) {
1129 $preProfileID = CRM_Utils_Array::value('custom_pre_id', $values);
1130 $postProfileID = CRM_Utils_Array::value('custom_post_id', $values);
1131
1132 if (!empty($values['params']['additionalParticipant'])) {
1133 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values, $preProfileID);
1134 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values, $postProfileID);
1135 }
1136
1137 self::buildCustomDisplay($preProfileID,
1138 'customPre',
1139 $contactID,
1140 $template,
1141 $participantId,
1142 $isTest,
1143 NULL,
1144 $participantParams
1145 );
1146
1147 self::buildCustomDisplay($postProfileID,
1148 'customPost',
1149 $contactID,
1150 $template,
1151 $participantId,
1152 $isTest,
1153 NULL,
1154 $participantParams
1155 );
1156
1157 $sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId);
1158
1159 $tplParams = array_merge($values, $participantParams, array(
1160 'email' => $email,
1161 'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $values['event']),
1162 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $values['event']),
1163 'contributeMode' => CRM_Utils_Array::value('contributeMode', $template->_tpl_vars),
1164 'participantID' => $participantId,
1165 'conference_sessions' => $sessions,
1166 'credit_card_number' =>
1167 CRM_Utils_System::mungeCreditCard(
1168 CRM_Utils_Array::value('credit_card_number', $participantParams)),
1169 'credit_card_exp_date' =>
1170 CRM_Utils_Date::mysqlToIso(
1171 CRM_Utils_Date::format(
1172 CRM_Utils_Array::value('credit_card_exp_date', $participantParams))),
1173 ));
1174
1175 // CRM-13890 : NOTE wait list condition need to be given so that
1176 // wait list message is shown properly in email i.e. WRT online event registration template
1177 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1178 $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id');
1179 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($statusId, NULL, 'label');
1180 }
1181 //CRM-15754 - if participant_status contains status ID
1182 elseif (CRM_Utils_Rule::integer($tplParams['participant_status'])) {
1183 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($tplParams['participant_status'], NULL, 'label');
1184 }
1185
1186 $sendTemplateParams = array(
1187 'groupName' => 'msg_tpl_workflow_event',
1188 'valueName' => 'event_online_receipt',
1189 'contactId' => $contactID,
1190 'isTest' => $isTest,
1191 'tplParams' => $tplParams,
1192 'PDFFilename' => ts('confirmation') . '.pdf',
1193 );
1194
1195 // address required during receipt processing (pdf and email receipt)
1196 if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
1197 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1198 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1199 }
1200
1201 // set lineItem details
1202 if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) {
1203 // check if additional prticipant, 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 ($taxAmt && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
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 * @return void
1272 */
1273 static function buildCustomDisplay(
1274 $id,
1275 $name,
1276 $cid,
1277 &$template,
1278 $participantId,
1279 $isTest,
1280 $isCustomProfile = FALSE,
1281 $participantParams = array()
1282 ) {
1283 if (!$id) {
1284 return array(NULL, NULL);
1285 }
1286
1287 if (!is_array($id)) {
1288 $id = CRM_Utils_Type::escape($id, 'Positive');
1289 $profileIds = array($id);
1290 }
1291 else {
1292 $profileIds = $id;
1293 }
1294
1295 foreach ($profileIds as $gid) {
1296 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
1297 $values = array();
1298 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW,
1299 NULL, NULL, FALSE, NULL,
1300 FALSE, NULL, CRM_Core_Permission::CREATE,
1301 'field_name', TRUE
1302 );
1303
1304 //this condition is added, since same contact can have multiple event registrations..
1305 $params = array(array('participant_id', '=', $participantId, 0, 0));
1306
1307 //add participant id
1308 $fields['participant_id'] = array(
1309 'name' => 'participant_id',
1310 'title' => ts('Participant ID'),
1311 );
1312 //check whether its a text drive
1313 if ($isTest) {
1314 $params[] = array('participant_test', '=', 1, 0, 0);
1315 }
1316
1317 //display campaign on thankyou page.
1318 if (array_key_exists('participant_campaign_id', $fields)) {
1319 if ($participantId) {
1320 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1321 $participantId,
1322 'campaign_id'
1323 );
1324 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1325 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array::value($campaignId,
1326 $campaigns
1327 );
1328 }
1329 unset($fields['participant_campaign_id']);
1330 }
1331
1332 $groupTitle = NULL;
1333 foreach ($fields as $k => $v) {
1334 if (!$groupTitle) {
1335 $groupTitle = $v['groupTitle'];
1336 }
1337 // suppress all file fields from display
1338 if (
1339 CRM_Utils_Array::value('data_type', $v, '') == 'File' ||
1340 CRM_Utils_Array::value('name', $v, '') == 'image_URL' ||
1341 CRM_Utils_Array::value('field_type', $v) == 'Formatting'
1342 ) {
1343 unset($fields[$k]);
1344 }
1345 }
1346
1347 if ($groupTitle) {
1348 $groupTitles[] = $groupTitle;
1349 }
1350 //display profile groups those are subscribed by participant.
1351 if (($groups = CRM_Utils_Array::value('group', $participantParams)) &&
1352 is_array($groups)
1353 ) {
1354 $grpIds = array();
1355 foreach ($groups as $grpId => $isSelected) {
1356 if ($isSelected) {
1357 $grpIds[] = $grpId;
1358 }
1359 }
1360 if (!empty($grpIds)) {
1361 //get the group titles.
1362 $grpTitles = array();
1363 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1364 $grp = CRM_Core_DAO::executeQuery($query);
1365 while ($grp->fetch()) {
1366 $grpTitles[] = $grp->title;
1367 }
1368 if (!empty($grpTitles) &&
1369 CRM_Utils_Array::value('title', CRM_Utils_Array::value('group', $fields))
1370 ) {
1371 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1372 }
1373 unset($fields['group']);
1374 }
1375 }
1376
1377 CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
1378
1379 if (isset($fields['participant_status_id']['title']) &&
1380 isset($values[$fields['participant_status_id']['title']]) &&
1381 is_numeric($values[$fields['participant_status_id']['title']])
1382 ) {
1383 $status = array();
1384 $status = CRM_Event_PseudoConstant::participantStatus();
1385 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1386 }
1387
1388 if (isset($fields['participant_role_id']['title']) &&
1389 isset($values[$fields['participant_role_id']['title']]) &&
1390 is_numeric($values[$fields['participant_role_id']['title']])
1391 ) {
1392 $roles = array();
1393 $roles = CRM_Event_PseudoConstant::participantRole();
1394 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1395 }
1396
1397 if (isset($fields['participant_register_date']['title']) &&
1398 isset($values[$fields['participant_register_date']['title']])
1399 ) {
1400 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date::customFormat($values[$fields['participant_register_date']['title']]);
1401 }
1402
1403 //handle fee_level for price set
1404 if (isset($fields['participant_fee_level']['title']) &&
1405 isset($values[$fields['participant_fee_level']['title']])
1406 ) {
1407 $feeLevel = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1408 $values[$fields['participant_fee_level']['title']]
1409 );
1410 foreach ($feeLevel as $key => $value) {
1411 if (!$value) {
1412 unset($feeLevel[$key]);
1413 }
1414 }
1415 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1416 }
1417
1418 unset($values[$fields['participant_id']['title']]);
1419
1420 $val[] = $values;
1421 }
1422 }
1423
1424 if (count($val)) {
1425 $template->assign($name, $val);
1426 }
1427
1428 if (count($groupTitles)) {
1429 $template->assign($name . '_grouptitle', $groupTitles);
1430 }
1431
1432 //return if we only require array of participant's info.
1433 if ($isCustomProfile) {
1434 if (count($val)) {
1435 return array($val, $groupTitles);
1436 }
1437 else {
1438 return NULL;
1439 }
1440 }
1441 }
1442
1443 /**
1444 * Build the array for display the profile fields
1445 *
1446 * @param array $params
1447 * Key value.
1448 * @param int $gid
1449 * Profile Id.
1450 * @param array $groupTitle
1451 * Profile Group Title.
1452 * @param array $values
1453 * Formatted array of key value.
1454 *
1455 * @param array $profileFields
1456 *
1457 * @return void
1458 * @static
1459 */
1460 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1461 if ($gid) {
1462 $config = CRM_Core_Config::singleton();
1463 $session = CRM_Core_Session::singleton();
1464 $contactID = $session->get('userID');
1465 if ($contactID) {
1466 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
1467 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW);
1468 }
1469 }
1470 else {
1471 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD);
1472 }
1473
1474 foreach ($fields as $v) {
1475 if (!empty($v['groupTitle'])) {
1476 $groupTitle['groupTitle'] = $v['groupTitle'];
1477 break;
1478 }
1479 }
1480 $customVal = '';
1481 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1482 //start of code to set the default values
1483 foreach ($fields as $name => $field) {
1484 $skip = FALSE;
1485 // skip fields that should not be displayed separately
1486 if ($field['skipDisplay']) {
1487 continue;
1488 }
1489
1490 $index = $field['title'];
1491 if ($name === 'organization_name') {
1492 $values[$index] = $params[$name];
1493 }
1494
1495 if ('state_province' == substr($name, 0, 14)) {
1496 if ($params[$name]) {
1497 $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
1498 }
1499 else {
1500 $values[$index] = '';
1501 }
1502 }
1503 elseif ('date' == substr($name, -4)) {
1504 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]),
1505 $config->dateformatFull);
1506 }
1507 elseif ('country' == substr($name, 0, 7)) {
1508 if ($params[$name]) {
1509 $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
1510 }
1511 else {
1512 $values[$index] = '';
1513 }
1514 }
1515 elseif ('county' == substr($name, 0, 6)) {
1516 if ($params[$name]) {
1517 $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
1518 }
1519 else {
1520 $values[$index] = '';
1521 }
1522 }
1523 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1524 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1525 }
1526 elseif (in_array($name, array(
1527 'addressee',
1528 'email_greeting',
1529 'postal_greeting',
1530 ))) {
1531 $filterCondition = array('greeting_type' => $name);
1532 $greeting = CRM_Core_PseudoConstant::greeting($filterCondition);
1533 $values[$index] = $greeting[$params[$name]];
1534 }
1535 elseif ($name === 'preferred_communication_method') {
1536 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1537 $compref = array();
1538 $pref = $params[$name];
1539 if (is_array($pref)) {
1540 foreach ($pref as $k => $v) {
1541 if ($v) {
1542 $compref[] = $communicationFields[$k];
1543 }
1544 }
1545 }
1546 $values[$index] = implode(',', $compref);
1547 }
1548 elseif ($name == 'contact_sub_type') {
1549 $values[$index] = implode(', ', $params[$name]);
1550 }
1551 elseif ($name == 'group') {
1552 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
1553 $title = array();
1554 foreach ($params[$name] as $gId => $dontCare) {
1555 if ($dontCare) {
1556 $title[] = $groups[$gId];
1557 }
1558 }
1559 $values[$index] = implode(', ', $title);
1560 }
1561 elseif ($name == 'tag') {
1562 $entityTags = $params[$name];
1563 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1564 $title = array();
1565 if (is_array($entityTags)) {
1566 foreach ($entityTags as $tagId => $dontCare) {
1567 $title[] = $allTags[$tagId];
1568 }
1569 }
1570 $values[$index] = implode(', ', $title);
1571 }
1572 elseif ('participant_role_id' == $name OR
1573 'participant_role' == $name
1574 ) {
1575 $roles = CRM_Event_PseudoConstant::participantRole();
1576 $values[$index] = $roles[$params[$name]];
1577 }
1578 elseif ('participant_status_id' == $name OR
1579 'participant_status' == $name
1580 ) {
1581 $status = CRM_Event_PseudoConstant::participantStatus();
1582 $values[$index] = $status[$params[$name]];
1583 }
1584 elseif (substr($name, -11) == 'campaign_id') {
1585 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($params[$name]);
1586 $values[$index] = CRM_Utils_Array::value($params[$name], $campaigns);
1587 }
1588 elseif (strpos($name, '-') !== FALSE) {
1589 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
1590 $detailName = str_replace(' ', '_', $name);
1591 if (in_array($fieldName, array(
1592 'state_province',
1593 'country',
1594 'county',
1595 ))) {
1596 $values[$index] = $params[$detailName];
1597 $idx = $detailName . '_id';
1598 $values[$index] = $params[$idx];
1599 }
1600 elseif ($fieldName == 'im') {
1601 $providerName = NULL;
1602 if ($providerId = $detailName . '-provider_id') {
1603 $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
1604 }
1605 if ($providerName) {
1606 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1607 }
1608 else {
1609 $values[$index] = $params[$detailName];
1610 }
1611 }
1612 elseif ($fieldName == 'phone') {
1613 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1614 if (isset($params[$phoneExtField])) {
1615 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1616 }
1617 else {
1618 $values[$index] = $params[$detailName];
1619 }
1620 }
1621 else {
1622 $values[$index] = $params[$detailName];
1623 }
1624 }
1625 else {
1626 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1627 if ($params[$name]) {
1628 $values[$index] = '[ x ]';
1629 }
1630 }
1631 else {
1632 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
1633 $query = "
1634 SELECT html_type, data_type
1635 FROM civicrm_custom_field
1636 WHERE id = $cfID
1637 ";
1638 $dao = CRM_Core_DAO::executeQuery($query);
1639 $dao->fetch();
1640 $htmlType = $dao->html_type;
1641
1642 if ($htmlType == 'File') {
1643 $values[$index] = $params[$index];
1644 }
1645 else {
1646 if ($dao->data_type == 'Int' ||
1647 $dao->data_type == 'Boolean'
1648 ) {
1649 $v = $params[$name];
1650 if (!CRM_Utils_System::isNull($v)) {
1651 $customVal = (int) $v;
1652 }
1653 }
1654 elseif ($dao->data_type == 'Float') {
1655 $customVal = (float ) ($params[$name]);
1656 }
1657 elseif ($dao->data_type == 'Date') {
1658 //@todo note the currently we are using default date time formatting. Since you can select/set
1659 // different date and time format specific to custom field we should consider fixing this
1660 // sometime in the future
1661 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1662 CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
1663
1664 if (!empty($params[$name . '_time'])) {
1665 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1666 CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']),
1667 $config->dateformatDatetime);
1668 }
1669 $skip = TRUE;
1670 }
1671 else {
1672 $customVal = $params[$name];
1673 }
1674 //take the custom field options
1675 $returnProperties = array($name => 1);
1676 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1677 $options = &$query->_options;
1678 if (!$skip) {
1679 $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
1680 }
1681 //Hack since we dont have function to check empty.
1682 //FIXME in 2.3 using crmIsEmptyArray()
1683 $customValue = TRUE;
1684 if (is_array($customVal) && is_array($displayValue)) {
1685 $customValue = array_diff($customVal, $displayValue);
1686 }
1687 //use difference of arrays
1688 if (empty($customValue) || !$customValue) {
1689 $values[$index] = '';
1690 }
1691 else {
1692 $values[$index] = $displayValue;
1693 }
1694 }
1695 }
1696 elseif ($name == 'home_URL' &&
1697 !empty($params[$name])
1698 ) {
1699 $url = CRM_Utils_System::fixURL($params[$name]);
1700 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1701 }
1702 elseif (in_array($name, array(
1703 'birth_date',
1704 'deceased_date',
1705 'participant_register_date',
1706 ))) {
1707 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
1708 }
1709 else {
1710 $values[$index] = $params[$name];
1711 }
1712 }
1713 }
1714 $profileFields[$name] = $field;
1715 }
1716 }
1717 }
1718
1719 /**
1720 * Build the array for Additional participant's information array of priamry and additional Ids
1721 *
1722 * @param int $participantId
1723 * Id of Primary participant.
1724 * @param array $values
1725 * Key/value event info.
1726 * @param int $contactId
1727 * Contact id of Primary participant.
1728 * @param bool $isTest
1729 * Whether test or live transaction.
1730 * @param bool $isIdsArray
1731 * To return an array of Ids.
1732 *
1733 * @param bool $skipCancel
1734 *
1735 * @return array
1736 * array of Additional participant's info OR array of Ids.
1737 */
1738 static function buildCustomProfile(
1739 $participantId,
1740 $values,
1741 $contactId = NULL,
1742 $isTest = FALSE,
1743 $isIdsArray = FALSE,
1744 $skipCancel = TRUE
1745 ) {
1746
1747 $customProfile = $additionalIDs = array();
1748 if (!$participantId) {
1749 CRM_Core_Error::fatal(ts('Cannot find participant ID'));
1750 }
1751
1752 //set Ids of Primary Participant also.
1753 if ($isIdsArray && $contactId) {
1754 $additionalIDs[$participantId] = $contactId;
1755 }
1756
1757 //hack to skip cancelled participants, CRM-4320
1758 $where = "participant.registered_by_id={$participantId}";
1759 if ($skipCancel) {
1760 $cancelStatusId = 0;
1761 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
1762 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1763 $where .= " AND participant.status_id != {$cancelStatusId}";
1764 }
1765 $query = "
1766 SELECT participant.id, participant.contact_id
1767 FROM civicrm_participant participant
1768 WHERE {$where}";
1769
1770 $dao = CRM_Core_DAO::executeQuery($query);
1771 while ($dao->fetch()) {
1772 $additionalIDs[$dao->id] = $dao->contact_id;
1773 }
1774
1775 //return if only array is required.
1776 if ($isIdsArray && $contactId) {
1777 return $additionalIDs;
1778 }
1779
1780 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values);
1781 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values);
1782 //else build array of Additional participant's information.
1783 if (count($additionalIDs)) {
1784 if ($preProfileID || $postProfileID) {
1785 $template = CRM_Core_Smarty::singleton();
1786
1787 $isCustomProfile = TRUE;
1788 $i = 1;
1789 $title = $groupTitles = array();
1790 foreach ($additionalIDs as $pId => $cId) {
1791 //get the params submitted by participant.
1792 $participantParams = CRM_Utils_Array::value($pId, $values['params'], array());
1793
1794 list($profilePre, $groupTitles) = self::buildCustomDisplay($preProfileID,
1795 'additionalCustomPre',
1796 $cId,
1797 $template,
1798 $pId,
1799 $isTest,
1800 $isCustomProfile,
1801 $participantParams
1802 );
1803
1804 if ($profilePre) {
1805 $profile = $profilePre;
1806 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1807 if ($i === 1) {
1808 $title = $groupTitles;
1809 }
1810 }
1811
1812 list($profilePost, $groupTitles) = self::buildCustomDisplay($postProfileID,
1813 'additionalCustomPost',
1814 $cId,
1815 $template,
1816 $pId,
1817 $isTest,
1818 $isCustomProfile,
1819 $participantParams
1820 );
1821
1822 if ($profilePost) {
1823 if (isset($profilePre)) {
1824 $profile = array_merge($profilePre, $profilePost);
1825 if ($i === 1) {
1826 $title = array_merge($title, $groupTitles);
1827 }
1828 }
1829 else {
1830 $profile = $profilePost;
1831 if ($i === 1) {
1832 $title = $groupTitles;
1833 }
1834 }
1835 }
1836 $profiles[] = $profile;
1837 $i++;
1838 }
1839 $customProfile['title'] = $title;
1840 $customProfile['profile'] = $profiles;
1841 }
1842 }
1843
1844 return $customProfile;
1845 }
1846
1847 /* Function to retrieve all events those having location block set.
1848 *
1849 * @return array
1850 * array of all events.
1851 */
1852 /**
1853 * @return array
1854 */
1855 public static function getLocationEvents() {
1856 $events = array();
1857
1858 $query = "
1859 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
1860 FROM civicrm_event ce
1861 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1862 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1863 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1864 ORDER BY sp.name, ca.city, ca.street_address ASC
1865 ";
1866
1867 $dao = CRM_Core_DAO::executeQuery($query);
1868 while ($dao->fetch()) {
1869 $events[$dao->loc_block_id] = $dao->title;
1870 }
1871
1872 return $events;
1873 }
1874
1875 /**
1876 * @param int $locBlockId
1877 *
1878 * @return int|null|string
1879 */
1880 public static function countEventsUsingLocBlockId($locBlockId) {
1881 if (!$locBlockId) {
1882 return 0;
1883 }
1884
1885 $locBlockId = CRM_Utils_Type::escape($locBlockId, 'Integer');
1886
1887 $query = "
1888 SELECT count(*) FROM civicrm_event ce
1889 WHERE ce.loc_block_id = $locBlockId";
1890
1891 return CRM_Core_DAO::singleValueQuery($query);
1892 }
1893
1894 /**
1895 * Check if event registration is valid according to permissions AND Dates
1896 *
1897 * @param array $values
1898 * @param int $eventID
1899 * @return boolean
1900 */
1901 public static function validRegistrationRequest($values, $eventID) {
1902 // check that the user has permission to register for this event
1903 $hasPermission = CRM_Core_Permission::event(CRM_Core_Permission::EDIT,
1904 $eventID, 'register for events'
1905 );
1906
1907 return $hasPermission && self::validRegistrationDate($values);
1908 }
1909
1910 /**
1911 * @param $values
1912 *
1913 * @return bool
1914 */
1915 public static function validRegistrationDate(&$values) {
1916 // make sure that we are between registration start date and registration end date
1917 $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_start_date', $values));
1918 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_end_date', $values));
1919 $eventEnd = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $values));
1920 $now = time();
1921 $validDate = TRUE;
1922 if ($startDate && $startDate >= $now) {
1923 $validDate = FALSE;
1924 }
1925 if ($endDate && $endDate < $now) {
1926 $validDate = FALSE;
1927 }
1928 if ($eventEnd && $eventEnd < $now) {
1929 $validDate = FALSE;
1930 }
1931
1932 return $validDate;
1933 }
1934
1935 /* Function to Show - Hide the Registration Link.
1936 *
1937 * @param array $values
1938 * Key/value event info.
1939 * @return boolean
1940 * true if allow registration otherwise false
1941 */
1942 /**
1943 * @param $values
1944 *
1945 * @return bool
1946 */
1947 public static function showHideRegistrationLink($values) {
1948
1949 $session = CRM_Core_Session::singleton();
1950 $contactID = $session->get('userID');
1951 $alreadyRegistered = FALSE;
1952
1953 if ($contactID) {
1954 $params = array('contact_id' => $contactID);
1955
1956 if ($eventId = CRM_Utils_Array::value('id', $values['event'])) {
1957 $params['event_id'] = $eventId;
1958 }
1959 if ($roleId = CRM_Utils_Array::value('default_role_id', $values['event'])) {
1960 $params['role_id'] = $roleId;
1961 }
1962 $alreadyRegistered = self::checkRegistration($params);
1963 }
1964
1965 if (!empty($values['event']['allow_same_participant_emails']) ||
1966 !$alreadyRegistered
1967 ) {
1968 return TRUE;
1969 }
1970 return FALSE;
1971 }
1972
1973 /* Function to check if given contact is already registered.
1974 *
1975 * @param array $params
1976 * Key/value participant info.
1977 * @return boolean
1978 */
1979 /**
1980 * @param array $params
1981 *
1982 * @return bool
1983 */
1984 public static function checkRegistration($params) {
1985 $alreadyRegistered = FALSE;
1986 if (empty($params['contact_id'])) {
1987 return $alreadyRegistered;
1988 }
1989
1990 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
1991
1992 $participant = new CRM_Event_DAO_Participant();
1993 $participant->copyValues($params);
1994
1995 $participant->is_test = CRM_Utils_Array::value('is_test', $params, 0);
1996 $participant->selectAdd();
1997 $participant->selectAdd('status_id');
1998 if ($participant->find(TRUE) && array_key_exists($participant->status_id, $statusTypes)) {
1999 $alreadyRegistered = TRUE;
2000 }
2001
2002 return $alreadyRegistered;
2003 }
2004
2005 /**
2006 * Make sure that the user has permission to access this event
2007 *
2008 * @param int $eventId
2009 * @param int $type
2010 *
2011 * @return string
2012 * the permission that the user has (or null)
2013 * @static
2014 */
2015 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission::VIEW) {
2016 static $permissions = NULL;
2017
2018 if (empty($permissions)) {
2019 $allEvents = CRM_Event_PseudoConstant::event(NULL, TRUE);
2020 $createdEvents = array();
2021
2022 $session = CRM_Core_Session::singleton();
2023 if ($userID = $session->get('userID')) {
2024 $createdEvents = array_keys(CRM_Event_PseudoConstant::event(NULL, TRUE, "created_id={$userID}"));
2025 }
2026
2027 // Note: for a multisite setup, a user with edit all events, can edit all events
2028 // including those from other sites
2029 if (CRM_Core_Permission::check('edit all events')) {
2030 $permissions[CRM_Core_Permission::EDIT] = array_keys($allEvents);
2031 }
2032 else {
2033 $permissions[CRM_Core_Permission::EDIT] = &CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents);
2034 }
2035
2036 if (CRM_Core_Permission::check('edit all events')) {
2037 $permissions[CRM_Core_Permission::VIEW] = array_keys($allEvents);
2038 }
2039 else {
2040 if (CRM_Core_Permission::check('access CiviEvent') &&
2041 CRM_Core_Permission::check('view event participants')
2042 ) {
2043 // use case: allow "view all events" but NOT "edit all events"
2044 // so for a normal site allow users with these two permissions to view all events AND
2045 // at the same time also allow any hook to override if needed.
2046 $createdEvents = array_keys($allEvents);
2047 }
2048 $permissions[CRM_Core_Permission::VIEW] = &CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, $createdEvents);
2049 }
2050
2051 $permissions[CRM_Core_Permission::DELETE] = array();
2052 if (CRM_Core_Permission::check('delete in CiviEvent')) {
2053 // Note: we want to restrict the scope of delete permission to
2054 // events that are editable/viewable (usecase multisite).
2055 // We can remove array_intersect once we have ACL support for delete functionality.
2056 $permissions[CRM_Core_Permission::DELETE] = array_intersect($permissions[CRM_Core_Permission::EDIT],
2057 $permissions[CRM_Core_Permission::VIEW]
2058 );
2059 }
2060 }
2061
2062 if ($eventId) {
2063 return in_array($eventId, $permissions[$type]) ? TRUE : FALSE;
2064 }
2065
2066 return $permissions;
2067 }
2068
2069 /**
2070 * Build From Email as the combination of all the email ids of the logged in user,
2071 * the domain email id and the email id configured for the event
2072 *
2073 * @param int $eventId
2074 * The id of the event.
2075 *
2076 * @return array
2077 * an array of email ids
2078 * @static
2079 */
2080 public static function getFromEmailIds($eventId = NULL) {
2081 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
2082
2083 if ($eventId) {
2084 // add the email id configured for the event
2085 $params = array('id' => $eventId);
2086 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
2087 $eventEmail = array();
2088
2089 CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2090 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2091 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2092
2093 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2094 $fromEmailId = array(
2095 'cc' => CRM_Utils_Array::value('cc_confirm', $eventEmail),
2096 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventEmail),
2097 );
2098 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2099 }
2100 }
2101
2102 return $fromEmailValues;
2103 }
2104
2105 /**
2106 * Calculate event total seats occupied.
2107 *
2108 * @param int $eventId
2109 * Event id.
2110 * @param sting $extraWhereClause
2111 * Extra filter on participants.
2112 *
2113 * @return int
2114 * event total seats w/ given criteria.
2115 * @static
2116 */
2117 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2118 if (empty($eventId)) {
2119 return 0;
2120 }
2121
2122 $extraWhereClause = trim($extraWhereClause);
2123 if (!empty($extraWhereClause)) {
2124 $extraWhereClause = " AND ( {$extraWhereClause} )";
2125 }
2126
2127 //event seats calculation :
2128 //1. consider event seat as a single when participant does not have line item.
2129 //2. consider event seat as a single when participant has line items but does not
2130 // have count for corresponding price field value ( ie price field value does not carry any seat )
2131 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2132
2133 $query = "
2134 SELECT IF ( SUM( value.count*lineItem.qty ),
2135 SUM( value.count*lineItem.qty ) +
2136 COUNT( DISTINCT participant.id ) -
2137 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2138 COUNT( DISTINCT participant.id ) )
2139 FROM civicrm_participant participant
2140 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2141 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2142 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2143 AND lineItem.entity_table = 'civicrm_participant' )
2144 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2145 WHERE ( participant.event_id = %1 )
2146 AND participant.is_test = 0
2147 {$extraWhereClause}
2148 GROUP BY participant.event_id";
2149
2150 return (int) CRM_Core_DAO::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2151 }
2152
2153 /**
2154 * Retrieve event template default values to be set
2155 * as default values for current new event.
2156 *
2157 * @param int $templateId
2158 * Event template id.
2159 *
2160 * @return array
2161 * Array of custom data defaults.
2162 */
2163 public static function getTemplateDefaultValues($templateId) {
2164 $defaults = array();
2165 if (!$templateId) {
2166 return $defaults;
2167 }
2168
2169 $templateParams = array('id' => $templateId);
2170 CRM_Event_BAO_Event::retrieve($templateParams, $defaults);
2171 $fieldsToExclude = array(
2172 'id',
2173 'default_fee_id',
2174 'default_discount_fee_id',
2175 'created_date',
2176 'created_id',
2177 'is_template',
2178 'template_title',
2179 );
2180 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2181 return $defaults;
2182 }
2183
2184 /**
2185 * @param int $event_id
2186 *
2187 * @return object
2188 */
2189 public static function get_sub_events($event_id) {
2190 $params = array('parent_event_id' => $event_id);
2191 $defaults = array();
2192 return CRM_Event_BAO_Event::retrieve($params, $defaults);
2193 }
2194
2195 /**
2196 * Update the Campaign Id of all the participants of the given event
2197 *
2198 * @param int $eventID
2199 * Event id.
2200 * @param int $eventCampaignID
2201 * Campaign id of that event.
2202 */
2203 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2204 $params = array();
2205 $params[1] = array($eventID, 'Integer');
2206
2207 if (empty($eventCampaignID)) {
2208 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2209 }
2210 else {
2211 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2212 $params[2] = array($eventCampaignID, 'Integer');
2213 }
2214 CRM_Core_DAO::executeQuery($query, $params);
2215 }
2216
2217 /**
2218 * Get options for a given field.
2219 * @see CRM_Core_DAO::buildOptions
2220 *
2221 * @param string $fieldName
2222 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2223 * @param array $props : whatever is known about this dao object
2224 *
2225 * @return array|bool
2226 */
2227 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2228 $params = array();
2229 // Special logic for fields whose options depend on context or properties
2230 switch ($fieldName) {
2231 case 'financial_type_id':
2232 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2233 return CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
2234
2235 break;
2236 }
2237 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
2238 }
2239
2240 }