/**
  * Function to actually build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     $this->addElement('text', 'api_key', ts('API Key'), array('size' => 48));
     $status = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
     foreach ($status as $id => $Name) {
         $this->addElement('checkbox', "participant_status_id[{$id}]", NULL, $Name);
     }
     $accessToken = CRM_Core_BAO_Setting::getItem(self::WEBINAR_SETTING_GROUP, 'access_token', NULL, FALSE);
     $organizerKey = CRM_Core_BAO_Setting::getItem(self::WEBINAR_SETTING_GROUP, 'organizer_key', NULL, FALSE);
     if ($accessToken && $organizerKey) {
         $upcomingWebinars = CRM_Gotowebinar_Form_Setting::findUpcomingWebinars();
         if (isset($upcomingWebinars['int_err_code']) and $upcomingWebinars['int_err_code'] != '') {
             $this->assign('error', $upcomingWebinars);
         } else {
             $this->assign('responseKey', TRUE);
             $this->assign('upcomingWebinars', $upcomingWebinars);
             $buttons = array(array('type' => 'submit', 'name' => ts('Save Status')));
             $this->addButtons($buttons);
         }
     } else {
         $this->add('text', "email_address", ts('Email Address'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', 'email'), TRUE);
         $this->add('text', "password", ts('Password'), array('size' => 48), TRUE);
         $buttons = array(array('type' => 'submit', 'name' => ts('Connect To My GoToWebinar')));
         // Add the Buttons.
         $this->addButtons($buttons);
         $this->assign('initial', TRUE);
     }
 }
 /**
  * Basic page run function.
  */
 public function run()
 {
     // Get link options for managing events.
     $enableCart = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME, 'enable_cart');
     $tabs = CRM_Event_Page_ManageEvent::tabs($enableCart);
     foreach ($tabs as $tab => $tabInfo) {
         $tabs[$tab]['name'] = $tabInfo['title'];
         $tabs[$tab]['qs'] = $tab == 'reminder' ? 'reset=1&action=browse&setTab=1&id=%%id%%' : 'reset=1&action=update&id=%%id%%';
     }
     // Get link options for participant listings.
     $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
     $statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0');
     $participantLinks = array();
     if (1 || !empty($statusTypes)) {
         $participantLinks[2] = array('name' => implode(', ', array_values($statusTypes)), 'url' => 'civicrm/event/search', 'qs' => 'reset=1&force=1&status=true&event=%%id%%', 'title' => ts('Counted', array('domain' => 'com.aghstrategies.eventpermissions')));
     }
     if (!empty($statusTypesPending)) {
         $participantLinks[3] = array('name' => implode(', ', array_values($statusTypesPending)), 'url' => 'civicrm/event/search', 'qs' => 'reset=1&force=1&status=false&event=%%id%%', 'title' => ts('Not Counted', array('domain' => 'com.aghstrategies.eventpermissions')));
     }
     $participantLinks[4] = array('name' => ts('Public Participant Listing', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/participant', 'qs' => 'reset=1&id=%%id%%', 'title' => ts('Public Participant Listing', array('domain' => 'com.aghstrategies.eventpermissions')));
     // Get link options for event links.
     $eventLinks = array(array('name' => ts('Register Participant', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/participant/add', 'qs' => 'reset=1&action=add&context=standalone&eid=%%id%%', 'title' => ts('Register Participant', array('domain' => 'com.aghstrategies.eventpermissions'))), array('name' => ts('Event Info', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/info', 'qs' => 'reset=1&id=%%id%%', 'title' => ts('Event Info', array('domain' => 'com.aghstrategies.eventpermissions'))), array('name' => ts('Online Registration (Test-drive)', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/register', 'qs' => 'reset=1&action=preview&id=%%id%%', 'title' => ts('Online Registration (Test-drive)', array('domain' => 'com.aghstrategies.eventpermissions'))), array('name' => ts('Online Registration (Live)', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/register', 'qs' => 'reset=1&id=%%id%%', 'title' => ts('Online Registration (Live)', array('domain' => 'com.aghstrategies.eventpermissions'))));
     $utils = new CRM_Eventpermissions_Utils();
     $events = array();
     foreach ($utils->myUpcomingEvents() as $id => $event) {
         $events[] = array('title' => CRM_Utils_System::href($event['title'], 'civicrm/event/info', "id={$id}&reset=1"), 'links' => CRM_Core_Action::formLink($tabs, NULL, array('id' => $id), ts('Configure', array('domain' => 'com.aghstrategies.eventpermissions')), TRUE, 'eventpermissions.myevents.configure', 'Event', $id), 'participantLinks' => CRM_Core_Action::formLink($participantLinks, $event['participant_listing_id'] ? 6 : 3, array('id' => $id), ts('Participants', array('domain' => 'com.aghstrategies.eventpermissions')), TRUE, 'eventpermissions.myevents.participants', 'Event', $id), 'eventLinks' => CRM_Core_Action::formLink($eventLinks, NULL, array('id' => $id), ts('Event Links', array('domain' => 'com.aghstrategies.eventpermissions')), TRUE, 'eventpermissions.myevents.links', 'Event', $id));
     }
     $this->assign('events', $events);
     parent::run();
 }
Ejemplo n.º 3
0
 /**
  * Browse all event templates.
  */
 public function browse()
 {
     //get all event templates.
     $allEventTemplates = array();
     $eventTemplate = new CRM_Event_DAO_Event();
     $eventTypes = CRM_Event_PseudoConstant::eventType();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $participantListings = CRM_Event_PseudoConstant::participantListing();
     //find all event templates.
     $eventTemplate->is_template = TRUE;
     $eventTemplate->find();
     while ($eventTemplate->fetch()) {
         CRM_Core_DAO::storeValues($eventTemplate, $allEventTemplates[$eventTemplate->id]);
         //get listing types.
         if ($eventTemplate->participant_listing_id) {
             $allEventTemplates[$eventTemplate->id]['participant_listing'] = $participantListings[$eventTemplate->participant_listing_id];
         }
         //get participant role
         if ($eventTemplate->default_role_id) {
             $allEventTemplates[$eventTemplate->id]['participant_role'] = $participantRoles[$eventTemplate->default_role_id];
         }
         //get event type.
         if (isset($eventTypes[$eventTemplate->event_type_id])) {
             $allEventTemplates[$eventTemplate->id]['event_type'] = $eventTypes[$eventTemplate->event_type_id];
         }
         //form all action links
         $action = array_sum(array_keys($this->links()));
         //add action links.
         $allEventTemplates[$eventTemplate->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $eventTemplate->id), ts('more'), FALSE, 'eventTemplate.manage.action', 'Event', $eventTemplate->id);
     }
     $this->assign('rows', $allEventTemplates);
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1&action=browse'));
 }
 /**
  * Set up the fields.
  */
 public function __construct()
 {
     $this->_columns = array('civicrm_contact' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('sort_name_linked' => array('title' => ts('Participant Name'), 'dbAlias' => 'contact_civireport.sort_name'), 'first_name' => array('title' => ts('First Name')), 'middle_name' => array('title' => ts('Middle Name')), 'last_name' => array('title' => ts('Last Name')), 'id' => array('no_display' => TRUE, 'required' => TRUE)), 'grouping' => 'contact-fields', 'order_bys' => array('sort_name' => array('title' => ts('Sort Name'))), 'filters' => array('sort_name' => array('title' => ts('Participant Name'), 'operator' => 'like'), 'employer_id' => array('title' => ts('Employer Name')), 'contact_type' => array('title' => ts('Contact Type (Participant)')), 'contact_sub_type' => array('title' => ts('Contact Subtype (Participant)')))), 'organization' => array('name' => 'civicrm_contact', 'dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('display_name' => array('title' => ts('Organization Name'), 'default' => TRUE)), 'order_bys' => array('org_sort_name' => array('name' => 'sort_name', 'title' => ts('Organization Name'), 'default' => '1', 'default_weight' => '0', 'default_order' => 'ASC')), 'group_bys' => array('org_id' => array('name' => 'id', 'title' => ts('Organization')))), 'civicrm_event' => array('dao' => 'CRM_Event_DAO_Event', 'grouping' => 'event-fields', 'filters' => array('eid' => array('name' => 'event_type_id', 'title' => ts('Event Type (Recent Period)'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_OptionGroup::values('event_type'), 'joinclause' => TRUE), 'event_start_date1' => array('title' => ts('Event Start Date (Recent Period)'), 'type' => CRM_Utils_Type::T_DATE, 'operatorType' => CRM_Report_Form::OP_DATE, 'name' => 'event_start_date', 'default' => 'this.year', 'joinclause' => TRUE))), 'civicrm_participant' => array('dao' => 'CRM_Event_DAO_Participant', 'fields' => array('participant_id' => array('title' => 'Participant ID (Recent Period)'), 'participant_record' => array('name' => 'id', 'no_display' => TRUE, 'required' => TRUE), 'event_id' => array('default' => TRUE, 'title' => ts('Events Attended (Recent Period)'), 'statistics' => array('count_distinct' => ts('Events Attended (Recent Period)'))), 'unique_staff' => array('name' => 'contact_id', 'default' => TRUE, 'title' => ts('Unique Staff'), 'statistics' => array('count_distinct' => ts('Unique Staff (Recent Period)')))), 'grouping' => 'event-fields', 'filters' => array('event_id' => array('name' => 'event_id', 'title' => ts('Event (Recent Period)'), 'operatorType' => CRM_Report_Form::OP_ENTITYREF, 'type' => CRM_Utils_Type::T_INT, 'attributes' => array('entity' => 'event', 'select' => array('minimumInputLength' => 0)), 'joinclause' => TRUE), 'sid' => array('name' => 'status_id', 'title' => ts('Participant Status (Recent Period)'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), 'joinclause' => TRUE), 'rid' => array('name' => 'role_id', 'title' => ts('Participant Role (Recent Period)'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Event_PseudoConstant::participantRole(), 'joinclause' => TRUE), 'participant_register_date' => array('title' => ts('Registration Date (Recent Period)'), 'operatorType' => CRM_Report_Form::OP_DATE, 'joinclause' => TRUE))), 'civicrm_event2' => array('name' => 'civicrm_event', 'dao' => 'CRM_Event_DAO_Event', 'grouping' => 'event-fields', 'filters' => array('eid2' => array('name' => 'event_type_id', 'title' => ts('Event Type (Prior Period)'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_OptionGroup::values('event_type'), 'joinclause' => TRUE), 'event_start_date2' => array('title' => ts('Event Start Date (Prior Period)'), 'type' => CRM_Utils_Type::T_DATE, 'operatorType' => CRM_Report_Form::OP_DATE, 'name' => 'event_start_date', 'default' => 'previous.year', 'joinclause' => TRUE))), 'civicrm_participant2' => array('name' => 'civicrm_participant', 'dao' => 'CRM_Event_DAO_Participant', 'fields' => array('participant_id' => array('title' => 'Participant ID (Prior Period)'), 'participant_record2' => array('name' => 'id', 'no_display' => TRUE, 'required' => TRUE), 'event_id2' => array('name' => 'event_id', 'default' => TRUE, 'title' => ts('Events Attended (Prior Period)'), 'statistics' => array('count_distinct' => ts('Events Attended (Prior Period)'))), 'unique_staff2' => array('name' => 'contact_id', 'default' => TRUE, 'title' => ts('Unique Staff (Prior Period)'), 'statistics' => array('count_distinct' => ts('Unique Staff (Prior Period)')))), 'grouping' => 'event-fields', 'filters' => array('event_id2' => array('name' => 'event_id', 'title' => ts('Event (Prior Period)'), 'operatorType' => CRM_Report_Form::OP_ENTITYREF, 'type' => CRM_Utils_Type::T_INT, 'attributes' => array('entity' => 'event', 'select' => array('minimumInputLength' => 0)), 'joinclause' => TRUE), 'sid2' => array('name' => 'status_id', 'title' => ts('Participant Status (Prior Period)'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), 'joinclause' => TRUE), 'rid' => array('name' => 'role_id', 'title' => ts('Participant Role (Prior Period)'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Event_PseudoConstant::participantRole(), 'joinclause' => TRUE), 'participant_register_date2' => array('name' => 'participant_register_date', 'title' => ts('Registration Date (Prior Period)'), 'operatorType' => CRM_Report_Form::OP_DATE, 'joinclause' => TRUE))));
     $this->_groupFilter = TRUE;
     $this->_tagFilter = TRUE;
     parent::__construct();
     $this->_columns['civicrm_group']['filters']['gid']['title'] = ts('Group (Employer)');
     $this->_columns['civicrm_tag']['filters']['tagid']['title'] = ts('Tag (Employer)');
 }
Ejemplo n.º 5
0
 /**
  * @param array $params
  * @param $participant
  * @param $event
  *
  * @return mixed
  */
 public function registerParticipant($params, &$participant, $event)
 {
     $transaction = new CRM_Core_Transaction();
     // handle register date CRM-4320
     $registerDate = date('YmdHis');
     $participantParams = array('id' => $participant->id, 'event_id' => $event->id, 'register_date' => $registerDate, 'source' => CRM_Utils_Array::value('participant_source', $params, $this->description), 'is_pay_later' => $this->is_pay_later, 'fee_amount' => CRM_Utils_Array::value('amount', $params, 0), 'fee_currency' => CRM_Utils_Array::value('currencyID', $params));
     if ($participant->must_wait) {
         $participant_status = 'On waitlist';
     } elseif (CRM_Utils_Array::value('is_pay_later', $params, FALSE)) {
         $participant_status = 'Pending from pay later';
     } else {
         $participant_status = 'Registered';
     }
     $participant_statuses = CRM_Event_PseudoConstant::participantStatus();
     $participantParams['status_id'] = array_search($participant_status, $participant_statuses);
     $participant_status_label = CRM_Utils_Array::value($participantParams['status_id'], CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'));
     $participantParams['participant_status'] = $participant_status_label;
     $this->assign('isOnWaitlist', $participant->must_wait);
     if ($this->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
         $participantParams['is_test'] = 1;
     } else {
         $participantParams['is_test'] = 0;
     }
     if (self::is_administrator()) {
         if (!empty($params['note'])) {
             $note_params = array('participant_id' => $participant->id, 'contact_id' => self::getContactID(), 'note' => $params['note']);
             CRM_Event_BAO_Participant::update_note($note_params);
         }
     }
     $participant->copyValues($participantParams);
     $participant->save();
     if (!empty($params['contributionID'])) {
         $payment_params = array('participant_id' => $participant->id, 'contribution_id' => $params['contributionID']);
         $ids = array();
         $paymentParticpant = CRM_Event_BAO_ParticipantPayment::create($payment_params, $ids);
     }
     $transaction->commit();
     $event_values = array();
     CRM_Core_DAO::storeValues($event, $event_values);
     $location = array();
     if (CRM_Utils_Array::value('is_show_location', $event_values) == 1) {
         $locationParams = array('entity_id' => $participant->event_id, 'entity_table' => 'civicrm_event');
         $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
         CRM_Core_BAO_Address::fixAddress($location['address'][1]);
     }
     list($pre_id, $post_id) = CRM_Event_Cart_Form_MerParticipant::get_profile_groups($participant->event_id);
     $payer_values = array('email' => '', 'name' => '');
     if ($this->payer_contact_id) {
         $payer_contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
         $payer_values = array('email' => $payer_contact_details[1], 'name' => $payer_contact_details[0]);
     }
     $values = array('params' => array($participant->id => $participantParams), 'event' => $event_values, 'location' => $location, 'custom_pre_id' => $pre_id, 'custom_post_id' => $post_id, 'payer' => $payer_values);
     CRM_Event_BAO_Event::sendMail($participant->contact_id, $values, $participant->id);
     return $participant;
 }
Ejemplo n.º 6
0
 public function buildQuickForm()
 {
     // CRM_Event_Form_Task_Batch::buildQuickForm() gets ufGroupId
     // from the form, so set it here to the id of the reserved profile
     $dao = new CRM_Core_DAO_UFGroup();
     $dao->name = 'participant_status';
     $dao->find(TRUE);
     $this->set('ufGroupId', $dao->id);
     $statuses = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
     asort($statuses, SORT_STRING);
     $this->add('select', 'status_change', ts('Change All Statuses'), array('' => ts('- select status -')) + $statuses);
     $this->assign('context', 'statusChange');
     # CRM-4321: display info on users being notified if any of the below statuses is enabled
     parent::assignToTemplate();
     parent::buildQuickForm();
 }
Ejemplo n.º 7
0
 /**  
  * Function to set variables up before form is built  
  *                                                            
  * @return void  
  * @access public  
  */
 public function preProcess()
 {
     require_once 'CRM/Event/BAO/Participant.php';
     $values = $ids = array();
     $params = array('id' => $this->get('id'));
     CRM_Event_BAO_Participant::getValues($params, $values, $ids);
     CRM_Event_BAO_Participant::resolveDefaults($values[$params['id']]);
     if (CRM_Utils_Array::value('fee_level', $values[$params['id']])) {
         CRM_Event_BAO_Participant::fixEventLevel($values[$params['id']]['fee_level']);
     }
     if ($values[$params['id']]['is_test']) {
         $values[$params['id']]['status'] .= ' (test) ';
     }
     // Get Note
     $noteValue = CRM_Core_BAO_Note::getNote($values[$params['id']]['id'], 'civicrm_participant');
     $values[$params['id']]['note'] = array_values($noteValue);
     require_once 'CRM/Price/BAO/LineItem.php';
     // Get Line Items
     $lineItem = CRM_Price_BAO_LineItem::getLineItems($params['id']);
     if (!CRM_Utils_System::isNull($lineItem)) {
         $values[$params['id']]['lineItem'][] = $lineItem;
     }
     $values[$params['id']]['totalAmount'] = $values[$params['id']]['fee_amount'];
     // get the option value for custom data type
     $roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
     $eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
     $roleGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $params['id'], null, $values[$params['id']]['role_id'], $roleCustomDataTypeID);
     $eventGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $params['id'], null, $values[$params['id']]['event_id'], $eventNameCustomDataTypeID);
     $groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree);
     $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $params['id']));
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     $this->assign($values[$params['id']]);
     // add viewed participant to recent items list
     require_once 'CRM/Utils/Recent.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$values[$params['id']]['id']}&cid={$values[$params['id']]['contact_id']}");
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values[$params['id']]['event_id'], 'title');
     $title = CRM_Contact_BAO_Contact::displayName($values[$params['id']]['contact_id']) . ' (' . $participantRoles[$values[$params['id']]['role_id']] . ' - ' . $eventTitle . ')';
     // add the recently created Activity
     CRM_Utils_Recent::add($title, $url, $values[$params['id']]['id'], 'Participant', $values[$params['id']]['contact_id'], null);
 }
 function run()
 {
     $this->preProcess();
     $fromClause = "\nFROM       civicrm_contact\nINNER JOIN civicrm_participant ON civicrm_contact.id = civicrm_participant.contact_id \nINNER JOIN civicrm_event       ON civicrm_participant.event_id = civicrm_event.id\n";
     $whereClause = "\nWHERE    civicrm_event.id = %1";
     $params = array(1 => array($this->_id, 'Integer'));
     $this->pager($fromClause, $whereClause, $params);
     $orderBy = $this->orderBy();
     list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
     $query = "\nSELECT   civicrm_contact.id                as contact_id    ,\n         civicrm_contact.display_name      as name          ,\n         civicrm_contact.sort_name         as sort_name     ,\n         civicrm_participant.id            as participant_id,\n         civicrm_participant.status_id     as status_id     ,\n         civicrm_participant.register_date as register_date\n         {$fromClause}\n         {$whereClause}\nORDER BY {$orderBy}\nLIMIT    {$offset}, {$rowCount}";
     $rows = array();
     $object = CRM_Core_DAO::executeQuery($query, $params);
     $statusLookup = CRM_Event_PseudoConstant::participantStatus();
     while ($object->fetch()) {
         $row = array('id' => $object->contact_id, 'participantID' => $object->participant_id, 'name' => $object->name, 'email' => $object->email, 'status' => CRM_Utils_Array::value($object->status_id, $statusLookup), 'date' => $object->register_date);
         $rows[] = $row;
     }
     $this->assign_by_ref('rows', $rows);
     return parent::run();
 }
