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