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