Ejemplo n.º 9
0
 function buildQuickForm()
 {
     // CRM_Event_Form_Task_Batch::buildQuickForm() gets ufGroupId
     // from the form, so set it here to the id of the reserved profile
     require_once 'CRM/Core/DAO/UFGroup.php';
     $dao = new CRM_Core_DAO_UFGroup();
     $dao->name = 'participant_status';
     $dao->find(true);
     $this->set('ufGroupId', $dao->id);
     require_once 'CRM/Event/PseudoConstant.php';
     $statuses =& CRM_Event_PseudoConstant::participantStatus();
     asort($statuses, SORT_STRING);
     $this->add('select', 'status_change', ts('Change All Statuses'), array('' => ts('- select status -')) + $statuses, null, array('onchange' => "if (this.value) setStatusesTo(this.value);"));
     $this->assign('context', 'statusChange');
     # CRM-4321: display info on users being notified if any of the below statuses is enabled
     require_once 'CRM/Event/PseudoConstant.php';
     $notifyingStatuses = array(ts('Pending from waitlist'), ts('Pending from approval'), ts('Expired'), ts('Cancelled'));
     $notifyingStatuses = array_intersect($notifyingStatuses, CRM_Event_PseudoConstant::participantStatus());
     $this->assign('notifyingStatuses', implode(', ', $notifyingStatuses));
     parent::buildQuickForm();
 }
/**
 * Implementation of buildAmount hook
 * To modify the priceset on the basis of participant role/price field id provided from the url
 */
