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