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