function rolebasedpricing_civicrm_buildAmount($pageType, &$form, &$amount)
{
    if ($pageType == 'event') {
        $priceSetId = $form->get('priceSetId');
        $backupPriceSet = $form->_priceSet;
        $priceSet =& $form->_priceSet;
        $participantrole = '';
        $participantroleHashed = CRM_Utils_Request::retrieve('participantrole', 'String', $form);
        $allParticipantRoles = CRM_Event_PseudoConstant::participantRole();
        //If we find participantrole in url
        if ($participantroleHashed) {
            foreach ($allParticipantRoles as $roleId => $roleName) {
                if (md5($roleId) == $participantroleHashed) {
                    $participantrole = $roleId;
                    break;
                }
            }
        } else {
            $defaultParticipantRole = $form->_values['event']['default_role_id'];
            $participantrole = $defaultParticipantRole;
        }
        if (isset($participantrole) && !empty($participantrole)) {
            if (!empty($priceSetId)) {
                $backupAmount = $amount;
                $feeBlock =& $amount;
                $counter = 0;
                foreach ($feeBlock as $k => &$fee) {
                    if (!is_array($fee['options'])) {
                        continue;
                    }
                    $price_field_id = $fee['id'];
                    foreach ($fee['options'] as $key => &$option) {
                        $fieldID = $option['id'];
                        $sql = "SELECT COUNT(*) as count\n              FROM civicrm_participantrole_price\n              WHERE participant_role = %1\n              AND price_field_id = %2\n              AND field_id = %3";
                        $params = array(1 => array((int) $participantrole, 'Integer'), 2 => array((int) $price_field_id, 'Integer'), 3 => array((int) $fieldID, 'Integer'));
                        $founInPriceRoleSetting = CRM_Core_DAO::singleValueQuery($sql, $params);
                        if ($founInPriceRoleSetting == 1) {
                            $counter++;
                        } else {
                            unset($feeBlock[$k]);
                            //unsetting it from $form->priceSet as it leaves the labels of Price Options behind
                            unset($priceSet['fields'][$price_field_id]);
                        }
                    }
                }
                //Restore priceset
                if ($counter < 1) {
                    $feeBlock = $backupAmount;
                    $priceSet = $backupPriceSet;
                }
            }
        }
    }
}
Ejemplo n.º 11
0
Archivo: PCP.php Proyecto: kidaa30/yes
 /**
  * Return PCP  Block info for dashboard.
  *
  * @param int $contactId
  *
  * @return array
  *   array of Pcp if found
  */
 public static function getPcpDashboardInfo($contactId)
 {
     $links = self::pcpLinks();
     $query = "\nSELECT * FROM civicrm_pcp pcp\nWHERE pcp.is_active = 1\n  AND pcp.contact_id = %1\nORDER BY page_type, page_id";
     $params = array(1 => array($contactId, 'Integer'));
     $pcpInfoDao = CRM_Core_DAO::executeQuery($query, $params);
     $pcpInfo = array();
     $hide = $mask = array_sum(array_keys($links['all']));
     $contactPCPPages = array();
     $event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
     $contribute = CRM_Contribute_PseudoConstant::contributionPage();
     $pcpStatus = CRM_Contribute_PseudoConstant::pcpStatus();
     $approved = CRM_Utils_Array::key('Approved', $pcpStatus);
     while ($pcpInfoDao->fetch()) {
         $mask = $hide;
         if ($links) {
             $replace = array('pcpId' => $pcpInfoDao->id, 'pcpBlock' => $pcpInfoDao->pcp_block_id, 'pageComponent' => $pcpInfoDao->page_type);
         }
         $pcpLink = $links['all'];
         $class = '';
         if ($pcpInfoDao->status_id != $approved || $pcpInfoDao->is_active != 1) {
             $class = 'disabled';
             if (!$pcpInfoDao->tellfriend) {
                 $mask -= CRM_Core_Action::DETACH;
             }
         }
         if ($pcpInfoDao->is_active == 1) {
             $mask -= CRM_Core_Action::ENABLE;
         } else {
             $mask -= CRM_Core_Action::DISABLE;
         }
         $action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'), FALSE, 'pcp.dashboard.active', 'PCP', $pcpInfoDao->id);
         $component = $pcpInfoDao->page_type;
         $pageTitle = CRM_Utils_Array::value($pcpInfoDao->page_id, ${$component});
         $pcpInfo[] = array('pageTitle' => $pageTitle, 'pcpId' => $pcpInfoDao->id, 'pcpTitle' => $pcpInfoDao->title, 'pcpStatus' => $pcpStatus[$pcpInfoDao->status_id], 'action' => $action, 'class' => $class);
         $contactPCPPages[$pcpInfoDao->page_type][] = $pcpInfoDao->page_id;
     }
     $excludePageClause = $clause = NULL;
     if (!empty($contactPCPPages)) {
         foreach ($contactPCPPages as $component => $entityIds) {
             $excludePageClause[] = "\n( target_entity_type = '{$component}'\nAND target_entity_id NOT IN ( " . implode(',', $entityIds) . ") )";
         }
         $clause = ' AND ' . implode(' OR ', $excludePageClause);
     }
     $query = "\nSELECT *\nFROM civicrm_pcp_block block\nLEFT JOIN civicrm_pcp pcp ON pcp.pcp_block_id = block.id\nWHERE block.is_active = 1\n{$clause}\nGROUP BY block.id\nORDER BY target_entity_type, target_entity_id\n";
     $pcpBlockDao = CRM_Core_DAO::executeQuery($query);
     $pcpBlock = array();
     $mask = 0;
     while ($pcpBlockDao->fetch()) {
         if ($links) {
             $replace = array('pageId' => $pcpBlockDao->target_entity_id, 'pageComponent' => $pcpBlockDao->target_entity_type);
         }
         $pcpLink = $links['add'];
         $action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'), FALSE, 'pcp.dashboard.other', "{$pcpBlockDao->target_entity_type}_PCP", $pcpBlockDao->target_entity_id);
         $component = $pcpBlockDao->target_entity_type;
         if ($pageTitle = CRM_Utils_Array::value($pcpBlockDao->target_entity_id, ${$component})) {
             $pcpBlock[] = array('pageId' => $pcpBlockDao->target_entity_id, 'pageTitle' => $pageTitle, 'action' => $action);
         }
     }
     return array($pcpBlock, $pcpInfo);
 }
Ejemplo n.º 12
0
 /**
  * Get additional participant Ids for cascading with primary participant status.
  *
  * @param int $participantId
  *   Participant id.
  * @param int $oldStatusId
  *   Previous status.
  * @param int $newStatusId
  *   New status.
  *
  * @return bool
  *   true if allowed
  */
 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId)
 {
     $additionalParticipantIds = array();
     static $participantStatuses = array();
     if (empty($participantStatuses)) {
         $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
     }
     if (CRM_Utils_Array::value($participantStatuses[$oldStatusId], self::$_statusTransitionsRules) && in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])) {
         $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
     }
     return $additionalParticipantIds;
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     //get the button.
     $buttonName = $this->controller->getButtonName();
     $participantId = $this->_participantId;
     if ($buttonName == '_qf_ParticipantConfirm_next') {
         //lets get contact id in session.
         $session = CRM_Core_Session::singleton();
         $session->set('userID', $this->_csContactID);
         $this->postProcessHook();
         //check user registration status is from pending class
         $url = CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$this->_eventId}&participantId={$participantId}");
         CRM_Utils_System::redirect($url);
     } elseif ($buttonName == '_qf_ParticipantConfirm_submit') {
         //need to registration status to 'cancelled'.
         $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
         $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
         $participantIds = array_merge(array($participantId), $additionalParticipantIds);
         $results = CRM_Event_BAO_Participant::transitionParticipants($participantIds, $cancelledId, NULL, TRUE);
         if (count($participantIds) > 1) {
             $statusMessage = ts("%1 Event registration(s) have been cancelled.", array(1 => count($participantIds)));
         } else {
             $statusMessage = ts("Your event registration has been cancelled.");
         }
         if (!empty($results['mailedParticipants'])) {
             foreach ($results['mailedParticipants'] as $key => $displayName) {
                 $statusMessage .= "<br />" . ts("Email has been sent to : %1", array(1 => $displayName));
             }
         }
         $this->postProcessHook();
         CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}&noFullMsg=1", FALSE, NULL, FALSE, TRUE));
     }
 }
Ejemplo n.º 14
0
 /**
  * Returns all the rows in the given offset and rowCount.
  *
  * @param string $action
  *   The action being performed.
  * @param int $offset
  *   The row number to start from.
  * @param int $rowCount
  *   The number of rows to return.
  * @param string $sort
  *   The sql string that describes the sort order.
  * @param string $output
  *   What should the result set include (web/email/csv).
  *
  * @return array
  *   rows in the given offset and rowCount
  */
 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, $this->_eventClause);
     // process the result of the query
     $rows = array();
     //lets handle view, edit and delete separately. CRM-4418
     $permissions = array(CRM_Core_Permission::VIEW);
     if (CRM_Core_Permission::check('edit event participants')) {
         $permissions[] = CRM_Core_Permission::EDIT;
     }
     if (CRM_Core_Permission::check('delete in CiviEvent')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     $statusTypes = CRM_Event_PseudoConstant::participantStatus();
     $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $sep = CRM_Core_DAO::VALUE_SEPARATOR;
     //get all campaigns.
     $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     while ($result->fetch()) {
         $row = array();
         // the columns we are interested in
         foreach (self::$_properties as $property) {
             if (isset($result->{$property})) {
                 $row[$property] = $result->{$property};
             }
         }
         //carry campaign on selectors.
         $row['campaign'] = CRM_Utils_Array::value($result->participant_campaign_id, $allCampaigns);
         $row['campaign_id'] = $result->participant_campaign_id;
         // gross hack to show extra information for pending status
         $statusClass = NULL;
         if (isset($row['participant_status_id']) && ($statusId = array_search($row['participant_status_id'], $statusTypes))) {
             $statusClass = $statusClasses[$statusId];
         }
         $row['showConfirmUrl'] = $statusClass == 'Pending' ? TRUE : FALSE;
         if (!empty($row['participant_is_test'])) {
             $row['participant_status'] .= ' (' . ts('test') . ')';
         }
         $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->participant_id;
         $links = self::links($this->_key, $this->_context, $this->_compContext);
         if ($statusTypes[$row['participant_status_id']] == 'Partially paid') {
             $links[CRM_Core_Action::ADD] = array('name' => ts('Record Payment'), 'url' => 'civicrm/payment', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event', 'title' => ts('Record Payment'));
         }
         if ($statusTypes[$row['participant_status_id']] == 'Pending refund') {
             $links[CRM_Core_Action::ADD] = array('name' => ts('Record Refund'), 'url' => 'civicrm/payment', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event', 'title' => ts('Record Refund'));
         }
         $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->participant_id, 'cid' => $result->contact_id, 'cxt' => $this->_context), ts('more'), FALSE, 'participant.selector.row', 'Participant', $result->participant_id);
         $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id);
         $row['paid'] = CRM_Event_BAO_Event::isMonetary($row['event_id']);
         if (!empty($row['participant_fee_level'])) {
             CRM_Event_BAO_Participant::fixEventLevel($row['participant_fee_level']);
         }
         if (CRM_Event_BAO_Event::usesPriceSet($row['event_id'])) {
             // add line item details if applicable
             $lineItems[$row['participant_id']] = CRM_Price_BAO_LineItem::getLineItems($row['participant_id']);
         }
         if (!empty($row['participant_role_id'])) {
             $viewRoles = array();
             foreach (explode($sep, $row['participant_role_id']) as $k => $v) {
                 $viewRoles[] = $participantRoles[$v];
             }
             $row['participant_role_id'] = implode(', ', $viewRoles);
         }
         $rows[] = $row;
     }
     CRM_Core_Selector_Controller::$_template->assign_by_ref('lineItems', $lineItems);
     return $rows;
 }
Ejemplo n.º 15
0
 /**
  * Browse all custom data groups.
  *
  * @param string $action   the action to be invoked
  *
  * @return void
  * @access public
  */
 function browse($action = NULL)
 {
     // get all custom groups sorted by weight
     $customGroup = array();
     $dao = new CRM_Core_DAO_CustomGroup();
     $dao->orderBy('weight, title');
     $dao->find();
     while ($dao->fetch()) {
         $customGroup[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $customGroup[$dao->id]);
         // form all action links
         $action = array_sum(array_keys($this->actionLinks()));
         // update enable/disable links depending on custom_group properties.
         if ($dao->is_active) {
             $action -= CRM_Core_Action::ENABLE;
         } else {
             $action -= CRM_Core_Action::DISABLE;
         }
         $customGroup[$dao->id]['order'] = $customGroup[$dao->id]['weight'];
         $customGroup[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id));
     }
     $customGroupExtends = CRM_Core_SelectValues::customGroupExtends();
     foreach ($customGroup as $key => $array) {
         CRM_Core_DAO_CustomGroup::addDisplayEnums($customGroup[$key]);
         $customGroup[$key]['extends_display'] = $customGroupExtends[$customGroup[$key]['extends']];
     }
     //fix for Displaying subTypes
     $subTypes = array();
     $subTypes['Activity'] = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
     $subTypes['Contribution'] = CRM_Contribute_PseudoConstant::contributionType();
     $subTypes['Membership'] = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
     $subTypes['Event'] = CRM_Core_OptionGroup::values('event_type');
     $subTypes['Grant'] = CRM_Core_OptionGroup::values('grant_type');
     $subTypes['Campaign'] = CRM_Campaign_PseudoConstant::campaignType();
     $subTypes['Participant'] = array();
     $subTypes['ParticipantRole'] = CRM_Core_OptionGroup::values('participant_role');
     $subTypes['ParticipantEventName'] = CRM_Event_PseudoConstant::event();
     $subTypes['ParticipantEventType'] = CRM_Core_OptionGroup::values('event_type');
     $subTypes['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
     $subTypes['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
     $subTypes['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
     $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
     $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
     $allRelationshipType = array();
     $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
     $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
     //adding subtype specific relationships CRM-5256
     $relSubType = CRM_Contact_BAO_ContactType::subTypeInfo();
     foreach ($relSubType as $subType => $val) {
         $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType);
         $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes);
     }
     $subTypes['Relationship'] = $allRelationshipType;
     $cSubTypes = CRM_Core_Component::contactSubTypes();
     $contactSubTypes = array();
     foreach ($cSubTypes as $key => $value) {
         $contactSubTypes[$key] = $key;
     }
     $subTypes['Contact'] = $contactSubTypes;
     CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($subTypes);
     foreach ($customGroup as $key => $values) {
         $subValue = CRM_Utils_Array::value('extends_entity_column_value', $customGroup[$key]);
         $subName = CRM_Utils_Array::value('extends_entity_column_id', $customGroup[$key]);
         $type = CRM_Utils_Array::value('extends', $customGroup[$key]);
         if ($subValue) {
             $subValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subValue, 1, -1));
             $colValue = NULL;
             foreach ($subValue as $sub) {
                 if ($sub) {
                     if ($type == 'Participant') {
                         if ($subName == 1) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantRole'][$sub] : $subTypes['ParticipantRole'][$sub];
                         } elseif ($subName == 2) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventName'][$sub] : $subTypes['ParticipantEventName'][$sub];
                         } elseif ($subName == 3) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventType'][$sub] : $subTypes['ParticipantEventType'][$sub];
                         }
                     } elseif ($type == 'Relationship') {
                         $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_a_b'] : $subTypes[$type][$sub . '_a_b'];
                         if (isset($subTypes[$type][$sub . '_b_a'])) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_b_a'] : $subTypes[$type][$sub . '_b_a'];
                         }
                     } else {
                         $colValue = $colValue ? $colValue . (isset($subTypes[$type][$sub]) ? ', ' . $subTypes[$type][$sub] : '') : (isset($subTypes[$type][$sub]) ? $subTypes[$type][$sub] : '');
                     }
                 }
             }
             $customGroup[$key]["extends_entity_column_value"] = $colValue;
         } else {
             if (is_array(CRM_Utils_Array::value($type, $subTypes))) {
                 $customGroup[$key]["extends_entity_column_value"] = ts("Any");
             }
         }
     }
     $returnURL = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1&action=browse");
     CRM_Utils_Weight::addOrder($customGroup, 'CRM_Core_DAO_CustomGroup', 'id', $returnURL);
     $this->assign('rows', $customGroup);
 }
Ejemplo n.º 16
0
 /**
  * set the first participant ID if not set, CRM-10032
  *
  * @param int $participantID
  */
 public function processFirstParticipant($participantID)
 {
     $this->_participantId = $participantID;
     $this->set('participantId', $this->_participantId);
     $ids = $participantValues = array();
     $participantParams = array('id' => $this->_participantId);
     CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
     $this->_values['participant'] = $participantValues[$this->_participantId];
     $this->set('values', $this->_values);
     // also set the allow confirmation stuff
     if (array_key_exists($this->_values['participant']['status_id'], CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'"))) {
         $this->_allowConfirmation = TRUE;
         $this->set('allowConfirmation', TRUE);
     }
 }
Ejemplo n.º 17
0
 /**
  * Add activity for Membership/Event/Contribution.
  *
  * @param object $activity
  *   (reference) particular component object.
  * @param string $activityType
  *   For Membership Signup or Renewal.
  * @param int $targetContactID
  *
  * @return bool|NULL
  */
 public static function addActivity(&$activity, $activityType = 'Membership Signup', $targetContactID = NULL)
 {
     if ($activity->__table == 'civicrm_membership') {
         $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id);
         if (!$membershipType) {
             $membershipType = ts('Membership');
         }
         $subject = "{$membershipType}";
         if (!empty($activity->source) && $activity->source != 'null') {
             $subject .= " - {$activity->source}";
         }
         if ($activity->owner_membership_id) {
             $query = "\nSELECT  display_name\n  FROM  civicrm_contact, civicrm_membership\n WHERE  civicrm_contact.id    = civicrm_membership.contact_id\n   AND  civicrm_membership.id = {$activity->owner_membership_id}\n";
             $displayName = CRM_Core_DAO::singleValueQuery($query);
             $subject .= " (by {$displayName})";
         }
         $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id, 'label');
         // CRM-72097 changed from start date to today
         $date = date('YmdHis');
         $component = 'Membership';
     } elseif ($activity->__table == 'civicrm_participant') {
         $event = CRM_Event_BAO_Event::getEvents(1, $activity->event_id, TRUE, FALSE);
         $roles = CRM_Event_PseudoConstant::participantRole();
         $status = CRM_Event_PseudoConstant::participantStatus();
         $subject = $event[$activity->event_id];
         if (!empty($roles[$activity->role_id])) {
             $subject .= ' - ' . $roles[$activity->role_id];
         }
         if (!empty($status[$activity->status_id])) {
             $subject .= ' - ' . $status[$activity->status_id];
         }
         $date = date('YmdHis');
         if ($activityType != 'Email') {
             $activityType = 'Event Registration';
         }
         $component = 'Event';
     } elseif ($activity->__table == 'civicrm_contribution') {
         // create activity record only for Completed Contributions
         if ($activity->contribution_status_id != 1) {
             return NULL;
         }
         $subject = NULL;
         $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency);
         if (!empty($activity->source) && $activity->source != 'null') {
             $subject .= " - {$activity->source}";
         }
         $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
         $activityType = $component = 'Contribution';
     }
     $activityParams = array('source_contact_id' => $activity->contact_id, 'source_record_id' => $activity->id, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'subject' => $subject, 'activity_date_time' => $date, 'is_test' => $activity->is_test, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'skipRecentView' => TRUE, 'campaign_id' => $activity->campaign_id);
     // create activity with target contacts
     $session = CRM_Core_Session::singleton();
     $id = $session->get('userID');
     if ($id) {
         $activityParams['source_contact_id'] = $id;
         $activityParams['target_contact_id'][] = $activity->contact_id;
     }
     // CRM-14945
     if (property_exists($activity, 'details')) {
         $activityParams['details'] = $activity->details;
     }
     //CRM-4027
     if ($targetContactID) {
         $activityParams['target_contact_id'][] = $targetContactID;
     }
     if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
         CRM_Core_Error::fatal("Failed creating Activity for {$component} of id {$activity->id}");
         return FALSE;
     }
 }
Ejemplo n.º 18
0
 /**
  * Get the list the export fields.
  *
  * @param int $selectAll
  *   User preference while export.
  * @param array $ids
  *   Contact ids.
  * @param array $params
  *   Associated array of fields.
  * @param string $order
  *   Order by clause.
  * @param array $fields
  *   Associated array of fields.
  * @param array $moreReturnProperties
  *   Additional return fields.
  * @param int $exportMode
  *   Export mode.
  * @param string $componentClause
  *   Component clause.
  * @param string $componentTable
  *   Component table.
  * @param bool $mergeSameAddress
  *   Merge records if they have same address.
  * @param bool $mergeSameHousehold
  *   Merge records if they belong to the same household.
  *
  * @param array $exportParams
  * @param string $queryOperator
  *
  */
 public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND')
 {
     $headerRows = $returnProperties = array();
     $primary = $paymentFields = $selectedPaymentFields = FALSE;
     $origFields = $fields;
     $relationField = NULL;
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
         case CRM_Export_Form_Select::GRANT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
             break;
         case CRM_Export_Form_Select::ACTIVITY_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
             break;
     }
     if ($fields) {
         //construct return properties
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = $imProviderId = NULL;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id separately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } elseif ($fieldName == 'im') {
                 $imProviderId = CRM_Utils_Array::value(3, $value);
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (!empty($value[2])) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 'Primary';
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(4, $value);
                     }
                 } elseif (!empty($value[4])) {
                     $relationField = CRM_Utils_Array::value(4, $value);
                     $relLocTypeId = CRM_Utils_Array::value(5, $value);
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(6, $value);
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } elseif ($relIMProviderId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                     } else {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                     }
                     $relPhoneTypeId = $relIMProviderId = NULL;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } elseif (is_numeric($locTypeId)) {
                 if ($phoneTypeId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                 } elseif ($imProviderId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                 } else {
                     $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                 }
             } else {
                 //hack to fix component fields
                 //revert mix of event_id and title
                 if ($fieldName == 'event_id') {
                     $returnProperties['event_id'] = 1;
                 } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT && array_key_exists($fieldName, self::componentPaymentFields())) {
                     $selectedPaymentFields = TRUE;
                     $paymentTableId = 'participant_id';
                     $returnProperties[$fieldName] = 1;
                 } else {
                     $returnProperties[$fieldName] = 1;
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
             $returnProperties['participant_id'] = 1;
             if (!empty($returnProperties['participant_role'])) {
                 unset($returnProperties['participant_role']);
                 $returnProperties['participant_role_id'] = 1;
             }
         } elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
             $returnProperties['membership_id'] = 1;
         } elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
             $returnProperties['pledge_id'] = 1;
         } elseif ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
             $returnProperties['case_id'] = 1;
         } elseif ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
             $returnProperties['grant_id'] = 1;
         } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
             $returnProperties['activity_id'] = 1;
         }
     } else {
         $primary = TRUE;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = FALSE;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = TRUE;
                 $paymentTableId = 'participant_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = TRUE;
                 $paymentTableId = 'membership_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = TRUE;
                 $paymentTableId = 'pledge_payment_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
                 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
                 $componentReturnProperties = array_merge($componentReturnProperties, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
             }
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset non exportable fields for components
             $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id');
             foreach ($nonExpoFields as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($mergeSameAddress) {
         //make sure the addressee fields are selected
         //while using merge same address feature
         $returnProperties['addressee'] = 1;
         $returnProperties['postal_greeting'] = 1;
         $returnProperties['email_greeting'] = 1;
         $returnProperties['street_name'] = 1;
         $returnProperties['household_name'] = 1;
         $returnProperties['street_address'] = 1;
         $returnProperties['city'] = 1;
         $returnProperties['state_province'] = 1;
         // some columns are required for assistance incase they are not already present
         $exportParams['merge_same_address']['temp_columns'] = array();
         $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
         foreach ($tempColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
                 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
             }
         }
     }
     if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
         // If an Additional Group is selected, then all contacts in that group are
         // added to the export set (filtering out duplicates).
         $query = "\nINSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id";
         CRM_Core_DAO::executeQuery($query);
     }
     if ($moreReturnProperties) {
         // fix for CRM-7066
         if (!empty($moreReturnProperties['group'])) {
             unset($moreReturnProperties['group']);
             $moreReturnProperties['groups'] = 1;
         }
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $exportParams['postal_mailing_export']['temp_columns'] = array();
     if ($exportParams['exportOption'] == 2 && isset($exportParams['postal_mailing_export']) && CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1) {
         $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
         foreach ($postalColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
             }
         }
     }
     // rectify params to what proximity search expects if there is a value for prox_distance
     // CRM-7021
     if (!empty($params)) {
         CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
     }
     $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, $queryMode, FALSE, TRUE, TRUE, NULL, $queryOperator);
     //sort by state
     //CRM-15301
     $query->_sort = $order;
     list($select, $from, $where, $having) = $query->query();
     if ($mergeSameHousehold == 1) {
         if (!$returnProperties['id']) {
             $returnProperties['id'] = 1;
         }
         //also merge Head of Household
         $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
         $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
         foreach ($returnProperties as $key => $value) {
             if (!array_key_exists($key, $contactRelationshipTypes)) {
                 $returnProperties[$relationKeyMOH][$key] = $value;
                 $returnProperties[$relationKeyHOH][$key] = $value;
             }
         }
         unset($returnProperties[$relationKeyMOH]['location_type']);
         unset($returnProperties[$relationKeyMOH]['im_provider']);
         unset($returnProperties[$relationKeyHOH]['location_type']);
         unset($returnProperties[$relationKeyHOH]['im_provider']);
     }
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, NULL, FALSE, FALSE, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
                 $relIDs = $ids;
             } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
                 $query = "SELECT contact_id FROM civicrm_activity_contact\n                              WHERE activity_id IN ( " . implode(',', $ids) . ") AND\n                              record_type_id = {$sourceID}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 while ($dao->fetch()) {
                     $relIDs[] = $dao->contact_id;
                 }
             } else {
                 switch ($exportMode) {
                     case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
                         $component = 'civicrm_contribution';
                         break;
                     case CRM_Export_Form_Select::EVENT_EXPORT:
                         $component = 'civicrm_participant';
                         break;
                     case CRM_Export_Form_Select::MEMBER_EXPORT:
                         $component = 'civicrm_membership';
                         break;
                     case CRM_Export_Form_Select::PLEDGE_EXPORT:
                         $component = 'civicrm_pledge';
                         break;
                     case CRM_Export_Form_Select::GRANT_EXPORT:
                         $component = 'civicrm_grant';
                         break;
                 }
                 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                     $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
                 } else {
                     $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
                 }
             }
             $relationshipJoin = $relationshipClause = '';
             if (!$selectAll && $componentTable) {
                 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
             } elseif (!empty($relIDs)) {
                 $relID = implode(',', $relIDs);
                 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
             }
             $relationFrom = " {$relationFrom}\n                INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}\n                {$relationshipJoin} ";
             //check for active relationship status only
             $today = date('Ymd');
             $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
             $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
             $relationGroupBy = " GROUP BY crel.{$contactA}";
             $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
             $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationHaving} {$relationGroupBy}";
             $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
             while ($allRelContactDAO->fetch()) {
                 //FIX Me: Migrate this to table rather than array
                 // build the array of all related contacts
                 $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO;
             }
             $allRelContactDAO->free();
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (!empty($returnProperties['groups'])) {
         $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
         $newClause = " ( {$oldClause} AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if (!$selectAll && $componentTable) {
         $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id ";
     } elseif ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     // CRM-13982 - check if is deleted
     $excludeTrashed = TRUE;
     foreach ($params as $value) {
         if ($value[0] == 'contact_is_deleted') {
             $excludeTrashed = FALSE;
         }
     }
     if (empty($where) && $excludeTrashed) {
         $where = "WHERE contact_a.is_deleted != 1";
     } elseif ($excludeTrashed) {
         $where .= " AND contact_a.is_deleted != 1";
     }
     $queryString = "{$select} {$from} {$where} {$having}";
     $groupBy = "";
     if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || CRM_Utils_Array::value('notes', $returnProperties) || $queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) {
         $groupBy = " GROUP BY contact_a.id";
     }
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $groupBy = 'GROUP BY civicrm_contribution.id';
             if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
                 // especial group by  when soft credit columns are included
                 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
             }
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $groupBy = 'GROUP BY civicrm_participant.id';
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $groupBy = " GROUP BY civicrm_membership.id";
             break;
     }
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
         $groupBy = " GROUP BY civicrm_activity.id ";
     }
     $queryString .= $groupBy;
     // always add contact_a.id to the ORDER clause
     // so the order is deterministic
     //CRM-15301
     if (strpos('contact_a.id', $order) === FALSE) {
         $order .= ", contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (!empty($returnProperties[$field])) {
             //CRM-15301
             $queryString .= " ORDER BY {$order}";
         }
     }
     $multipleSelectFields = array('preferred_communication_method' => 1);
     $addPaymentHeader = FALSE;
     $paymentDetails = array();
     if ($paymentFields || $selectedPaymentFields) {
         // get payment related in for event and members
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
         //get all payment headers.
         // If we haven't selected specific payment fields, load in all the
         // payment headers.
         if (!$selectedPaymentFields) {
             $paymentHeaders = self::componentPaymentFields();
             if (!empty($paymentDetails)) {
                 $addPaymentHeader = TRUE;
             }
         } else {
             $paymentHeaders = array();
         }
         $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
     }
     $componentDetails = $headerRows = $sqlColumns = array();
     $setHeader = TRUE;
     $rowCount = self::EXPORT_ROW_COUNT;
     $offset = 0;
     // we write to temp table often to avoid using too much memory
     $tempRowCount = 100;
     $count = -1;
     // for CRM-3157 purposes
     $i18n = CRM_Core_I18n::singleton();
     $outputColumns = array();
     //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point
     // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing
     foreach ($returnProperties as $key => $value) {
         $outputColumns[$key] = $value;
     }
     while (1) {
         $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
         $dao = CRM_Core_DAO::executeQuery($limitQuery);
         if ($dao->N <= 0) {
             break;
         }
         while ($dao->fetch()) {
             $count++;
             $row = array();
             //convert the pseudo constants
             // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
             // temporary iterationDAO object to get around it.
             // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
             // these additional properties are NOT reset when the $dao cycles through the while loop
             // nor are they overwritten as they are not in the loop
             // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
             // relevant property is set.
             // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
             // export class before tackling a better architectural fix
             $iterationDAO = clone $dao;
             $query->convertToPseudoNames($iterationDAO);
             //first loop through output columns so that we return what is required, and in same order.
             $relationshipField = 0;
             foreach ($outputColumns as $field => $value) {
                 //we should set header only once
                 if ($setHeader) {
                     $sqlDone = FALSE;
                     // Split campaign into 2 fields for id and title
                     if (substr($field, -14) == 'campaign_title') {
                         $headerRows[] = ts('Campaign Title');
                     } elseif (substr($field, -11) == 'campaign_id') {
                         $headerRows[] = ts('Campaign ID');
                     } elseif (isset($query->_fields[$field]['title'])) {
                         $headerRows[] = $query->_fields[$field]['title'];
                     } elseif ($field == 'phone_type_id') {
                         $headerRows[] = ts('Phone Type');
                     } elseif ($field == 'provider_id') {
                         $headerRows[] = ts('IM Service Provider');
                     } elseif (is_array($value) && $field == 'location') {
                         // fix header for location type case
                         foreach ($value as $ltype => $val) {
                             foreach (array_keys($val) as $fld) {
                                 $type = explode('-', $fld);
                                 $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                 if (!empty($type[1])) {
                                     if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                     } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                     }
                                 }
                                 $headerRows[] = $hdr;
                                 self::sqlColumnDefn($query, $sqlColumns, $hdr);
                             }
                             $sqlDone = TRUE;
                         }
                     } elseif (substr($field, 0, 5) == 'case_') {
                         if ($query->_fields['case'][$field]['title']) {
                             $headerRows[] = $query->_fields['case'][$field]['title'];
                         } elseif ($query->_fields['activity'][$field]['title']) {
                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                         }
                     } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                         $relName = $field;
                         foreach ($value as $relationField => $relationValue) {
                             // below block is same as primary block (duplicate)
                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
                                     $headerName = $field . '-' . $relationField;
                                 } else {
                                     if ($relationField == 'current_employer') {
                                         $headerName = $field . '-' . 'current_employer';
                                     } else {
                                         $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
                                     }
                                 }
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'phone_type_id') {
                                 $headerName = $field . '-' . 'Phone Type';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'provider_id') {
                                 $headerName = $field . '-' . 'Im Service Provider';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'state_province_id') {
                                 $headerName = $field . '-' . 'state_province_id';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif (is_array($relationValue) && $relationField == 'location') {
                                 // fix header for location type case
                                 foreach ($relationValue as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                         if (!empty($type[1])) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                             }
                                         }
                                         $headerName = $field . '-' . $hdr;
                                         $headerRows[] = $headerName;
                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                     }
                                 }
                             }
                         }
                     } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                         $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
                     } else {
                         $headerRows[] = $field;
                     }
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $field);
                     }
                 }
                 // add im_provider to $dao object
                 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
                     $iterationDAO->im_provider = $iterationDAO->provider_id;
                 }
                 //build row values (data)
                 $fieldValue = NULL;
                 if (property_exists($iterationDAO, $field)) {
                     $fieldValue = $iterationDAO->{$field};
                     // to get phone type from phone type id
                     if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
                         $fieldValue = $phoneTypes[$fieldValue];
                     } elseif ($field == 'provider_id' || $field == 'im_provider') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     } elseif ($field == 'participant_role_id') {
                         $participantRoles = CRM_Event_PseudoConstant::participantRole();
                         $sep = CRM_Core_DAO::VALUE_SEPARATOR;
                         $viewRoles = array();
                         foreach (explode($sep, $iterationDAO->{$field}) as $k => $v) {
                             $viewRoles[] = $participantRoles[$v];
                         }
                         $fieldValue = implode(',', $viewRoles);
                     } elseif ($field == 'master_id') {
                         $masterAddressId = NULL;
                         if (isset($iterationDAO->master_id)) {
                             $masterAddressId = $iterationDAO->master_id;
                         }
                         // get display name of contact that address is shared.
                         $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id);
                     }
                 }
                 if ($field == 'id') {
                     $row[$field] = $iterationDAO->contact_id;
                     // special case for calculated field
                 } elseif ($field == 'source_contact_id') {
                     $row[$field] = $iterationDAO->contact_id;
                 } elseif ($field == 'pledge_balance_amount') {
                     $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
                     // special case for calculated field
                 } elseif ($field == 'pledge_next_pay_amount') {
                     $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
                 } elseif (is_array($value) && $field == 'location') {
                     // fix header for location type case
                     foreach ($value as $ltype => $val) {
                         foreach (array_keys($val) as $fld) {
                             $type = explode('-', $fld);
                             $fldValue = "{$ltype}-" . $type[0];
                             // CRM-14076 - fix label to work as the query object expects
                             // FIXME: We should not be using labels as keys!
                             $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0];
                             if (!empty($type[1])) {
                                 $fldValue .= "-" . $type[1];
                                 $daoField .= "-" . $type[1];
                             }
                             // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                             switch ($fld) {
                                 case 'country':
                                 case 'world_region':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'country'));
                                     break;
                                 case 'state_province':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'province'));
                                     break;
                                 case 'im_provider':
                                     $imFieldvalue = $daoField . "-provider_id";
                                     $row[$fldValue] = CRM_Utils_Array::value($iterationDAO->{$imFieldvalue}, $imProviders);
                                     break;
                                 default:
                                     $row[$fldValue] = $iterationDAO->{$daoField};
                                     break;
                             }
                         }
                     }
                 } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                     $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]);
                     $relationQuery[$field]->convertToPseudoNames($relDAO);
                     foreach ($value as $relationField => $relationValue) {
                         if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                             $fieldValue = $relDAO->{$relationField};
                             if ($relationField == 'phone_type_id') {
                                 $fieldValue = $phoneTypes[$relationValue];
                             } elseif ($relationField == 'provider_id') {
                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                             } elseif (is_object($relDAO) && in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                 //special case for greeting replacement
                                 $fldValue = "{$relationField}_display";
                                 $fieldValue = $relDAO->{$fldValue};
                             }
                         } elseif (is_object($relDAO) && $relationField == 'state_province') {
                             $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
                         } elseif (is_object($relDAO) && $relationField == 'country') {
                             $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
                         } else {
                             $fieldValue = '';
                         }
                         $field = $field . '_';
                         if (array_key_exists($relationField, $multipleSelectFields)) {
                             $param = array($relationField => $fieldValue);
                             $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
                             CRM_Core_OptionGroup::lookupValues($param, $names, FALSE);
                             $fieldValue = $param[$relationField];
                         }
                         if (is_object($relDAO) && $relationField == 'id') {
                             $row[$field . $relationField] = $relDAO->contact_id;
                         } elseif (is_array($relationValue) && $relationField == 'location') {
                             foreach ($relationValue as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (!empty($type[1])) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     // CRM-3157: localise country, region (both have ‘country’ context)
                                     // and state_province (‘province’ context)
                                     switch (TRUE) {
                                         case !is_object($relDAO):
                                             $row[$field . '_' . $fldValue] = '';
                                             break;
                                         case in_array('country', $type):
                                         case in_array('world_region', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country'));
                                             break;
                                         case in_array('state_province', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province'));
                                             break;
                                         default:
                                             $row[$field . '_' . $fldValue] = $relDAO->{$fldValue};
                                             break;
                                     }
                                 }
                             }
                         } elseif (isset($fieldValue) && $fieldValue != '') {
                             //check for custom data
                             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                 $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                             } else {
                                 //normal relationship fields
                                 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                 switch ($relationField) {
                                     case 'country':
                                     case 'world_region':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                         break;
                                     case 'state_province':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                         break;
                                     default:
                                         $row[$field . $relationField] = $fieldValue;
                                         break;
                                 }
                             }
                         } else {
                             // if relation field is empty or null
                             $row[$field . $relationField] = '';
                         }
                     }
                 } elseif (isset($fieldValue) && $fieldValue != '') {
                     //check for custom data
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                     } elseif (array_key_exists($field, $multipleSelectFields)) {
                         //option group fixes
                         $paramsNew = array($field => $fieldValue);
                         if ($field == 'test_tutoring') {
                             $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                             // for  readers group
                         } elseif (substr($field, 0, 4) == 'cmr_') {
                             $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                         } else {
                             $name = array($field => array('newName' => $field, 'groupName' => $field));
                         }
                         CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                         $row[$field] = $paramsNew[$field];
                     } elseif (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                         //special case for greeting replacement
                         $fldValue = "{$field}_display";
                         $row[$field] = $iterationDAO->{$fldValue};
                     } else {
                         //normal fields with a touch of CRM-3157
                         switch ($field) {
                             case 'country':
                             case 'world_region':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                 break;
                             case 'state_province':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                 break;
                             case 'gender':
                             case 'preferred_communication_method':
                             case 'preferred_mail_format':
                             case 'communication_style':
                                 $row[$field] = $i18n->crm_translate($fieldValue);
                                 break;
                             default:
                                 $row[$field] = $fieldValue;
                                 break;
                         }
                     }
                 } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                     $paymentData = CRM_Utils_Array::value($iterationDAO->{$paymentTableId}, $paymentDetails);
                     $payFieldMapper = array('componentPaymentField_total_amount' => 'total_amount', 'componentPaymentField_contribution_status' => 'contribution_status', 'componentPaymentField_payment_instrument' => 'pay_instru', 'componentPaymentField_transaction_id' => 'trxn_id', 'componentPaymentField_received_date' => 'receive_date');
                     $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
                 } else {
                     // if field is empty or null
                     $row[$field] = '';
                 }
             }
             // add payment headers if required
             if ($addPaymentHeader && $paymentFields) {
                 $headerRows = array_merge($headerRows, $paymentHeaders);
                 foreach (array_keys($paymentHeaders) as $paymentHdr) {
                     self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
                 }
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = FALSE;
             // If specific payment fields have been selected for export, payment
             // data will already be in $row. Otherwise, add payment related
             // information, if appropriate.
             if ($addPaymentHeader) {
                 if (!$selectedPaymentFields) {
                     if ($paymentFields) {
                         $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
                         if (!is_array($paymentData) || empty($paymentData)) {
                             $paymentData = $nullContributionDetails;
                         }
                         $row = array_merge($row, $paymentData);
                     } elseif (!empty($paymentDetails)) {
                         $row = array_merge($row, $nullContributionDetails);
                     }
                 }
             }
             //remove organization name for individuals if it is set for current employer
             if (!empty($row['contact_type']) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) {
                 $row['organization_name'] = '';
             }
             // add component info
             // write the row to a file
             $componentDetails[] = $row;
             // output every $tempRowCount rows
             if ($count % $tempRowCount == 0) {
                 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
                 $componentDetails = array();
             }
         }
         $dao->free();
         $offset += $rowCount;
     }
     if ($exportTempTable) {
         self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
         // do merge same address and merge same household processing
         if ($mergeSameAddress) {
             self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
         }
         // merge the records if they have corresponding households
         if ($mergeSameHousehold) {
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
         }
         // fix the headers for rows with relationship type
         if (!empty($relName)) {
             self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
         }
         // if postalMailing option is checked, exclude contacts who are deceased, have
         // "Do not mail" privacy setting, or have no street address
         if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && $exportParams['postal_mailing_export']['postal_mailing_export'] == 1) {
             self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         }
         // call export hook
         CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // now write the CSV file
         self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // delete the export temp table and component table
         $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
         CRM_Core_DAO::executeQuery($sql);
         CRM_Utils_System::civiExit();
     } else {
         CRM_Core_Error::fatal(ts('No records to export'));
     }
 }
Ejemplo n.º 19
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Ejemplo n.º 20
0
 function alterParticipantRole($value)
 {
     if (empty($value)) {
         return;
     }
     $roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
     $value = array();
     foreach ($roles as $role) {
         $value[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE);
     }
     return implode(', ', $value);
 }
Ejemplo n.º 21
0
 /**
  * This function update contribution as well as related objects.
  */
 function transitionComponents($params, $processContributionObject = false)
 {
     // get minimum required values.
     $contactId = CRM_Utils_Array::value('contact_id', $params);
     $componentId = CRM_Utils_Array::value('component_id', $params);
     $componentName = CRM_Utils_Array::value('componentName', $params);
     $contributionId = CRM_Utils_Array::value('contribution_id', $params);
     $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
     // if we already processed contribution object pass previous status id.
     $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
     $updateResult = array();
     require_once 'CRM/Contribute/PseudoConstant.php';
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name');
     // we process only ( Completed, Cancelled, or Failed ) contributions.
     if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) {
         return $updateResult;
     }
     if (!$componentName || !$componentId) {
         // get the related component details.
         $componentDetails = self::getComponentDetails($contributionId);
     } else {
         $componentDetails['contact_id'] = $contactId;
         $componentDetails['component'] = $componentName;
         if ($componentName = 'event') {
             $componentDetails['participant'] = $componentId;
         } else {
             $componentDetails['membership'] = $componentId;
         }
     }
     if (CRM_Utils_Array::value('contact_id', $componentDetails)) {
         $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id');
     }
     // do check for required ids.
     if (!CRM_Utils_Array::value('membership', $componentDetails) && !CRM_Utils_Array::value('participant', $componentDetails) && !CRM_Utils_Array::value('pledge_payment', $componentDetails) || !CRM_Utils_Array::value('contact_id', $componentDetails)) {
         return $updateResult;
     }
     //now we are ready w/ required ids, start processing.
     require_once 'CRM/Core/Payment/BaseIPN.php';
     $baseIPN = new CRM_Core_Payment_BaseIPN();
     $input = $ids = $objects = array();
     $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
     $ids['contribution'] = $contributionId;
     $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
     $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
     $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
     $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
     $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
     $ids['contributionRecur'] = null;
     $ids['contributionPage'] = null;
     if (!$baseIPN->validateData($input, $ids, $objects, false)) {
         CRM_Core_Error::fatal();
     }
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $pledgePayment =& $objects['pledge_payment'];
     $contribution =& $objects['contribution'];
     if ($pledgePayment) {
         require_once 'CRM/Pledge/BAO/Payment.php';
         $pledgePaymentIDs = array();
         foreach ($pledgePayment as $key => $object) {
             $pledgePaymentIDs[] = $object->id;
         }
         $pledgeID = $pledgePayment[0]->pledge_id;
     }
     require_once 'CRM/Event/PseudoConstant.php';
     require_once 'CRM/Event/BAO/Participant.php';
     require_once 'CRM/Pledge/BAO/Pledge.php';
     require_once 'CRM/Member/PseudoConstant.php';
     require_once 'CRM/Member/BAO/Membership.php';
     $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
     if ($participant) {
         $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
         $oldStatus = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participant->id, 'status_id');
     }
     // we might want to process contribution object.
     $processContribution = false;
     if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
         if ($membership) {
             $membership->status_id = array_search('Cancelled', $membershipStatuses);
             $membership->save();
             $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($participant) {
             $updatedStatusId = array_search('Cancelled', $participantStatuses);
             CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
             $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($pledgePayment) {
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
             $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
     } else {
         if ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
             if ($membership) {
                 $membership->status_id = array_search('Expired', $membershipStatuses);
                 $membership->save();
                 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($participant) {
                 $updatedStatusId = array_search('Cancelled', $participantStatuses);
                 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($pledgePayment) {
                 CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
         } else {
             if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
                 // only pending contribution related object processed.
                 if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) {
                     // this is case when we already processed contribution object.
                     return $updateResult;
                 } else {
                     if (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
                         // this is case when we will going to process contribution object.
                         return $updateResult;
                     }
                 }
                 if ($membership) {
                     $format = '%Y%m%d';
                     require_once 'CRM/Member/BAO/MembershipType.php';
                     //CRM-4523
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     if ($currentMembership) {
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     require_once 'CRM/Member/BAO/MembershipStatus.php';
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format));
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                     $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     require_once 'CRM/Member/BAO/MembershipLog.php';
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y');
                     $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($participant) {
                     $updatedStatusId = array_search('Registered', $participantStatuses);
                     CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                     $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($pledgePayment) {
                     CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                     $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
             }
         }
     }
     // process contribution object.
     if ($processContribution) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contributionParams = array();
         $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'contribution_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number');
         foreach ($fields as $field) {
             if (!CRM_Utils_Array::value($field, $params)) {
                 continue;
             }
             $contributionParams[$field] = $params[$field];
         }
         $ids = array('contribution' => $contributionId);
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
     }
     return $updateResult;
 }
Ejemplo n.º 22
0
 /**
  * make sure that the user has permission to access this event
  *
  * @param int $id   the id of the event
  * @param int $name the name or title of the event
  *
  * @return string   the permission that the user has (or null)
  * @access public
  * @static
  */
 static function checkPermission($eventId = null, $type = CRM_Core_Permission::VIEW)
 {
     static $permissions = null;
     if (empty($permissions)) {
         require_once 'CRM/ACL/API.php';
         require_once 'CRM/Event/PseudoConstant.php';
         $allEvents = CRM_Event_PseudoConstant::event(null, true);
         $createdEvents = array();
         $session =& CRM_Core_Session::singleton();
         if ($userID = $session->get('userID')) {
             $createdEvents = array_keys(CRM_Event_PseudoConstant::event(null, true, "created_id={$userID}"));
         }
         // Note: for a multisite setup, a user with edit all events, can edit all events
         // including those from other sites
         if (CRM_Core_Permission::check('edit all events')) {
             $permissions[CRM_Core_Permission::EDIT] = array_keys($allEvents);
         } else {
             $permissions[CRM_Core_Permission::EDIT] =& CRM_ACL_API::group(CRM_Core_Permission::EDIT, null, 'civicrm_event', $allEvents, $createdEvents);
         }
         if (CRM_Core_Permission::check('edit all events')) {
             $permissions[CRM_Core_Permission::VIEW] = array_keys($allEvents);
         } else {
             if (CRM_Core_Permission::check('access CiviEvent') && CRM_Core_Permission::check('view event participants')) {
                 // use case: allow "view all events" but NOT "edit all events"
                 // so for a normal site allow users with these two permissions to view all events AND
                 // at the same time also allow any hook to override if needed.
                 $createdEvents = array_keys($allEvents);
             }
             $permissions[CRM_Core_Permission::VIEW] =& CRM_ACL_API::group(CRM_Core_Permission::VIEW, null, 'civicrm_event', $allEvents, $createdEvents);
         }
         $permissions[CRM_Core_Permission::DELETE] = array();
         if (CRM_Core_Permission::check('delete in CiviEvent')) {
             // Note: we want to restrict the scope of delete permission to
             // events that are editable/viewable (usecase multisite).
             // We can remove array_intersect once we have ACL support for delete functionality.
             $permissions[CRM_Core_Permission::DELETE] = array_intersect($permissions[CRM_Core_Permission::EDIT], $permissions[CRM_Core_Permission::VIEW]);
         }
     }
     if ($eventId) {
         return in_array($eventId, $permissions[$type]) ? true : false;
     }
     return $permissions;
 }
Ejemplo n.º 23
0
 /**
  * Set variables up before form is built.
  *
  * @return void
  */
 public function preProcess()
 {
     $values = $ids = array();
     $participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $params = array('id' => $participantID);
     CRM_Event_BAO_Participant::getValues($params, $values, $ids);
     if (empty($values)) {
         CRM_Core_Error::statusBounce(ts('The requested participant record does not exist (possibly the record was deleted).'));
     }
     CRM_Event_BAO_Participant::resolveDefaults($values[$participantID]);
     if (!empty($values[$participantID]['fee_level'])) {
         CRM_Event_BAO_Participant::fixEventLevel($values[$participantID]['fee_level']);
     }
     $this->assign('contactId', $contactID);
     $this->assign('participantId', $participantID);
     $paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $participantID, 'id', 'participant_id');
     $this->assign('hasPayment', $paymentId);
     if ($parentParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'registered_by_id')) {
         $parentHasPayment = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $parentParticipantId, 'id', 'participant_id');
         $this->assign('parentHasPayment', $parentHasPayment);
     }
     $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'status_id', 'id');
     $status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id');
     $status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id');
     if ($status == 'Transferred') {
         $transferId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'transferred_to_contact_id', 'id');
         $pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $transferId, 'id', 'contact_id');
         $transferName = current(CRM_Contact_BAO_Contact::getContactDetails($transferId));
         $this->assign('pid', $pid);
         $this->assign('transferId', $transferId);
         $this->assign('transferName', $transferName);
     }
     $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
     if ($values[$participantID]['is_test']) {
         $values[$participantID]['status'] .= ' (test) ';
     }
     // Get Note
     $noteValue = CRM_Core_BAO_Note::getNote($participantID, 'civicrm_participant');
     $values[$participantID]['note'] = array_values($noteValue);
     // Get Line Items
     $lineItem = CRM_Price_BAO_LineItem::getLineItems($participantID);
     if (!CRM_Utils_System::isNull($lineItem)) {
         $values[$participantID]['lineItem'][] = $lineItem;
     }
     $values[$participantID]['totalAmount'] = CRM_Utils_Array::value('fee_amount', $values[$participantID]);
     // Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859)
     if (!empty($values[$participantID]['participant_registered_by_id'])) {
         $values[$participantID]['registered_by_contact_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $values[$participantID]['participant_registered_by_id'], 'contact_id', 'id');
         $values[$participantID]['registered_by_display_name'] = CRM_Contact_BAO_Contact::displayName($values[$participantID]['registered_by_contact_id']);
     }
     // Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true  (CRM-4859)
     if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantID)) {
         $values[$participantID]['additionalParticipants'] = CRM_Event_BAO_Participant::getAdditionalParticipants($participantID);
     }
     // get the option value for custom data type
     $roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
     $eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
     $eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name');
     $allRoleIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $values[$participantID]['role_id']);
     $groupTree = array();
     $finalTree = array();
     foreach ($allRoleIDs as $k => $v) {
         $roleGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $v, $roleCustomDataTypeID);
         $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $values[$participantID]['event_id'], $eventNameCustomDataTypeID);
         $eventTypeID = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $values[$participantID]['event_id'], 'event_type_id', 'id');
         $eventTypeGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $eventTypeID, $eventTypeCustomDataTypeID);
         $groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree);
         $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $eventTypeGroupTree);
         $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID));
         foreach ($groupTree as $treeId => $trees) {
             $finalTree[$treeId] = $trees;
         }
     }
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $finalTree, FALSE, NULL, NULL, NULL, $participantID);
     $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values[$participantID]['event_id'], 'title');
     //CRM-7150, show event name on participant view even if the event is disabled
     if (empty($values[$participantID]['event'])) {
         $values[$participantID]['event'] = $eventTitle;
     }
     //do check for campaigns
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $values[$participantID])) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $values[$participantID]['campaign'] = $campaigns[$campaignId];
     }
     $this->assign($values[$participantID]);
     // add viewed participant to recent items list
     $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home");
     $recentOther = array();
     if (CRM_Core_Permission::check('edit event participants')) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=update&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home");
     }
     if (CRM_Core_Permission::check('delete in CiviEvent')) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=delete&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home");
     }
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $displayName = CRM_Contact_BAO_Contact::displayName($values[$participantID]['contact_id']);
     $participantCount = array();
     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     $totalTaxAmount = 0;
     foreach ($lineItem as $k => $v) {
         if (CRM_Utils_Array::value('participant_count', $lineItem[$k]) > 0) {
             $participantCount[] = $lineItem[$k]['participant_count'];
         }
         $totalTaxAmount = $v['tax_amount'] + $totalTaxAmount;
     }
     if ($invoicing) {
         $this->assign('totalTaxAmount', $totalTaxAmount);
     }
     if ($participantCount) {
         $this->assign('pricesetFieldsCount', $participantCount);
     }
     $this->assign('displayName', $displayName);
     // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
     CRM_Utils_System::setTitle(ts('View Event Registration for') . ' ' . $displayName);
     $roleId = CRM_Utils_Array::value('role_id', $values[$participantID]);
     $title = $displayName . ' (' . CRM_Utils_Array::value($roleId, $participantRoles) . ' - ' . $eventTitle . ')';
     $sep = CRM_Core_DAO::VALUE_SEPARATOR;
     $viewRoles = array();
     foreach (explode($sep, $values[$participantID]['role_id']) as $k => $v) {
         $viewRoles[] = $participantRoles[$v];
     }
     $values[$participantID]['role_id'] = implode(', ', $viewRoles);
     $this->assign('role', $values[$participantID]['role_id']);
     // add Participant to Recent Items
     CRM_Utils_Recent::add($title, $url, $values[$participantID]['id'], 'Participant', $values[$participantID]['contact_id'], NULL, $recentOther);
 }
Ejemplo n.º 24
0
 static function updatePendingOnlineContribution($participantId, $statusId)
 {
     if (!$participantId || !$statusId) {
         return;
     }
     $contributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($participantId, 'Event');
     if (!$contributionId) {
         return;
     }
     //status rules.
     //1. participant - positive => contribution - completed.
     //2. participant - negative => contribution - cancelled.
     $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
     $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $contributionStatusId = NULL;
     if (array_key_exists($statusId, $positiveStatuses)) {
         $contributionStatusId = array_search('Completed', $contributionStatuses);
     }
     if (array_key_exists($statusId, $negativeStatuses)) {
         $contributionStatusId = array_search('Cancelled', $contributionStatuses);
     }
     if (!$contributionStatusId) {
         return;
     }
     $params = array('component_id' => $participantId, 'componentName' => 'Event', 'contribution_id' => $contributionId, 'contribution_status_id' => $contributionStatusId);
     //change related contribution status.
     $updatedStatusId = CRM_Core_Payment_BaseIPN::updateContributionStatus($params);
     return $updatedStatusId;
 }
 /**
  * Alter display of rows.
  *
  * Iterate through the rows retrieved via SQL and make changes for display purposes,
  * such as rendering contacts as links.
  *
  * @param array $rows
  *   Rows generated by SQL, with an array for each row.
  */
 public function alterDisplay(&$rows)
 {
     $entryFound = FALSE;
     $eventType = CRM_Core_OptionGroup::values('event_type');
     $financialTypes = CRM_Contribute_PseudoConstant::financialType();
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
     foreach ($rows as $rowNum => $row) {
         // make count columns point to detail report
         // convert display name to links
         if (array_key_exists('civicrm_participant_event_id', $row)) {
             $eventId = $row['civicrm_participant_event_id'];
             if ($eventId) {
                 $rows[$rowNum]['civicrm_participant_event_id'] = CRM_Event_PseudoConstant::event($eventId, FALSE);
                 $url = CRM_Report_Utils_Report::getNextUrl('event/income', 'reset=1&force=1&id_op=in&id_value=' . $eventId, $this->_absoluteUrl, $this->_id, $this->_drilldownReport);
                 $rows[$rowNum]['civicrm_participant_event_id_link'] = $url;
                 $rows[$rowNum]['civicrm_participant_event_id_hover'] = ts("View Event Income Details for this Event");
             }
             $entryFound = TRUE;
         }
         // handle event type id
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_event_event_type_id', $rowNum, $eventType);
         // handle participant status id
         if (array_key_exists('civicrm_participant_status_id', $row)) {
             $statusId = $row['civicrm_participant_status_id'];
             if ($statusId) {
                 $rows[$rowNum]['civicrm_participant_status_id'] = CRM_Event_PseudoConstant::participantStatus($statusId, FALSE, 'label');
             }
             $entryFound = TRUE;
         }
         // handle participant role id
         if (array_key_exists('civicrm_participant_role_id', $row)) {
             $roleId = $row['civicrm_participant_role_id'];
             if ($roleId) {
                 $roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $roleId);
                 $roleId = array();
                 foreach ($roles as $role) {
                     $roleId[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE);
                 }
                 $rows[$rowNum]['civicrm_participant_role_id'] = implode(', ', $roleId);
             }
             $entryFound = TRUE;
         }
         // Handel value seperator in Fee Level
         if (array_key_exists('civicrm_participant_participant_fee_level', $row)) {
             $feeLevel = $row['civicrm_participant_participant_fee_level'];
             if ($feeLevel) {
                 CRM_Event_BAO_Participant::fixEventLevel($feeLevel);
                 $rows[$rowNum]['civicrm_participant_participant_fee_level'] = $feeLevel;
             }
             $entryFound = TRUE;
         }
         // Convert display name to link
         $displayName = CRM_Utils_Array::value('civicrm_contact_sort_name_linked', $row);
         $cid = CRM_Utils_Array::value('civicrm_contact_id', $row);
         $id = CRM_Utils_Array::value('civicrm_participant_participant_record', $row);
         if ($displayName && $cid && $id) {
             $url = CRM_Report_Utils_Report::getNextUrl('contact/detail', "reset=1&force=1&id_op=eq&id_value={$cid}", $this->_absoluteUrl, $this->_id, $this->_drilldownReport);
             $viewUrl = CRM_Utils_System::url("civicrm/contact/view/participant", "reset=1&id={$id}&cid={$cid}&action=view&context=participant");
             $contactTitle = ts('View Contact Details');
             $participantTitle = ts('View Participant Record');
             $rows[$rowNum]['civicrm_contact_sort_name_linked'] = "<a title='{$contactTitle}' href={$url}>{$displayName}</a>";
             if ($this->_outputMode !== 'csv') {
                 $rows[$rowNum]['civicrm_contact_sort_name_linked'] .= "<span style='float: right;'><a title='{$participantTitle}' href={$viewUrl}>" . ts('View') . "</a></span>";
             }
             $entryFound = TRUE;
         }
         // Handle country id
         if (array_key_exists('civicrm_address_country_id', $row)) {
             $countryId = $row['civicrm_address_country_id'];
             if ($countryId) {
                 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($countryId, TRUE);
             }
             $entryFound = TRUE;
         }
         // Handle state/province id
         if (array_key_exists('civicrm_address_state_province_id', $row)) {
             $provinceId = $row['civicrm_address_state_province_id'];
             if ($provinceId) {
                 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($provinceId, TRUE);
             }
             $entryFound = TRUE;
         }
         // Handle employer id
         if (array_key_exists('civicrm_contact_employer_id', $row)) {
             $employerId = $row['civicrm_contact_employer_id'];
             if ($employerId) {
                 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId);
                 $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl);
                 $rows[$rowNum]['civicrm_contact_employer_id_link'] = $url;
                 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for this Contact.');
             }
         }
         // Convert campaign_id to campaign title
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_participant_campaign_id', $rowNum, $this->activeCampaigns);
         // handle contribution status
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_contribution_status_id', $rowNum, $contributionStatus);
         // handle payment instrument
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_payment_instrument_id', $rowNum, $paymentInstruments);
         // handle financial type
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_financial_type_id', $rowNum, $financialTypes);
         $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'event/participantListing', 'View Event Income Details') ? TRUE : $entryFound;
         // display birthday in the configured custom format
         if (array_key_exists('civicrm_contact_birth_date', $row)) {
             $birthDate = $row['civicrm_contact_birth_date'];
             if ($birthDate) {
                 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
             }
             $entryFound = TRUE;
         }
         // skip looking further in rows, if first row itself doesn't
         // have the column we need
         if (!$entryFound) {
             break;
         }
     }
 }
Ejemplo n.º 26
0
 /**
  * Function to record additional payment for partial and refund contributions.
  *
  * @param int $contributionId
  *   is the invoice contribution id (got created after processing participant payment).
  * @param array $trxnsData
  *   to take user provided input of transaction details.
  * @param string $paymentType
  *   'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
  * @param int $participantId
  *
  * @return null|object
  */
 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL)
 {
     $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
     $getInfoOf['id'] = $contributionId;
     $defaults = array();
     $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
     if ($paymentType == 'owed') {
         // build params for recording financial trxn entry
         $params['contribution'] = $contributionDAO;
         $params = array_merge($defaults, $params);
         $params['skipLineItem'] = TRUE;
         $params['partial_payment_total'] = $contributionDAO->total_amount;
         $params['partial_amount_pay'] = $trxnsData['total_amount'];
         $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
         $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
         // record the entry
         $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
         $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
         if (!empty($trxnId)) {
             $trxnId = $trxnId['trxn_id'];
         } elseif (!empty($contributionDAO->payment_instrument_id)) {
             $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
         } else {
             $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
             $queryParams = array(1 => array($relationTypeId, 'Integer'));
             $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
         }
         // update statuses
         // criteria for updates contribution total_amount == financial_trxns of partial_payments
         $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total\nFROM civicrm_financial_trxn ft\nLEFT JOIN civicrm_entity_financial_trxn eft\n  ON (ft.id = eft.financial_trxn_id)\nWHERE eft.entity_table = 'civicrm_contribution'\n  AND eft.entity_id = {$contributionId}\n  AND ft.to_financial_account_id != {$toFinancialAccount}\n  AND ft.status_id = {$statusId}\n";
         $query = CRM_Core_DAO::executeQuery($sql);
         $query->fetch();
         $sumOfPayments = $query->sum_of_payments;
         // update statuses
         if ($contributionDAO->total_amount == $sumOfPayments) {
             // update contribution status and
             // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
             $contributionDAO->contribution_status_id = $statusId;
             $contributionDAO->cancel_date = 'null';
             $contributionDAO->cancel_reason = NULL;
             $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount'];
             $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
             $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
             $contributionDAO->save();
             //Change status of financial record too
             $financialTrxn->status_id = $statusId;
             $financialTrxn->save();
             // note : not using the self::add method,
             // the reason because it performs 'status change' related code execution for financial records
             // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
             // are coded below i.e. just updating financial_item status to 'Paid'
             if ($participantId) {
                 // update participant status
                 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
                 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
                 foreach ($ids as $val) {
                     $participantUpdate['id'] = $val;
                     $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
                     CRM_Event_BAO_Participant::add($participantUpdate);
                 }
             }
             // update financial item statuses
             $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
             $paidStatus = array_search('Paid', $financialItemStatus);
             $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
             $sqlFinancialItemUpdate = "\nUPDATE civicrm_financial_item fi\n  LEFT JOIN civicrm_entity_financial_trxn eft\n    ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')\nSET status_id = {$paidStatus}\nWHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})\n";
             CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
         }
     } elseif ($paymentType == 'refund') {
         // build params for recording financial trxn entry
         $params['contribution'] = $contributionDAO;
         $params = array_merge($defaults, $params);
         $params['skipLineItem'] = TRUE;
         $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
         $trxnsData['total_amount'] = -$trxnsData['total_amount'];
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
         $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
         // record the entry
         $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
         // note : not using the self::add method,
         // the reason because it performs 'status change' related code execution for financial records
         // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
         // are coded below i.e. just updating financial_item status to 'Paid'
         $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
         // add financial item entry
         $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
         $getLine['entity_id'] = $contributionDAO->id;
         $getLine['entity_table'] = 'civicrm_contribution';
         $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
         if (!empty($lineItemId->id)) {
             $addFinancialEntry = array('transaction_date' => $financialTrxn->trxn_date, 'contact_id' => $contributionDAO->contact_id, 'amount' => $financialTrxn->total_amount, 'status_id' => array_search('Paid', $financialItemStatus), 'entity_id' => $lineItemId->id, 'entity_table' => 'civicrm_line_item');
             $trxnIds['id'] = $financialTrxn->id;
             CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
         }
         if ($participantId) {
             // update participant status
             $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
             $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
             foreach ($ids as $val) {
                 $participantUpdate['id'] = $val;
                 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
                 CRM_Event_BAO_Participant::add($participantUpdate);
             }
         }
     }
     // activity creation
     if (!empty($financialTrxn)) {
         if ($participantId) {
             $inputParams['id'] = $participantId;
             $values = array();
             $ids = array();
             $component = 'event';
             $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
             $entityObj = $entityObj[$participantId];
         }
         $activityType = $paymentType == 'refund' ? 'Refund' : 'Payment';
         self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
     }
     return $financialTrxn;
 }
Ejemplo n.º 27
0
 /**
  * @return mixed
  */
 public static function get_pending_in_cart_status_id()
 {
     $status_types = CRM_Event_PseudoConstant::participantStatus(NULL, "name='Pending in cart'");
     $status_names = array_keys($status_types);
     return end($status_names);
 }
Ejemplo n.º 28
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     //need to assign custom data type and subtype to the template
     $this->assign('customDataType', 'Event');
     if ($this->_eventType) {
         $this->assign('customDataSubType', $this->_eventType);
     }
     $this->assign('entityId', $this->_id);
     $this->_first = TRUE;
     $this->applyFilter('__ALL__', 'trim');
     $attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
     if ($this->_isTemplate) {
         $this->add('text', 'template_title', ts('Template Title'), $attributes['template_title'], TRUE);
     }
     if ($this->_action & CRM_Core_Action::ADD) {
         $eventTemplates = CRM_Event_PseudoConstant::eventTemplates();
         if (CRM_Utils_System::isNull($eventTemplates) && !$this->_isTemplate) {
             $url = CRM_Utils_System::url('civicrm/admin/eventTemplate', array('reset' => 1));
             CRM_Core_Session::setStatus(ts('If you find that you are creating multiple events with similar settings, you may want to use the <a href="%1">Event Templates</a> feature to streamline your workflow.', array(1 => $url)), ts('Tip'), 'info');
         }
         if (!CRM_Utils_System::isNull($eventTemplates)) {
             $this->add('select', 'template_id', ts('From Template'), array('' => ts('- select -')) + $eventTemplates, FALSE, array('class' => 'crm-select2 huge'));
         }
         // Make sure this form redirects properly
         $this->preventAjaxSubmit();
     }
     // add event title, make required if this is not a template
     $this->add('text', 'title', ts('Event Title'), $attributes['event_title'], !$this->_isTemplate);
     $this->addSelect('event_type_id', array('onChange' => "CRM.buildCustomData( 'Event', this.value );"), TRUE);
     //CRM-7362 --add campaigns.
     $campaignId = NULL;
     if ($this->_id) {
         $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'campaign_id');
     }
     CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
     $this->addSelect('default_role_id', array(), TRUE);
     $this->addSelect('participant_listing_id', array('placeholder' => ts('Disabled'), 'option_url' => NULL));
     $this->add('textarea', 'summary', ts('Event Summary'), $attributes['summary']);
     $this->add('wysiwyg', 'description', ts('Complete Description'), $attributes['event_description']);
     $this->addElement('checkbox', 'is_public', ts('Public Event'));
     $this->addElement('checkbox', 'is_share', ts('Allow sharing through social media?'));
     $this->addElement('checkbox', 'is_map', ts('Include Map to Event Location'));
     $this->addDateTime('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDateTime'));
     $this->addDateTime('end_date', ts('End Date / Time'), FALSE, array('formatType' => 'activityDateTime'));
     $this->add('text', 'max_participants', ts('Max Number of Participants'), array('onchange' => "if (this.value != '') {cj('#id-waitlist').show(); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false); showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); return;} else {cj('#id-event_full, #id-waitlist, #id-waitlist-text').hide(); return;}"));
     $this->addRule('max_participants', ts('Max participants should be a positive number'), 'positiveInteger');
     $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
     $waitlist = 0;
     if (in_array('On waitlist', $participantStatuses) and in_array('Pending from waitlist', $participantStatuses)) {
         $this->addElement('checkbox', 'has_waitlist', ts('Offer a Waitlist?'), NULL, array('onclick' => "showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false);"));
         $this->add('textarea', 'waitlist_text', ts('Waitlist Message'), $attributes['waitlist_text']);
         $waitlist = 1;
     }
     $this->assign('waitlist', $waitlist);
     $this->add('textarea', 'event_full_text', ts('Message if Event Is Full'), $attributes['event_full_text']);
     $this->addElement('checkbox', 'is_active', ts('Is this Event Active?'));
     $this->addFormRule(array('CRM_Event_Form_ManageEvent_EventInfo', 'formRule'));
     parent::buildQuickForm();
 }
Ejemplo n.º 29
0
 /**
  * Process Registration of free event.
  *
  * @param array $params
  *   Form values.
  * @param int $contactID
  */
 public function processRegistration($params, $contactID = NULL)
 {
     $session = CRM_Core_Session::singleton();
     $this->_participantInfo = array();
     // CRM-4320, lets build array of cancelled additional participant ids
     // those are drop or skip by primary at the time of confirmation.
     // get all in and then unset those are confirmed.
     $cancelledIds = $this->_additionalParticipantIds;
     $participantCount = array();
     foreach ($params as $participantNum => $record) {
         if ($record == 'skip') {
             $participantCount[$participantNum] = 'skip';
         } elseif ($participantNum) {
             $participantCount[$participantNum] = 'participant';
         }
     }
     $registerByID = NULL;
     foreach ($params as $key => $value) {
         if ($value != 'skip') {
             $fields = NULL;
             // setting register by Id and unset contactId.
             if (empty($value['is_primary'])) {
                 $contactID = NULL;
                 $registerByID = $this->get('registerByID');
                 if ($registerByID) {
                     $value['registered_by_id'] = $registerByID;
                 }
                 // get an email if one exists for the participant
                 $participantEmail = '';
                 foreach (array_keys($value) as $valueName) {
                     if (substr($valueName, 0, 6) == 'email-') {
                         $participantEmail = $value[$valueName];
                     }
                 }
                 if ($participantEmail) {
                     $this->_participantInfo[] = $participantEmail;
                 } else {
                     $this->_participantInfo[] = $value['first_name'] . ' ' . $value['last_name'];
                 }
             } elseif (!empty($value['contact_id'])) {
                 $contactID = $value['contact_id'];
             } else {
                 $contactID = $this->getContactID();
             }
             CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
             //for free event or additional participant, dont create billing email address.
             if (empty($value['is_primary']) || !$this->_values['event']['is_monetary']) {
                 unset($value["email-{$this->_bltID}"]);
             }
             $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
             // lets store the contactID in the session
             // we dont store in userID in case the user is doing multiple
             // transactions etc
             // for things like tell a friend
             if (!$this->getContactID() && !empty($value['is_primary'])) {
                 $session->set('transaction.userID', $contactID);
             }
             //lets get the status if require approval or waiting.
             $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($this->_allowWaitlist && !$this->_allowConfirmation) {
                 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
             } elseif ($this->_requireApproval && !$this->_allowConfirmation) {
                 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
             }
             $this->set('value', $value);
             $this->confirmPostProcess($contactID, NULL, NULL);
             //lets get additional participant id to cancel.
             if ($this->_allowConfirmation && is_array($cancelledIds)) {
                 $additonalId = CRM_Utils_Array::value('participant_id', $value);
                 if ($additonalId && ($key = array_search($additonalId, $cancelledIds))) {
                     unset($cancelledIds[$key]);
                 }
             }
         }
     }
     // update status and send mail to cancelled additional participants, CRM-4320
     if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
         $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
         CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
     }
     //set information about additional participants if exists
     if (count($this->_participantInfo)) {
         $this->set('participantInfo', $this->_participantInfo);
     }
     //send mail Confirmation/Receipt
     if ($this->_contributeMode != 'checkout' || $this->_contributeMode != 'notify') {
         $isTest = FALSE;
         if ($this->_action & CRM_Core_Action::PREVIEW) {
             $isTest = TRUE;
         }
         //handle if no additional participant.
         if (!$registerByID) {
             $registerByID = $this->get('registerByID');
         }
         $primaryContactId = $this->get('primaryContactId');
         //build an array of custom profile and assigning it to template.
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
         //lets carry all participant params w/ values.
         foreach ($additionalIDs as $participantID => $contactId) {
             $participantNum = NULL;
             if ($participantID == $registerByID) {
                 $participantNum = 0;
             } else {
                 if ($participantNum = array_search('participant', $participantCount)) {
                     unset($participantCount[$participantNum]);
                 }
             }
             if ($participantNum === NULL) {
                 break;
             }
             //carry the participant submitted values.
             $this->_values['params'][$participantID] = $params[$participantNum];
         }
         //lets send  mails to all with meanigful text, CRM-4320.
         $this->assign('isOnWaitlist', $this->_allowWaitlist);
         $this->assign('isRequireApproval', $this->_requireApproval);
         foreach ($additionalIDs as $participantID => $contactId) {
             if ($participantID == $registerByID) {
                 //set as Primary Participant
                 $this->assign('isPrimary', 1);
                 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
                 if (count($customProfile)) {
                     $this->assign('customProfile', $customProfile);
                     $this->set('customProfile', $customProfile);
                 }
             } else {
                 $this->assign('isPrimary', 0);
                 $this->assign('customProfile', NULL);
             }
             //send Confirmation mail to Primary & additional Participants if exists
             CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
         }
     }
 }
 function alterDisplay(&$rows)
 {
     if (is_array($rows)) {
         $eventType = CRM_Core_OptionGroup::values('event_type');
         foreach ($rows as $rowNum => $row) {
             if (array_key_exists('civicrm_event_title', $row)) {
                 if ($value = $row['civicrm_event_id']) {
                     CRM_Event_PseudoConstant::event($value, FALSE);
                     $url = CRM_Report_Utils_Report::getNextUrl('event/participantlist', 'reset=1&force=1&event_id_op=eq&event_id_value=' . $value, $this->_absoluteUrl, $this->_id);
                     $rows[$rowNum]['civicrm_event_title_link'] = $url;
                     $rows[$rowNum]['civicrm_event_title_hover'] = ts("View Event Participants For this Event");
                 }
             }
             //handle event type
             if (array_key_exists('civicrm_event_event_type_id', $row)) {
                 if ($value = $row['civicrm_event_event_type_id']) {
                     $rows[$rowNum]['civicrm_event_event_type_id'] = $eventType[$value];
                 }
             }
         }
     }
 }