示例#1
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);
 }
示例#2
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess($params = null)
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $deleteParams = array('id' => $this->_activityId);
         CRM_Activity_BAO_Activity::deleteActivity($deleteParams);
         CRM_Core_Session::setStatus(ts("Selected Activity has been deleted sucessfully."));
         return;
     }
     // store the submitted values in an array
     if (!$params) {
         $params = $this->controller->exportValues($this->_name);
     }
     //set activity type id
     if (!CRM_Utils_Array::value('activity_type_id', $params)) {
         $params['activity_type_id'] = $this->_activityTypeId;
     }
     if (CRM_Utils_Array::value('hidden_custom', $params) && !isset($params['custom'])) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', false, false, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', false, false, null, null, true));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_activityId, 'Activity');
     }
     // store the date with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     // assigning formated value to related variable
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         $params['target_contact_id'] = explode(',', $params['target_contact_id']);
     } else {
         $params['target_contact_id'] = array();
     }
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = array();
     }
     // get ids for associated contacts
     if (!$params['source_contact_id']) {
         $params['source_contact_id'] = $this->_currentUserId;
     } else {
         $params['source_contact_id'] = $this->_submitValues['source_contact_qid'];
     }
     if (isset($this->_activityId)) {
         $params['id'] = $this->_activityId;
     }
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity', $this->_activityId);
     // format target params
     if (!$this->_single) {
         $params['target_contact_id'] = $this->_contactIds;
     }
     $activityAssigned = array();
     // format assignee params
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
         //skip those assignee contacts which are already assigned
         //while sending a copy.CRM-4509.
         $activityAssigned = array_flip($params['assignee_contact_id']);
         if ($this->_activityId) {
             $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($this->_activityId);
             $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
         }
     }
     // call begin post process. Idea is to let injecting file do
     // any processing before the activity is added/updated.
     $this->beginPostProcess($params);
     $activity = CRM_Activity_BAO_Activity::create($params);
     // call end post process. Idea is to let injecting file do any
     // processing needed, after the activity has been added/updated.
     $this->endPostProcess($params, $activity);
     // create follow up activity if needed
     $followupStatus = '';
     if (CRM_Utils_Array::value('followup_activity_type_id', $params)) {
         $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
         $followupStatus = "A followup activity has been scheduled.";
     }
     // send copy to assignee contacts.CRM-4509
     $mailStatus = '';
     $config =& CRM_Core_Config::singleton();
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id']) && $config->activityAssigneeNotification) {
         $mailToContacts = array();
         $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activity->id, true, false);
         //build an associative array with unique email addresses.
         foreach ($activityAssigned as $id => $dnc) {
             if (isset($id) && array_key_exists($id, $assigneeContacts)) {
                 $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
             }
         }
         if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
             //include attachments while sendig a copy of activity.
             $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
             require_once "CRM/Case/BAO/Case.php";
             $result = CRM_Case_BAO_Case::sendActivityCopy(null, $activity->id, $mailToContacts, $attachments, null);
             $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
         }
     }
     // set status message
     if (CRM_Utils_Array::value('subject', $params)) {
         $params['subject'] = "'" . $params['subject'] . "'";
     }
     CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2. %3', array(1 => $params['subject'], 2 => $followupStatus, 3 => $mailStatus)));
     return array('activity' => $activity);
 }
示例#3
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);
 }
示例#4
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}"));
     }
 }
示例#5
0
 /**
  * Process the form submission.
  *
  *
  * @param array $params
  * @return array|null
  */
 public function postProcess($params = NULL)
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $deleteParams = array('id' => $this->_activityId);
         $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($this->_activityId);
         CRM_Activity_BAO_Activity::deleteActivity($deleteParams, $moveToTrash);
         // delete tags for the entity
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus(ts("Selected Activity has been deleted successfully."), ts('Record Deleted'), 'success');
         return NULL;
     }
     // store the submitted values in an array
     if (!$params) {
         $params = $this->controller->exportValues($this->_name);
     }
     // Set activity type id.
     if (empty($params['activity_type_id'])) {
         $params['activity_type_id'] = $this->_activityTypeId;
     }
     if (!empty($params['hidden_custom']) && !isset($params['custom'])) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_activityId, 'Activity');
     }
     // store the date with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     // format params as arrays
     foreach (array('target', 'assignee', 'followup_assignee') as $name) {
         if (!empty($params["{$name}_contact_id"])) {
             $params["{$name}_contact_id"] = explode(',', $params["{$name}_contact_id"]);
         } else {
             $params["{$name}_contact_id"] = array();
         }
     }
     // get ids for associated contacts
     if (!$params['source_contact_id']) {
         $params['source_contact_id'] = $this->_currentUserId;
     }
     if (isset($this->_activityId)) {
         $params['id'] = $this->_activityId;
     }
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity', $this->_activityId);
     $activity = array();
     if (!empty($params['is_multi_activity']) && !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])) {
         $targetContacts = $params['target_contact_id'];
         foreach ($targetContacts as $targetContactId) {
             $params['target_contact_id'] = array($targetContactId);
             // save activity
             $activity[] = $this->processActivity($params);
         }
     } else {
         // save activity
         $activity = $this->processActivity($params);
     }
     $activityIds = empty($this->_activityIds) ? array($this->_activityId) : $this->_activityIds;
     foreach ($activityIds as $activityId) {
         // set params for repeat configuration in create mode
         $params['entity_id'] = $activityId;
         $params['entity_table'] = 'civicrm_activity';
         if (!empty($params['entity_id']) && !empty($params['entity_table'])) {
             $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($params['entity_id'], $params['entity_table']);
             if ($checkParentExistsForThisId) {
                 $params['parent_entity_id'] = $checkParentExistsForThisId;
                 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $params['entity_table']);
             } else {
                 $params['parent_entity_id'] = $params['entity_id'];
                 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($params['entity_id'], $params['entity_table']);
             }
             if (property_exists($scheduleReminderDetails, 'id')) {
                 $params['schedule_reminder_id'] = $scheduleReminderDetails->id;
             }
         }
         $params['dateColumns'] = array('activity_date_time');
         // Set default repetition start if it was not provided.
         if (empty($params['repetition_start_date'])) {
             $params['repetition_start_date'] = $params['activity_date_time'];
         }
         // unset activity id
         unset($params['id']);
         $linkedEntities = array(array('table' => 'civicrm_activity_contact', 'findCriteria' => array('activity_id' => $activityId), 'linkedColumns' => array('activity_id'), 'isRecurringEntityRecord' => FALSE));
         CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_activity', $linkedEntities);
     }
     return array('activity' => $activity);
 }
 /**
  * Given a list of conditions in params generate the required
  * where clause
  *
  * @return void
  * @access public
  */
 function whereClause()
 {
     $this->_where[0] = array();
     $this->_qill[0] = array();
     $config = CRM_Core_Config::singleton();
     $this->includeContactIds();
     if (!empty($this->_params)) {
         $activity = FALSE;
         foreach (array_keys($this->_params) as $id) {
             if (!CRM_Utils_Array::value(0, $this->_params[$id])) {
                 continue;
             }
             // check for both id and contact_id
             if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
                 if ($this->_params[$id][1] == 'IS NULL' || $this->_params[$id][1] == 'IS NOT NULL') {
                     $this->_where[0][] = "contact_a.id {$this->_params[$id][1]}";
                 } else {
                     $this->_where[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
                 }
             } else {
                 $this->whereClauseSingle($this->_params[$id]);
             }
             if (substr($this->_params[$id][0], 0, 9) == 'activity_') {
                 $activity = TRUE;
             }
         }
         CRM_Core_Component::alterQuery($this, 'where');
     }
     if ($this->_customQuery) {
         // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
         // Hope it wont affect the other part of civicrm.. if it does please remove it.
         if (!empty($this->_customQuery->_where)) {
             $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
         }
         $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
     }
     $clauses = array();
     $andClauses = array();
     $validClauses = 0;
     if (!empty($this->_where)) {
         foreach ($this->_where as $grouping => $values) {
             if ($grouping > 0 && !empty($values)) {
                 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
                 $validClauses++;
             }
         }
         if (!empty($this->_where[0])) {
             $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
         }
         if (!empty($clauses)) {
             $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
         }
         if ($validClauses > 1) {
             $this->_useDistinct = TRUE;
         }
     }
     return implode(' AND ', $andClauses);
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $tx = new CRM_Core_Transaction();
     // check if dedupe button, if so return.
     $buttonName = $this->controller->getButtonName();
     if (isset($this->_dedupeButtonName) && $buttonName == $this->_dedupeButtonName) {
         return;
     }
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = NULL;
         $caseDelete = CRM_Case_BAO_Case::deleteCase($this->_caseId, TRUE);
         if ($caseDelete) {
             $statusMsg = ts('The selected case has been moved to the Trash. You can view and / or restore deleted cases by checking the "Deleted Cases" option under Find Cases.<br />');
         }
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = NULL;
         $caseRestore = CRM_Case_BAO_Case::restoreCase($this->_caseId);
         if ($caseRestore) {
             $statusMsg = ts('The selected case has been restored.<br />');
         }
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $params['now'] = date("Ymd");
     // 1. call begin post process
     if ($this->_activityTypeFile) {
         eval("CRM_Case_Form_Activity_{$this->_activityTypeFile}" . "::beginPostProcess( \$this, \$params );");
     }
     if (CRM_Utils_Array::value('hidden_custom', $params) && !isset($params['custom'])) {
         $customFields = array();
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, NULL, 'Case');
     }
     // 2. create/edit case
     if (CRM_Utils_Array::value('case_type_id', $params)) {
         $caseType = CRM_Case_PseudoConstant::caseType('name');
         $params['case_type'] = $caseType[$params['case_type_id']];
         $params['subject'] = $params['activity_subject'];
         $params['case_type_id'] = CRM_Core_DAO::VALUE_SEPARATOR . $params['case_type_id'] . CRM_Core_DAO::VALUE_SEPARATOR;
     }
     $caseObj = CRM_Case_BAO_Case::create($params);
     $params['case_id'] = $caseObj->id;
     // unset any ids, custom data
     unset($params['id'], $params['custom']);
     // add tags if exists
     $tagParams = array();
     if (!empty($params['tag'])) {
         $tagParams = array();
         foreach ($params['tag'] as $tag) {
             $tagParams[$tag] = 1;
         }
     }
     CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_case', $caseObj->id);
     //save free tags
     if (isset($params['case_taglist']) && !empty($params['case_taglist'])) {
         CRM_Core_Form_Tag::postProcess($params['case_taglist'], $caseObj->id, 'civicrm_case', $this);
     }
     // user context
     $url = CRM_Utils_System::url('civicrm/contact/view/case', "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseObj->id}");
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext($url);
     // 3. format activity custom data
     if (CRM_Utils_Array::value('hidden_custom', $params)) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_activityId, 'Activity');
     }
     // 4. call end post process
     if ($this->_activityTypeFile) {
         eval("CRM_Case_Form_Activity_{$this->_activityTypeFile}" . "::endPostProcess( \$this, \$params );");
     }
     // 5. auto populate activites
     // 6. set status
     CRM_Core_Session::setStatus("{$params['statusMsg']}");
 }
 /**
  * Process the PDf and email with activity and attachment.
  * on click of Print Invoices
  *
  * @param array $contribIDs
  *   Contribution Id.
  * @param array $params
  *   Associated array of submitted values.
  * @param array $contactIds
  *   Contact Id.
  * @param CRM_Core_Form $form
  *   Form object.
  */
 public static function printPDF($contribIDs, &$params, $contactIds, &$form)
 {
     // get all the details needed to generate a invoice
     $messageInvoice = array();
     $invoiceTemplate = CRM_Core_Smarty::singleton();
     $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
     // gives the status id when contribution status is 'Refunded'
     $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
     // getting data from admin page
     $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     foreach ($invoiceElements['details'] as $contribID => $detail) {
         $input = $ids = $objects = array();
         if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
             continue;
         }
         $input['component'] = $detail['component'];
         $ids['contact'] = $detail['contact'];
         $ids['contribution'] = $contribID;
         $ids['contributionRecur'] = NULL;
         $ids['contributionPage'] = NULL;
         $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
         $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
         $ids['event'] = CRM_Utils_Array::value('event', $detail);
         if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
             CRM_Core_Error::fatal();
         }
         $contribution =& $objects['contribution'];
         $input['amount'] = $contribution->total_amount;
         $input['invoice_id'] = $contribution->invoice_id;
         $input['receive_date'] = $contribution->receive_date;
         $input['contribution_status_id'] = $contribution->contribution_status_id;
         $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
         $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
         $addressParams = array('contact_id' => $contribution->contact_id);
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
         // to get billing address if present
         $billingAddress = array();
         foreach ($addressDetails as $key => $address) {
             if (isset($address['is_billing']) && $address['is_billing'] == 1 && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
                 break;
             } elseif ($address['is_billing'] == 0 && $address['is_primary'] == 1 || isset($address['is_billing']) && $address['is_billing'] == 1 && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
             }
         }
         if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
             $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
         } else {
             $stateProvinceAbbreviation = '';
         }
         if ($contribution->contribution_status_id == $refundedStatusId) {
             $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
         }
         $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
         //to obtain due date for PDF invoice
         $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
         $invoiceDate = date("F j, Y");
         $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
         if ($input['component'] == 'contribute') {
             $eid = $contribID;
             $etable = 'contribution';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
         } else {
             $eid = $contribution->_relatedObjects['participant']->id;
             $etable = 'participant';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable);
         }
         //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
         $amountDue = $input['amount'] - $input['amount'];
         // retreiving the subtotal and sum of same tax_rate
         $dataArray = array();
         $subTotal = 0;
         foreach ($lineItem as $entity_id => $taxRate) {
             if (isset($dataArray[(string) $taxRate['tax_rate']])) {
                 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
             } else {
                 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
             }
             $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
         }
         // to email the invoice
         $mailDetails = array();
         $values = array();
         if ($contribution->_component == 'event') {
             $daoName = 'CRM_Event_DAO_Event';
             $pageId = $contribution->_relatedObjects['event']->id;
             $mailElements = array('title', 'confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
         } elseif ($contribution->_component == 'contribute') {
             $daoName = 'CRM_Contribute_DAO_ContributionPage';
             $pageId = $contribution->contribution_page_id;
             $mailElements = array('title', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
         }
         $source = $contribution->source;
         $config = CRM_Core_Config::singleton();
         if (!isset($params['forPage'])) {
             $config->doNotAttachPDFReceipt = 1;
         }
         // get organization address
         $domain = CRM_Core_BAO_Domain::getDomain();
         $locParams = array('contact_id' => $domain->id);
         $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
         if (isset($locationDefaults['address'][1]['state_province_id'])) {
             $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
         } else {
             $stateProvinceAbbreviationDomain = '';
         }
         if (isset($locationDefaults['address'][1]['country_id'])) {
             $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
         } else {
             $countryDomain = '';
         }
         // parameters to be assign for template
         $tplParams = array('title' => $title, 'component' => $input['component'], 'id' => $contribution->id, 'source' => $source, 'invoice_id' => $invoiceId, 'resourceBase' => $config->userFrameworkResourceURL, 'defaultCurrency' => $config->defaultCurrency, 'amount' => $contribution->total_amount, 'amountDue' => $amountDue, 'invoice_date' => $invoiceDate, 'dueDate' => $dueDate, 'notes' => CRM_Utils_Array::value('notes', $prefixValue), 'display_name' => $contribution->_relatedObjects['contact']->display_name, 'lineItem' => $lineItem, 'dataArray' => $dataArray, 'refundedStatusId' => $refundedStatusId, 'contribution_status_id' => $contribution->contribution_status_id, 'subTotal' => $subTotal, 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'stateProvinceAbbreviation' => $stateProvinceAbbreviation, 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'is_pay_later' => $contribution->is_pay_later, 'organization_name' => $contribution->_relatedObjects['contact']->organization_name, 'domain_organization' => $domain->name, 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_state' => $stateProvinceAbbreviationDomain, 'domain_country' => $countryDomain, 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])), 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])));
         if (isset($creditNoteId)) {
             $tplParams['creditnote_id'] = $creditNoteId;
         }
         $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_invoice_receipt', 'contactId' => $contribution->contact_id, 'tplParams' => $tplParams, 'PDFFilename' => 'Invoice.pdf');
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         //CRM-16319 - we dont store in userID in case the user is doing multiple
         //transactions etc
         if (empty($contactID)) {
             $contactID = $session->get('transaction.userID');
         }
         $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
         $emails = array();
         $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
         foreach ($contactEmails as $emailId => $item) {
             $email = $item['email'];
             if ($email) {
                 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
             }
         }
         $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
         // from email address
         if (isset($params['from_email_address'])) {
             $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
         }
         // condition to check for download PDF Invoice or email Invoice
         if ($invoiceElements['createPdf']) {
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if (isset($params['forPage'])) {
                 return $html;
             } else {
                 $mail = array('subject' => $subject, 'body' => $message, 'html' => $html);
                 if ($mail['html']) {
                     $messageInvoice[] = $mail['html'];
                 } else {
                     $messageInvoice[] = nl2br($mail['body']);
                 }
             }
         } elseif ($contribution->_component == 'contribute') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         } elseif ($contribution->_component == 'event') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         }
         CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
         if ($contribution->contribution_status_id == $refundedStatusId) {
             CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
         }
         $invoiceTemplate->clearTemplateVars();
     }
     if ($invoiceElements['createPdf']) {
         if (isset($params['forPage'])) {
             return $html;
         } else {
             CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array('margin_top' => 10, 'margin_left' => 65, 'metric' => 'px'));
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contactIds, $fileName, $params);
             CRM_Utils_System::civiExit();
         }
     } else {
         if ($invoiceElements['suppressedEmails']) {
             $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails']));
             $msgTitle = ts('Email Error');
             $msgType = 'error';
         } else {
             $status = ts('Your mail has been sent.');
             $msgTitle = ts('Sent');
             $msgType = 'success';
         }
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     }
 }
示例#9
0
 /**
  * @param bool $printReport
  *
  * @return array
  */
 public function getActivities($printReport = FALSE)
 {
     $retval = array();
     /*
      * Loop through the activities in the file and add them to the appropriate region array.
      */
     $doc = new DOMDocument();
     if ($doc->loadXML($this->xmlString)) {
         $regionList = $this->auditConfig->getRegions();
         $ifBlanks = $this->auditConfig->getIfBlanks();
         $includeAll = $doc->getElementsByTagName("IncludeActivities")->item(0)->nodeValue;
         $includeAll = $includeAll == 'All';
         $activityindex = 0;
         $activityList = $doc->getElementsByTagName("Activity");
         $caseActivities = array();
         $activityStatusType = array();
         foreach ($activityList as $activity) {
             $retval[$activityindex] = array();
             $ifBlankReplacements = array();
             $completed = FALSE;
             $sortValues = array('1970-01-01');
             $category = '';
             $fieldindex = 1;
             $fields = $activity->getElementsByTagName("Field");
             foreach ($fields as $field) {
                 $datatype_elements = $field->getElementsByTagName("Type");
                 $datatype = $datatype_elements->item(0)->nodeValue;
                 $label_elements = $field->getElementsByTagName("Label");
                 $label = $label_elements->item(0)->nodeValue;
                 $value_elements = $field->getElementsByTagName("Value");
                 $value = $value_elements->item(0)->nodeValue;
                 $category_elements = $field->getElementsByTagName("Category");
                 if (!empty($category_elements->length)) {
                     $category = $category_elements->item(0)->nodeValue;
                 }
                 // Based on the config file, does this field's label and value indicate a completed activity?
                 if ($label == $this->auditConfig->getCompletionLabel() && $value == $this->auditConfig->getCompletionValue()) {
                     $completed = TRUE;
                 }
                 // Based on the config file, does this field's label match the one to use for sorting activities?
                 if (in_array($label, $this->auditConfig->getSortByLabels())) {
                     $sortValues[$label] = $value;
                 }
                 foreach ($regionList as $region) {
                     // Based on the config file, is this field a potential replacement for another?
                     if (!empty($ifBlanks[$region])) {
                         if (in_array($label, $ifBlanks[$region])) {
                             $ifBlankReplacements[$label] = $value;
                         }
                     }
                     if ($this->auditConfig->includeInRegion($label, $region)) {
                         $retval[$activityindex][$region][$fieldindex] = array();
                         $retval[$activityindex][$region][$fieldindex]['label'] = $label;
                         $retval[$activityindex][$region][$fieldindex]['datatype'] = $datatype;
                         $retval[$activityindex][$region][$fieldindex]['value'] = $value;
                         if ($datatype == 'Date') {
                             $retval[$activityindex][$region][$fieldindex]['includeTime'] = $this->auditConfig->includeTime($label, $region);
                         }
                         //CRM-4570
                         if ($printReport) {
                             if (!in_array($label, array('Activity Type', 'Status'))) {
                                 $caseActivities[$activityindex][$fieldindex] = array();
                                 $caseActivities[$activityindex][$fieldindex]['label'] = $label;
                                 $caseActivities[$activityindex][$fieldindex]['datatype'] = $datatype;
                                 $caseActivities[$activityindex][$fieldindex]['value'] = $value;
                             } else {
                                 $activityStatusType[$activityindex][$fieldindex] = array();
                                 $activityStatusType[$activityindex][$fieldindex]['label'] = $label;
                                 $activityStatusType[$activityindex][$fieldindex]['datatype'] = $datatype;
                                 $activityStatusType[$activityindex][$fieldindex]['value'] = $value;
                             }
                         }
                     }
                 }
                 $fieldindex++;
             }
             if ($printReport) {
                 $caseActivities[$activityindex] = CRM_Utils_Array::crmArrayMerge($activityStatusType[$activityindex], $caseActivities[$activityindex]);
                 $caseActivities[$activityindex]['sortValues'] = $sortValues;
             }
             if ($includeAll || !$completed) {
                 $retval[$activityindex]['completed'] = $completed;
                 $retval[$activityindex]['category'] = $category;
                 $retval[$activityindex]['sortValues'] = $sortValues;
                 // Now sort the fields based on the order in the config file.
                 foreach ($regionList as $region) {
                     $this->auditConfig->sort($retval[$activityindex][$region], $region);
                 }
                 $retval[$activityindex]['editurl'] = $activity->getElementsByTagName("EditURL")->item(0)->nodeValue;
                 // If there are any fields with ifBlank specified, replace their values.
                 // We need to do this as a second pass because if we do it while looping through fields we might not have come across the field we need yet.
                 foreach ($regionList as $region) {
                     foreach ($retval[$activityindex][$region] as &$v) {
                         $vlabel = $v['label'];
                         if (trim($v['value']) == '' && !empty($ifBlanks[$region][$vlabel])) {
                             if (!empty($ifBlankReplacements[$ifBlanks[$region][$vlabel]])) {
                                 $v['value'] = $ifBlankReplacements[$ifBlanks[$region][$vlabel]];
                             }
                         }
                     }
                     unset($v);
                 }
                 $activityindex++;
             } else {
                 /* This is a little bit inefficient, but the alternative is to do two passes
                    because we don't know until we've examined all the field values whether the activity
                    is completed, since the field that determines it and its value is configurable,
                    so either way isn't ideal. */
                 unset($retval[$activityindex]);
                 unset($caseActivities[$activityindex]);
             }
         }
         if ($printReport) {
             @uasort($caseActivities, array($this, "compareActivities"));
         } else {
             @uasort($retval, array($this, "compareActivities"));
         }
     }
     if ($printReport) {
         return $caseActivities;
     } else {
         return $retval;
     }
 }
示例#10
0
 /**
  * Process membership records.
  *
  * @param array $params
  *   Associated array of submitted values.
  *
  *
  * @return bool
  */
 private function processMembership(&$params)
 {
     $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate');
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     // get the price set associated with offline membership
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
     $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             foreach ($dateTypes as $dateField => $dateVariable) {
                 ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]);
                 $fDate[$dateField] = CRM_Utils_Array::value($dateField, $value);
             }
             $calcDates = array();
             $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate);
             foreach ($calcDates as $memType => $calcDate) {
                 foreach ($dates as $d) {
                     //first give priority to form values then calDates.
                     $date = CRM_Utils_Array::value($d, $value);
                     if (!$date) {
                         $date = CRM_Utils_Array::value($d, $calcDate);
                     }
                     $value[$d] = CRM_Utils_Date::processDate($date);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             if (!empty($value['membership_status'])) {
                 $value['status_id'] = $value['membership_status'];
                 unset($value['membership_status']);
             }
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $key, 'Membership', $membershipTypeId);
             if (!empty($value['financial_type'])) {
                 $value['financial_type_id'] = $value['financial_type'];
             }
             if (!empty($value['payment_instrument'])) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             // handle soft credit
             if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
                 //CRM-15350: if soft-credit-type profile field is disabled or removed then
                 //we choose Gift as default value as per Gift Membership rule
                 if (!empty($params['soft_credit_type'][$key])) {
                     $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
                 } else {
                     $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'Gift', 'name');
                 }
             }
             if (!empty($value['receive_date'])) {
                 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             unset($value['financial_type']);
             unset($value['payment_instrument']);
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // make entry in line item for contribution
             $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]);
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (!empty($editedResults)) {
                 unset($this->_priceSet['fields']);
                 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
                 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
                 $fid = $editedResults['id'];
                 $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']);
                 $editedResults = array();
                 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
                 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
                 if (!empty($value['total_amount'])) {
                     $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
                 }
                 $fieldID = key($this->_priceSet['fields']);
                 $value['price_' . $fieldID] = $editedResults['id'];
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
                 //CRM-11529 for backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                     foreach ($lineItem[$priceSetId] as &$values) {
                         $values['financial_type_id'] = $value['financial_type_id'];
                     }
                 }
                 $value['lineItems'] = $lineItem;
                 $value['processPriceSet'] = TRUE;
             }
             // end of contribution related section
             unset($value['membership_type']);
             unset($value['membership_start_date']);
             unset($value['membership_end_date']);
             $value['is_renew'] = FALSE;
             if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
                 // The following parameter setting may be obsolete.
                 $this->_params = $params;
                 $value['is_renew'] = TRUE;
                 $isPayLater = CRM_Utils_Array::value('is_pay_later', $params);
                 $campaignId = NULL;
                 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
                     $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
                     if (!array_key_exists('campaign_id', $this->_params)) {
                         $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
                     }
                 }
                 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
                     //CRM-18000 - ignore $dateType if its not explicitly passed
                     if (!empty($fDate[$dateType]) || !empty($fDate['membership_' . $dateType])) {
                         $formDates[$dateType] = CRM_Utils_Array::value($dateType, $value);
                     }
                 }
                 $membershipSource = CRM_Utils_Array::value('source', $value);
                 list($membership) = CRM_Member_BAO_Membership::renewMembership($value['contact_id'], $value['membership_type_id'], FALSE, NULL, NULL, $value['custom'], 1, NULL, FALSE, NULL, $membershipSource, $isPayLater, $campaignId, $formDates);
                 // make contribution entry
                 $contrbutionParams = array_merge($value, array('membership_id' => $membership->id));
                 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
                 // This form should set the correct params & not call this fn directly.
                 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
             } else {
                 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'), 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($membership->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['membership_id'] = $membership->id;
                 $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
                 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
             }
         }
     }
     return TRUE;
 }
 /**
  * Process the renewal form.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $ids = array();
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $this->storeContactFields($formValues);
     // use values from screen
     if ($formValues['membership_type_id'][1] != 0) {
         $defaults['receipt_text_renewal'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'receipt_text_renewal');
     }
     $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
     $this->convertDateFieldsToMySQL($formValues);
     $this->assign('receive_date', $formValues['receive_date']);
     if (!empty($this->_params['send_receipt'])) {
         $formValues['receipt_date'] = $now;
         $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($formValues['receipt_date']));
     } else {
         $formValues['receipt_date'] = NULL;
     }
     if ($this->_mode) {
         $formValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params, CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee'));
         if (empty($formValues['financial_type_id'])) {
             $formValues['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_contributorEmail;
         $formValues['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
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["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}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         //here we are setting up the billing contact - if different from the member they are already created
         // but they will get billing details assigned
         CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         // 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['description'] = ts('Office Credit Card Membership Renewal Contribution');
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $formValues['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $paymentParams['invoiceID'] = $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 passed params
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         $paymentParams['contactID'] = $this->_contributorContactID;
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
         if (!empty($paymentParams['auto_renew'])) {
             $contributionRecurParams = $this->processRecurringContribution($paymentParams);
             $this->_params['contributionRecurID'] = $contributionRecurParams['contributionRecurID'];
             $paymentParams = array_merge($paymentParams, $contributionRecurParams);
         }
         $result = $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $formValues['contribution_status_id'] = 1;
         $formValues['invoice_id'] = $this->_params['invoiceID'];
         $formValues['trxn_id'] = $result['trxn_id'];
         $formValues['payment_instrument_id'] = 1;
         $formValues['is_test'] = $this->_mode == 'live' ? 0 : 1;
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
     }
     $renewalDate = NULL;
     if ($formValues['renewal_date']) {
         $this->set('renewalDate', CRM_Utils_Date::processDate($formValues['renewal_date']));
     }
     $this->_membershipId = $this->_id;
     // membership type custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $formValues['membership_type_id'][1]);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
     $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     // check for test membership.
     $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
     // chk for renewal for multiple terms CRM-8750
     $numRenewTerms = 1;
     if (is_numeric(CRM_Utils_Array::value('num_terms', $formValues))) {
         $numRenewTerms = $formValues['num_terms'];
     }
     //if contribution status is pending then set pay later
     if ($formValues['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
         $this->_params['is_pay_later'] = 1;
     }
     $renewMembership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($this->_contactID, $formValues['membership_type_id'][1], $isTestMembership, $this, NULL, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId);
     $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
     if (!empty($formValues['record_contribution']) || $this->_mode) {
         // set the source
         $formValues['contribution_source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
         //create line items
         $lineItem = array();
         $priceSetId = NULL;
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         //CRM-11529 for quick config backoffice transactions
         //when financial_type_id is passed in form, update the
         //line items with the financial type selected in form
         if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues)) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
         $formValues['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         if (!empty($lineItem)) {
             $formValues['lineItems'] = $lineItem;
             $formValues['processPriceSet'] = TRUE;
         }
         //assign contribution contact id to the field expected by recordMembershipContribution
         if ($this->_contributorContactID != $this->_contactID) {
             $formValues['contribution_contact_id'] = $this->_contributorContactID;
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $formValues['soft_credit'] = array('soft_credit_type_id' => $this->_params['soft_credit_type_id'], 'contact_id' => $this->_contactID);
             }
         }
         $formValues['contact_id'] = $this->_contactID;
         //recordMembershipContribution receives params as a reference & adds one variable. This is
         // not a great pattern & ideally it would not receive as a reference. We assign our params as a
         // temporary variable to avoid e-notice & to make it clear to future refactorer that
         // this function is NOT reliant on that var being set
         $temporaryParams = array_merge($formValues, array('membership_id' => $renewMembership->id));
         CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
     }
     $receiptSend = FALSE;
     if (!empty($formValues['send_receipt'])) {
         $receiptSend = TRUE;
         $receiptFrom = $formValues['from_email_address'];
         if (!empty($formValues['payment_instrument_id'])) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         }
         //get the group Tree
         $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
         // retrieve custom data
         $customFields = $customValues = $fo = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
         // check whether its a test drive
         if ($this->_mode == 'test') {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
         $this->assign_by_ref('formValues', $formValues);
         if (!empty($formValues['contribution_id'])) {
             $this->assign('contributionID', $formValues['contribution_id']);
         }
         $this->assign('membershipID', $this->_id);
         $this->assign('contactID', $this->_contactID);
         $this->assign('module', 'Membership');
         $this->assign('receiptType', 'membership renewal');
         $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
         $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
         $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id));
         $this->assign('customValues', $customValues);
         if ($this->_mode) {
             if (!empty($this->_params['billing_first_name'])) {
                 $name = $this->_params['billing_first_name'];
             }
             if (!empty($this->_params['billing_middle_name'])) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (!empty($this->_params['billing_last_name'])) {
                 $name .= " {$this->_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($this->_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($this->_params['credit_card_number']));
             $this->assign('credit_card_type', $this->_params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
             if ($this->_mode == 'test') {
                 $this->assign('action', '1024');
             }
         }
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $this->_receiptContactId, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => $this->_mode == 'test'));
     }
     $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_memberDisplayName));
     if ($endDate) {
         $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => CRM_Utils_Date::customFormat(substr($endDate, 0, 8))));
     }
     if ($receiptSend && $mailSend) {
         $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
 }
 /**
  * Given a list of conditions in params generate the required.
  * where clause
  *
  * @return string
  */
 public function whereClause()
 {
     $this->_where[0] = array();
     $this->_qill[0] = array();
     $this->includeRelationshipIds();
     if (!empty($this->_params)) {
         foreach (array_keys($this->_params) as $id) {
             if (empty($this->_params[$id][0])) {
                 continue;
             }
             // check for both id and contact_id
             if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'relationship_id') {
                 $this->_where[0][] = self::buildClause("relationship.id", $this->_params[$id][1], $this->_params[$id][2]);
             } else {
                 $this->whereClauseSingle($this->_params[$id]);
             }
         }
     }
     if ($this->_customQuery) {
         if (!empty($this->_customQuery->_where)) {
             $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
         }
         $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
     }
     $clauses = array();
     $andClauses = array();
     $validClauses = 0;
     if (!empty($this->_where)) {
         foreach ($this->_where as $grouping => $values) {
             if ($grouping > 0 && !empty($values)) {
                 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
                 $validClauses++;
             }
         }
         if (!empty($this->_where[0])) {
             $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
         }
         if (!empty($clauses)) {
             $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
         }
         if ($validClauses > 1) {
             $this->_useDistinct = TRUE;
         }
     }
     return implode(' AND ', $andClauses);
 }
示例#13
0
 /**
  * Given a list of conditions in params generate the required where clause.
  *
  * @param string $apiEntity
  *
  * @return string
  */
 public function whereClause($apiEntity = NULL)
 {
     $this->_where[0] = array();
     $this->_qill[0] = array();
     $this->includeContactIds();
     if (!empty($this->_params)) {
         foreach (array_keys($this->_params) as $id) {
             if (empty($this->_params[$id][0])) {
                 continue;
             }
             // check for both id and contact_id
             if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
                 $this->_where[0][] = self::buildClause("contact_a.id", $this->_params[$id][1], $this->_params[$id][2]);
             } else {
                 $this->whereClauseSingle($this->_params[$id], $apiEntity);
             }
         }
         CRM_Core_Component::alterQuery($this, 'where');
         CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where');
     }
     if ($this->_customQuery) {
         // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
         // Hope it wont affect the other part of civicrm.. if it does please remove it.
         if (!empty($this->_customQuery->_where)) {
             $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
         }
         $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
     }
     $clauses = array();
     $andClauses = array();
     $validClauses = 0;
     if (!empty($this->_where)) {
         foreach ($this->_where as $grouping => $values) {
             if ($grouping > 0 && !empty($values)) {
                 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
                 $validClauses++;
             }
         }
         if (!empty($this->_where[0])) {
             $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
         }
         if (!empty($clauses)) {
             $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
         }
         if ($validClauses > 1) {
             $this->_useDistinct = TRUE;
         }
     }
     return implode(' AND ', $andClauses);
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active');
     foreach ($checkBoxes as $key) {
         if (!isset($params[$key])) {
             $params[$key] = 0;
         }
     }
     $session = CRM_Core_Session::singleton();
     $contactID = isset($this->_contactID) ? $this->_contactID : $session->get('userID');
     if (!$contactID) {
         $contactID = $this->get('contactID');
     }
     $params['title'] = $params['pcp_title'];
     $params['intro_text'] = $params['pcp_intro_text'];
     $params['contact_id'] = $contactID;
     $params['page_id'] = $this->get('component_page_id') ? $this->get('component_page_id') : $this->_contriPageId;
     $params['page_type'] = $this->_component;
     // since we are allowing html input from the user
     // we also need to purify it, so lets clean it up
     $htmlFields = array('intro_text', 'page_text', 'title');
     foreach ($htmlFields as $field) {
         if (!empty($params[$field])) {
             $params[$field] = CRM_Utils_String::purifyHTML($params[$field]);
         }
     }
     $entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($params['page_type']);
     $pcpBlock = new CRM_PCP_DAO_PCPBlock();
     $pcpBlock->entity_table = $entity_table;
     $pcpBlock->entity_id = $params['page_id'];
     $pcpBlock->find(TRUE);
     $params['pcp_block_id'] = $pcpBlock->id;
     $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
     $approval_needed = $pcpBlock->is_approval_needed;
     $approvalMessage = NULL;
     if ($this->get('action') & CRM_Core_Action::ADD) {
         $params['status_id'] = $approval_needed ? 1 : 2;
         $approvalMessage = $approval_needed ? ts('but requires administrator review before you can begin promoting your campaign. You will receive an email confirmation shortly which includes a link to return to this page.') : ts('and is ready to use.');
     }
     $params['id'] = $this->_pageId;
     $pcp = CRM_PCP_BAO_PCP::add($params, FALSE);
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_pcp', $pcp->id);
     //MV: update Custom Values
     if (!empty($params['hidden_custom']) && CRM_Core_Permission::check('administer CiviCRM')) {
         $customFields = CRM_Core_BAO_CustomField::getFields('PCP');
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('PCP'));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $pcpBlock->entity_id, 'PCP');
         //API to Update Custom Values;
         $customApiParams = array('version' => 3, 'entity_id' => $params['id']);
         foreach ($params['custom'] as $elementId => $elementValues) {
             $elementValue = array_values($elementValues);
             $customApiParams['custom_' . $elementId] = $elementValue[0]['value'];
             if ($elementValue['id']) {
                 $customApiParams['id'] = $elementValue[0]['id'];
             }
         }
         $temp = civicrm_api3('CustomValue', 'create', $customApiParams);
     }
     //END
     $pageStatus = isset($this->_pageId) ? ts('updated') : ts('created');
     $statusId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp->id, 'status_id');
     //send notification of PCP create/update.
     $pcpParams = array('entity_table' => $entity_table, 'entity_id' => $pcp->page_id);
     $notifyParams = array();
     $notifyStatus = "";
     CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, array('notify_email'));
     if ($emails = $pcpBlock->notify_email) {
         $this->assign('pcpTitle', $pcp->title);
         if ($this->_pageId) {
             $this->assign('mode', 'Update');
         } else {
             $this->assign('mode', 'Add');
         }
         $pcpStatus = CRM_Core_OptionGroup::getLabel('pcp_status', $statusId);
         $this->assign('pcpStatus', $pcpStatus);
         $this->assign('pcpId', $pcp->id);
         $supporterUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$pcp->contact_id}", TRUE, NULL, FALSE, FALSE);
         $this->assign('supporterUrl', $supporterUrl);
         $supporterName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $pcp->contact_id, 'display_name');
         $this->assign('supporterName', $supporterName);
         if ($this->_component == 'contribute') {
             $pageUrl = CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE);
             $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $pcpBlock->entity_id, 'title');
         } elseif ($this->_component == 'event') {
             $pageUrl = CRM_Utils_System::url('civicrm/event', "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE);
             $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $pcpBlock->entity_id, 'title');
         }
         $this->assign('contribPageUrl', $pageUrl);
         $this->assign('contribPageTitle', $contribPageTitle);
         $managePCPUrl = CRM_Utils_System::url('civicrm/admin/pcp', "reset=1", TRUE, NULL, FALSE, FALSE);
         $this->assign('managePCPUrl', $managePCPUrl);
         //get the default domain email address.
         list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
         if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') {
             $fixUrl = CRM_Utils_System::url('civicrm/admin/domain', 'action=update&reset=1');
             CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl)));
         }
         //if more than one email present for PCP notification ,
         //first email take it as To and other as CC and First email
         //address should be sent in users email receipt for
         //support purpose.
         $emailArray = explode(',', $emails);
         $to = $emailArray[0];
         unset($emailArray[0]);
         $cc = implode(',', $emailArray);
         list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_notify', 'contactId' => $contactID, 'from' => "{$domainEmailName} <{$domainEmailAddress}>", 'toEmail' => $to, 'cc' => $cc));
         if ($sent) {
             $notifyStatus = ts('A notification email has been sent to the site administrator.');
         }
     }
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_pcp', $pcp->id);
     // send email notification to supporter, if initial setup / add mode.
     if (!$this->_pageId) {
         CRM_PCP_BAO_PCP::sendStatusUpdate($pcp->id, $statusId, TRUE, $this->_component);
         if ($approvalMessage && CRM_Utils_Array::value('status_id', $params) == 1) {
             $notifyStatus .= ts(' You will receive a second email as soon as the review process is complete.');
         }
     }
     //check if pcp created by anonymous user
     $anonymousPCP = 0;
     if (!$session->get('userID')) {
         $anonymousPCP = 1;
     }
     CRM_Core_Session::setStatus(ts("Your Personal Campaign Page has been %1 %2 %3", array(1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus)), '', 'info');
     if (!$this->_pageId) {
         $session->pushUserContext(CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcp->id}&ap={$anonymousPCP}"));
     } elseif ($this->_context == 'dashboard') {
         $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/pcp', 'reset=1'));
     }
 }
示例#15
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Grant_BAO_Grant::del($this->_id);
         return;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $ids['grant_id'] = $this->_id;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if (empty($params['grant_report_received'])) {
         $params['grant_report_received'] = "null";
     }
     // set the contact, when contact is selected
     if ($this->_context == 'standalone') {
         $this->_contactID = $params['contact_id'];
     }
     $params['contact_id'] = $this->_contactID;
     $ids['note'] = array();
     if ($this->_noteId) {
         $ids['note']['id'] = $this->_noteId;
     }
     // build custom data getFields array
     $customFieldsGrantType = CRM_Core_BAO_CustomField::getFields('Grant', FALSE, FALSE, CRM_Utils_Array::value('grant_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsGrantType, CRM_Core_BAO_CustomField::getFields('Grant', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Grant');
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_grant', $this->_id);
     $grant = CRM_Grant_BAO_Grant::create($params, $ids);
     $buttonName = $this->controller->getButtonName();
     $session = CRM_Core_Session::singleton();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/grant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=grant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/grant', "reset=1&action=add&context=grant&cid={$this->_contactID}"));
     }
 }
示例#16
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     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));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $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;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $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);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl 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'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $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['payment_action'] = 'Sale';
         $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 (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($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 (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $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']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $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;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 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) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $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 (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 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();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $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();
         $event['participant_role'] = $role[$params['role_id']];
         $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');
             require_once 'CRM/Core/BAO/Location.php';
             $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) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $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];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $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']);
             $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 (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $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) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $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;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $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.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // 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;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($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 (CRM_Utils_Array::value('send_receipt', $params) && 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 - 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');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
示例#17
0
 function printCaseReport()
 {
     $caseID = CRM_Utils_Request::retrieve('caseID', 'Positive', CRM_Core_DAO::$_nullObject);
     $clientID = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject);
     $activitySetName = CRM_Utils_Request::retrieve('asn', 'String', CRM_Core_DAO::$_nullObject);
     $isRedact = CRM_Utils_Request::retrieve('redact', 'Boolean', CRM_Core_DAO::$_nullObject);
     $includeActivities = CRM_Utils_Request::retrieve('all', 'Positive', CRM_Core_DAO::$_nullObject);
     $params = $otherRelationships = $globalGroupInfo = array();
     $report = new CRM_Case_XMLProcessor_Report($isRedact);
     if ($includeActivities) {
         $params['include_activities'] = 1;
     }
     if ($isRedact) {
         $params['is_redact'] = 1;
         $report->_redactionStringRules = array();
     }
     $template = CRM_Core_Smarty::singleton();
     //get case related relationships (Case Role)
     $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($clientID, $caseID);
     $caseType = CRM_Case_BAO_Case::getCaseType($caseID, 'name');
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $caseRoles = $xmlProcessor->get($caseType, 'CaseRoles');
     foreach ($caseRelationships as $key => &$value) {
         if (!empty($caseRoles[$value['relation_type']])) {
             unset($caseRoles[$value['relation_type']]);
         }
         if ($isRedact) {
             if (!array_key_exists($value['name'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($value['name'] => 'name_' . rand(10000, 100000)));
             }
             $value['name'] = self::redact($value['name'], TRUE, $report->_redactionStringRules);
             if (!empty($value['email']) && !array_key_exists($value['email'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($value['email'] => 'email_' . rand(10000, 100000)));
             }
             $value['email'] = self::redact($value['email'], TRUE, $report->_redactionStringRules);
             if (!empty($value['phone']) && !array_key_exists($value['phone'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($value['phone'] => 'phone_' . rand(10000, 100000)));
             }
             $value['phone'] = self::redact($value['phone'], TRUE, $report->_redactionStringRules);
         }
     }
     $caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($caseID);
     if ($isRedact) {
         if (!array_key_exists($caseRoles['client']['sort_name'], $report->_redactionStringRules)) {
             $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($caseRoles['client']['sort_name'] => 'name_' . rand(10000, 100000)));
         }
         if (!array_key_exists($caseRoles['client']['display_name'], $report->_redactionStringRules)) {
             $report->_redactionStringRules[$caseRoles['client']['display_name']] = $report->_redactionStringRules[$caseRoles['client']['sort_name']];
         }
         $caseRoles['client']['sort_name'] = self::redact($caseRoles['client']['sort_name'], TRUE, $report->_redactionStringRules);
         if (!empty($caseRoles['client']['email']) && !array_key_exists($caseRoles['client']['email'], $report->_redactionStringRules)) {
             $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($caseRoles['client']['email'] => 'email_' . rand(10000, 100000)));
         }
         $caseRoles['client']['email'] = self::redact($caseRoles['client']['email'], TRUE, $report->_redactionStringRules);
         if (!empty($caseRoles['client']['phone']) && !array_key_exists($caseRoles['client']['phone'], $report->_redactionStringRules)) {
             $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($caseRoles['client']['phone'] => 'phone_' . rand(10000, 100000)));
         }
         $caseRoles['client']['phone'] = self::redact($caseRoles['client']['phone'], TRUE, $report->_redactionStringRules);
     }
     // Retrieve ALL client relationships
     $relClient = CRM_Contact_BAO_Relationship::getRelationship($clientID, CRM_Contact_BAO_Relationship::CURRENT, 0, 0, 0, NULL, NULL, FALSE);
     foreach ($relClient as $r) {
         if ($isRedact) {
             if (!array_key_exists($r['name'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($r['name'] => 'name_' . rand(10000, 100000)));
             }
             if (!array_key_exists($r['display_name'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules[$r['display_name']] = $report->_redactionStringRules[$r['name']];
             }
             $r['name'] = self::redact($r['name'], TRUE, $report->_redactionStringRules);
             if (!empty($r['phone']) && !array_key_exists($r['phone'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($r['phone'] => 'phone_' . rand(10000, 100000)));
             }
             $r['phone'] = self::redact($r['phone'], TRUE, $report->_redactionStringRules);
             if (!empty($r['email']) && !array_key_exists($r['email'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($r['email'] => 'email_' . rand(10000, 100000)));
             }
             $r['email'] = self::redact($r['email'], TRUE, $report->_redactionStringRules);
         }
         if (!array_key_exists($r['id'], $caseRelationships)) {
             $otherRelationships[] = $r;
         }
     }
     // Now global contact list that appears on all cases.
     $relGlobal = CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo);
     foreach ($relGlobal as &$r) {
         if ($isRedact) {
             if (!array_key_exists($r['sort_name'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($r['sort_name'] => 'name_' . rand(10000, 100000)));
             }
             if (!array_key_exists($r['display_name'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules[$r['display_name']] = $report->_redactionStringRules[$r['sort_name']];
             }
             $r['sort_name'] = self::redact($r['sort_name'], TRUE, $report->_redactionStringRules);
             if (!empty($r['phone']) && !array_key_exists($r['phone'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($r['phone'] => 'phone_' . rand(10000, 100000)));
             }
             $r['phone'] = self::redact($r['phone'], TRUE, $report->_redactionStringRules);
             if (!empty($r['email']) && !array_key_exists($r['email'], $report->_redactionStringRules)) {
                 $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules, array($r['email'] => 'email_' . rand(10000, 100000)));
             }
             $r['email'] = self::redact($r['email'], TRUE, $report->_redactionStringRules);
         }
     }
     $template->assign('caseRelationships', $caseRelationships);
     $template->assign('caseRoles', $caseRoles);
     $template->assign('otherRelationships', $otherRelationships);
     $template->assign('globalRelationships', $relGlobal);
     $template->assign('globalGroupInfo', $globalGroupInfo);
     $contents = self::getCaseReport($clientID, $caseID, $activitySetName, $params, $report);
     $printReport = CRM_Case_Audit_Audit::run($contents, $clientID, $caseID, TRUE);
     echo $printReport;
     CRM_Utils_System::civiExit();
 }
示例#18
0
 /**
  * This function is used to setDefault componet specific profile fields.
  * 
  * @param array  $fields      profile fields.
  * @param int    $componentId componetID
  * @param string $component   component name
  * @param array  $defaults    an array of default values.
  *
  * @return void.
  */
 function setComponentDefaults(&$fields, $componentId, $component, &$defaults)
 {
     if (!$componentId || !in_array($component, array('Contribute', 'Membership', 'Event'))) {
         return;
     }
     $componentBAO = $componentSubType = null;
     switch ($component) {
         case 'Membership':
             $componentBAO = 'CRM_Member_BAO_Membership';
             $componentBAOName = 'Membership';
             $componentSubType = array('membership_type_id');
             break;
         case 'Contribute':
             $componentBAO = 'CRM_Contribute_BAO_Contribution';
             $componentBAOName = 'Contribution';
             $componentSubType = array('contribution_type_id');
             break;
         case 'Event':
             $componentBAO = 'CRM_Event_BAO_Participant';
             $componentBAOName = 'Participant';
             $componentSubType = array('role_id', 'event_id');
             break;
     }
     $values = array();
     $params = array('id' => $componentId);
     //get the component values.
     CRM_Core_DAO::commonRetrieve($componentBAO, $params, $values);
     $formattedGroupTree = array();
     foreach ($fields as $name => $field) {
         $fldName = "field[{$componentId}][{$name}]";
         if ($name == 'participant_register_date') {
             $timefldName = "field[{$componentId}][{$name}_time]";
             list($defaults[$fldName], $defaults[$timefldName]) = CRM_Utils_Date::setDateDefaults($values[$name]);
         } else {
             if (array_key_exists($name, $values)) {
                 $defaults[$fldName] = $values[$name];
             } else {
                 if ($name == 'participant_note') {
                     require_once "CRM/Core/BAO/Note.php";
                     $noteDetails = array();
                     $noteDetails = CRM_Core_BAO_Note::getNote($componentId, 'civicrm_participant');
                     $defaults[$fldName] = array_pop($noteDetails);
                 } else {
                     if (in_array($name, array('contribution_type', 'payment_instrument'))) {
                         $defaults[$fldName] = $values["{$name}_id"];
                     } else {
                         if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($name, true)) {
                             if (empty($formattedGroupTree)) {
                                 //get the groupTree as per subTypes.
                                 $groupTree = array();
                                 require_once 'CRM/Core/BAO/CustomGroup.php';
                                 foreach ($componentSubType as $subType) {
                                     $subTree = CRM_Core_BAO_CustomGroup::getTree($componentBAOName, CRM_Core_DAO::$_nullObject, $componentId, 0, $values[$subType]);
                                     $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $subTree);
                                 }
                                 $formattedGroupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, CRM_Core_DAO::$_nullObject);
                                 CRM_Core_BAO_CustomGroup::setDefaults($formattedGroupTree, $defaults);
                             }
                             //FIX ME: We need to loop defaults, but once we move to custom_1_x convention this code can be simplified.
                             foreach ($defaults as $customKey => $customValue) {
                                 if ($customFieldDetails = CRM_Core_BAO_CustomField::getKeyID($customKey, true)) {
                                     if ($name == 'custom_' . $customFieldDetails[0]) {
                                         //hack to set default for checkbox
                                         //basically this is for weired field name like field[33][custom_19]
                                         //we are converting this field name to array structure and assign value.
                                         $skipValue = false;
                                         foreach ($formattedGroupTree as $tree) {
                                             if ('CheckBox' == CRM_Utils_Array::value('html_type', $tree['fields'][$customFieldDetails[0]])) {
                                                 $skipValue = true;
                                                 $defaults['field'][$componentId][$name] = $customValue;
                                                 break;
                                             } else {
                                                 if (CRM_Utils_Array::value('data_type', $tree['fields'][$customFieldDetails[0]]) == 'Date') {
                                                     $skipValue = true;
                                                     $customValue = $tree['fields'][$customFieldDetails[0]]['element_value'];
                                                     list($defaults['field'][$componentId][$name], $defaults['field'][$componentId][$name . '_time']) = CRM_Utils_Date::setDateDefaults($customValue);
                                                 }
                                             }
                                         }
                                         if (!$skipValue) {
                                             $defaults[$fldName] = $customValue;
                                         }
                                         unset($defaults[$customKey]);
                                         break;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
示例#19
0
 /**
  * Form submission of petition signature.
  */
 public function postProcess()
 {
     $tag_name = Civi::settings()->get('tag_unconfirmed');
     if ($tag_name) {
         // Check if contact 'email confirmed' tag exists, else create one
         // This should be in the petition module initialise code to create a default tag for this
         $tag_params['name'] = $tag_name;
         $tag_params['version'] = 3;
         $tag = civicrm_api('tag', 'get', $tag_params);
         if ($tag['count'] == 0) {
             //create tag
             $tag_params['description'] = $tag_name;
             $tag_params['is_reserved'] = 1;
             $tag_params['used_for'] = 'civicrm_contact';
             $tag = civicrm_api('tag', 'create', $tag_params);
         }
         $this->_tagId = $tag['id'];
     }
     // export the field values to be used for saving the profile form
     $params = $this->controller->exportValues($this->_name);
     $session = CRM_Core_Session::singleton();
     // format params
     $params['last_modified_id'] = $session->get('userID');
     $params['last_modified_date'] = date('YmdHis');
     if ($this->_action & CRM_Core_Action::ADD) {
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     if (isset($this->_surveyId)) {
         $params['sid'] = $this->_surveyId;
     }
     if (isset($this->_contactId)) {
         $params['contactId'] = $this->_contactId;
     }
     // if logged in user, skip dedupe
     if ($this->_loggedIn) {
         $ids[0] = $this->_contactId;
     } else {
         // dupeCheck - check if contact record already exists
         // code modified from api/v2/Contact.php-function civicrm_contact_check_params()
         $params['contact_type'] = $this->_ctype;
         //TODO - current dedupe finds soft deleted contacts - adding param is_deleted not working
         // ignore soft deleted contacts
         //$params['is_deleted'] = 0;
         $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
         $dedupeParams['check_permission'] = '';
         //dupesByParams($params, $ctype, $level = 'Unsupervised', $except = array())
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type']);
     }
     $petition_params['id'] = $this->_surveyId;
     $petition = array();
     CRM_Campaign_BAO_Survey::retrieve($petition_params, $petition);
     switch (count($ids)) {
         case 0:
             //no matching contacts - create a new contact
             // Add a source for this new contact
             $params['source'] = ts('Petition Signature') . ' ' . $this->petition['title'];
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
             } else {
                 $this->_sendEmailMode = self::EMAIL_CONFIRM;
                 // Set status for signature activity to scheduled until email is verified
                 $params['statusId'] = 1;
             }
             break;
         case 1:
             $this->_contactId = $params['contactId'] = $ids[0];
             // check if user has already signed this petition - redirects to Thank You if true
             $this->redirectIfSigned($params);
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
                 break;
             }
             // dedupe matched single contact, check for 'unconfirmed' tag
             if ($tag_name) {
                 $tag = new CRM_Core_DAO_EntityTag();
                 $tag->entity_id = $this->_contactId;
                 $tag->tag_id = $this->_tagId;
                 if (!$tag->find()) {
                     // send thank you email directly, the user is known and validated
                     $this->_sendEmailMode = self::EMAIL_THANK;
                     // Set status for signature activity to completed
                     $params['statusId'] = 2;
                 } else {
                     // send email verification email
                     $this->_sendEmailMode = self::EMAIL_CONFIRM;
                     // Set status for signature activity to scheduled until email is verified
                     $params['statusId'] = 1;
                 }
             }
             break;
         default:
             // more than 1 matching contact
             // for time being, take the first matching contact (not sure that's the best strategy, but better than creating another duplicate)
             $this->_contactId = $params['contactId'] = $ids[0];
             // check if user has already signed this petition - redirects to Thank You if true
             $this->redirectIfSigned($params);
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
                 break;
             }
             if ($tag_name) {
                 $tag = new CRM_Core_DAO_EntityTag();
                 $tag->entity_id = $this->_contactId;
                 $tag->tag_id = $this->_tagId;
                 if (!$tag->find()) {
                     // send thank you email
                     $this->_sendEmailMode = self::EMAIL_THANK;
                     // Set status for signature activity to completed
                     $params['statusId'] = 2;
                 } else {
                     // send email verification email
                     $this->_sendEmailMode = self::EMAIL_CONFIRM;
                     // Set status for signature activity to scheduled until email is verified
                     $params['statusId'] = 1;
                 }
             }
             break;
     }
     $transaction = new CRM_Core_Transaction();
     // CRM-17029 - get the add_to_group_id from the _contactProfileFields array.
     // There's a much more elegant solution with
     // array_values($this->_contactProfileFields)[0] but it's PHP 5.4+ only.
     $slice = array_slice($this->_contactProfileFields, 0, 1);
     $firstField = array_shift($slice);
     $addToGroupID = isset($firstField['add_to_group_id']) ? $firstField['add_to_group_id'] : NULL;
     $this->_contactId = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_contactProfileFields, $this->_contactId, $addToGroupID, $this->_contactProfileId, $this->_ctype, TRUE);
     // get additional custom activity profile field data
     // to save with new signature activity record
     $surveyInfo = $this->bao->getSurveyInfo($this->_surveyId);
     $customActivityFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyInfo['activity_type_id']);
     $customActivityFields = CRM_Utils_Array::crmArrayMerge($customActivityFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, NULL, 'Activity');
     // create the signature activity record
     $params['contactId'] = $this->_contactId;
     $params['activity_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->petition);
     $result = $this->bao->createSignature($params);
     // send thank you or email verification emails
     // if logged in using Facebook connect and email on form matches Fb email,
     // no need for email confirmation, send thank you email
     if ($this->forceEmailConfirmed['flag'] && $this->forceEmailConfirmed['email'] == $params['email-Primary']) {
         $this->_sendEmailMode = self::EMAIL_THANK;
     }
     switch ($this->_sendEmailMode) {
         case self::EMAIL_THANK:
             // mark the signature activity as completed and set confirmed cookie
             $this->bao->confirmSignature($result->id, $this->_contactId, $this->_surveyId);
             break;
         case self::EMAIL_CONFIRM:
             // set 'Unconfirmed' tag for this new contact
             if ($tag_name) {
                 unset($tag_params);
                 $tag_params['contact_id'] = $this->_contactId;
                 $tag_params['tag_id'] = $this->_tagId;
                 $tag_params['version'] = 3;
                 $tag_value = civicrm_api('entity_tag', 'create', $tag_params);
             }
             break;
     }
     //send email
     $params['activityId'] = $result->id;
     $params['tagId'] = $this->_tagId;
     $transaction->commit();
     $this->bao->sendEmail($params, $this->_sendEmailMode);
     if ($result) {
         // call the hook before we redirect
         $this->postProcessHook();
         // set the template to thank you
         $url = CRM_Utils_System::url('civicrm/petition/thankyou', 'pid=' . $this->_surveyId . '&id=' . $this->_sendEmailMode . '&reset=1');
         CRM_Utils_System::redirect($url);
     }
 }
示例#20
0
 /**
  * @param CRM_Core_Form $form
  */
 public static function preProcessFromAddress(&$form)
 {
     $form->_single = FALSE;
     $className = CRM_Utils_System::getClassName($form);
     if (property_exists($form, '_context') && $form->_context != 'search' && $className == 'CRM_Contact_Form_Task_Email') {
         $form->_single = TRUE;
     }
     $form->_emails = $emails = array();
     $session = CRM_Core_Session::singleton();
     $contactID = $session->get('userID');
     $form->_contactIds = array($contactID);
     $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
     $form->_onHold = array();
     $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
     foreach ($contactEmails as $emailId => $item) {
         $email = $item['email'];
         if (!$email && count($emails) < 1) {
             // set it if no emails are present at all
             $form->_noEmails = TRUE;
         } else {
             if ($email) {
                 if (in_array($email, $emails)) {
                     // CRM-3624
                     continue;
                 }
                 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
                 $form->_onHold[$emailId] = $item['on_hold'];
                 $form->_noEmails = FALSE;
             }
         }
         $form->_emails[$emailId] = $emails[$emailId];
         $emails[$emailId] .= $item['locationType'];
         if ($item['is_primary']) {
             $emails[$emailId] .= ' ' . ts('(preferred)');
         }
         $emails[$emailId] = htmlspecialchars($emails[$emailId]);
     }
     $form->assign('noEmails', $form->_noEmails);
     if ($form->_noEmails) {
         CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address'));
     }
     // now add domain from addresses
     $domainEmails = array();
     $domainFrom = CRM_Core_OptionGroup::values('from_email_address');
     foreach (array_keys($domainFrom) as $k) {
         $domainEmail = $domainFrom[$k];
         $domainEmails[$domainEmail] = htmlspecialchars($domainEmail);
         $form->_emails[$domainEmail] = $domainEmail;
     }
     $form->_fromEmails = CRM_Utils_Array::crmArrayMerge($emails, $domainEmails);
     // Add signature
     $defaultEmail = civicrm_api3('email', 'getsingle', array('id' => key($form->_fromEmails)));
     $defaults = array();
     if (!empty($defaultEmail['signature_html'])) {
         $defaults['html_message'] = '<br/><br/>--' . $defaultEmail['signature_html'];
     }
     if (!empty($defaultEmail['signature_text'])) {
         $defaults['text_message'] = "\n\n--\n" . $defaultEmail['signature_text'];
     }
     $form->setDefaults($defaults);
 }
示例#21
0
 /**
  * Process the form after the input has been submitted and validated.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $dates = array('join_date', 'membership_start_date', 'membership_end_date');
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             $ids['membership'] = $key;
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             if (!empty($value['membership_type'])) {
                 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             }
             unset($value['membership_source']);
             unset($value['membership_type']);
             //Get the membership status
             $value['status_id'] = CRM_Utils_Array::value('membership_status', $value) ? $value['membership_status'] : CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $key, 'status_id');
             unset($value['membership_status']);
             foreach ($dates as $val) {
                 if (isset($value[$val])) {
                     $value[$val] = CRM_Utils_Date::processDate($value[$val]);
                 }
             }
             if (empty($customFields)) {
                 if (empty($value['membership_type_id'])) {
                     $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $key, 'membership_type_id');
                 }
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $key, 'Membership', $membershipTypeId);
             $membership = CRM_Member_BAO_Membership::add($value, $ids);
             // add custom field values
             if (!empty($value['custom']) && is_array($value['custom'])) {
                 CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_membership', $membership->id);
             }
         }
         CRM_Core_Session::setStatus(ts("Your updates have been saved."), ts('Saved'), 'success');
     } else {
         CRM_Core_Session::setStatus(ts("No updates have been saved."), ts('Not Saved'), 'alert');
     }
 }
示例#22
0
 /**
  * Given a list of conditions in params generate the required.
  * where clause
  *
  * @return string
  */
 public function whereClause()
 {
     $this->_where[0] = array();
     $this->_qill[0] = array();
     $this->includeContactIds();
     if (!empty($this->_params)) {
         foreach (array_keys($this->_params) as $id) {
             if (empty($this->_params[$id][0])) {
                 continue;
             }
             // check for both id and contact_id
             if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
                 if ($this->_params[$id][1] == 'IS NULL' || $this->_params[$id][1] == 'IS NOT NULL') {
                     $this->_where[0][] = "contact_a.id {$this->_params[$id][1]}";
                 } elseif (is_array($this->_params[$id][2])) {
                     $idList = implode("','", $this->_params[$id][2]);
                     //why on earth do they put ' in the middle & not on the outside? We have to assume it's
                     //to support 'something' so lets add them conditionally to support the api (which is a tested flow
                     // so if you are looking to alter this check api test results
                     if (strpos(trim($idList), "'") > 0) {
                         $idList = "'" . $idList . "'";
                     }
                     $this->_where[0][] = "contact_a.id IN ({$idList})";
                 } else {
                     $this->_where[0][] = self::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
                 }
             } else {
                 $this->whereClauseSingle($this->_params[$id]);
             }
         }
         CRM_Core_Component::alterQuery($this, 'where');
         CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where');
     }
     if ($this->_customQuery) {
         // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
         // Hope it wont affect the other part of civicrm.. if it does please remove it.
         if (!empty($this->_customQuery->_where)) {
             $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
         }
         $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
     }
     $clauses = array();
     $andClauses = array();
     $validClauses = 0;
     if (!empty($this->_where)) {
         foreach ($this->_where as $grouping => $values) {
             if ($grouping > 0 && !empty($values)) {
                 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
                 $validClauses++;
             }
         }
         if (!empty($this->_where[0])) {
             $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
         }
         if (!empty($clauses)) {
             $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
         }
         if ($validClauses > 1) {
             $this->_useDistinct = TRUE;
         }
     }
     return implode(' AND ', $andClauses);
 }
 /**
  * Build the form
  *
  * @access public
  *
  * @return void
  */
 function buildQuickForm()
 {
     $ufGroupId = $this->get('ufGroupId');
     if (!$ufGroupId) {
         CRM_Core_Error::fatal('ufGroupId is missing');
     }
     $this->_title = ts('Batch Update for Events') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
     CRM_Utils_System::setTitle($this->_title);
     $this->addDefaultButtons(ts('Save'));
     $this->_fields = array();
     $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
     // remove file type field and then limit fields
     $suppressFields = FALSE;
     $removehtmlTypes = array('File', 'Autocomplete-Select');
     foreach ($this->_fields as $name => $field) {
         if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) {
             $suppressFields = TRUE;
             unset($this->_fields[$name]);
         }
         //fix to reduce size as we are using this field in grid
         if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
             //shrink class to "form-text-medium"
             $this->_fields[$name]['attributes']['size'] = 19;
         }
     }
     $this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
     $this->addButtons(array(array('type' => 'submit', 'name' => ts('Update Participant(s)'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->assign('profileTitle', $this->_title);
     $this->assign('componentIds', $this->_participantIds);
     $fileFieldExists = FALSE;
     //load all campaigns.
     if (array_key_exists('participant_campaign_id', $this->_fields)) {
         $this->_componentCampaigns = array();
         CRM_Core_PseudoConstant::populate($this->_componentCampaigns, 'CRM_Event_DAO_Participant', TRUE, 'campaign_id', 'id', ' id IN (' . implode(' , ', array_values($this->_participantIds)) . ' ) ');
     }
     //fix for CRM-2752
     // get the option value for custom data type
     $this->_roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
     $this->_eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
     $this->_customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     foreach ($this->_participantIds as $participantId) {
         $roleId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'role_id');
         $eventId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'event_id');
         foreach ($this->_fields as $name => $field) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                 $customValue = CRM_Utils_Array::value($customFieldID, $this->_customFields);
                 $entityColumnValue = array();
                 if (CRM_Utils_Array::value('extends_entity_column_value', $customValue)) {
                     $entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customValue['extends_entity_column_value']);
                 }
                 $entityColumnValueRole = CRM_Utils_Array::value($roleId, $entityColumnValue);
                 if ($this->_roleCustomDataTypeID == $customValue['extends_entity_column_id'] && $entityColumnValueRole) {
                     CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
                 } elseif ($this->_eventNameCustomDataTypeID == $customValue['extends_entity_column_id'] && $eventId == $entityColumnValueRole) {
                     CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
                 } elseif (CRM_Utils_System::isNull($entityColumnValueRole)) {
                     CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
                 }
             } else {
                 if ($field['name'] == 'participant_role_id') {
                     $field['is_multiple'] = TRUE;
                 }
                 // handle non custom fields
                 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
             }
         }
     }
     $this->assign('fields', $this->_fields);
     // don't set the status message when form is submitted.
     $buttonName = $this->controller->getButtonName('submit');
     if ($suppressFields && $buttonName != '_qf_Batch_next') {
         CRM_Core_Session::setStatus("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update and have been excluded.");
     }
     $this->addDefaultButtons(ts('Update Participant(s)'));
 }
示例#24
0
 /**
  * This function is called after the user submits the form.
  *
  * @access public
  *
  * @return none
  */
 public function postProcess()
 {
     global $user;
     $isAdmin = in_array('civihr_admin', $user->roles) ? true : false;
     $session = CRM_Core_Session::singleton();
     $submitValues = $this->_submitValues;
     if (!empty($submitValues['contacts_id'])) {
         $this->_targetContactID = $submitValues['contacts_id'];
     }
     $absentDateDurations = array();
     $activityStatus = CRM_HRAbsence_BAO_HRAbsenceType::getActivityStatus('name');
     $activityStatusId['status_id'] = CRM_Utils_Array::key('Completed', $activityStatus);
     if (!empty($submitValues['date_values'])) {
         foreach (explode('|', $submitValues['date_values']) as $key => $dateString) {
             if ($dateString) {
                 $values = explode('(', $dateString);
                 $date = CRM_Utils_Date::processDate($values[0]);
                 $valuesDate = explode(':', $dateString);
                 $absentDateDurations[$date]['duration'] = (int) $valuesDate[1];
                 if (isset($valuesDate[2]) && $valuesDate[2] == 1 && $this->_showhide == 1 && array_key_exists('_qf_AbsenceRequest_done_save', $submitValues) || isset($valuesDate[2]) && $valuesDate[2] == 0 && $this->_showhide == 0 && array_key_exists('_qf_AbsenceRequest_done_save', $submitValues)) {
                     $absentDateDurations[$date]['approval'] = CRM_Utils_Array::key('Scheduled', $activityStatus);
                 } elseif (isset($valuesDate[2]) && $valuesDate[2] == 0 && $this->_showhide == 1) {
                     $absentDateDurations[$date]['approval'] = CRM_Utils_Array::key('Rejected', $activityStatus);
                 } elseif (array_key_exists('_qf_AbsenceRequest_done_saveandapprove', $submitValues) || array_key_exists('_qf_AbsenceRequest_done_approve', $submitValues)) {
                     $absentDateDurations[$date]['approval'] = CRM_Utils_Array::key('Completed', $activityStatus);
                 }
             }
         }
     }
     // set email template values
     $taDays = explode('|', $submitValues['tot_app_days']);
     $totDays = $taDays[0];
     if (!empty($taDays[1])) {
         $appDays = $taDays[1];
     }
     $msgTempResult = civicrm_api3('MessageTemplate', 'get', array('msg_title' => "Absence Email"));
     $targetContactResult = civicrm_api3('contact', 'get', array('id' => $this->_targetContactID));
     $mailprm[$this->_targetContactID]['display_name'] = $targetContactResult['values'][$this->_targetContactID]['display_name'];
     $mailprm[$this->_targetContactID]['email'] = $targetContactResult['values'][$this->_targetContactID]['email'];
     $tplParams = array('messageTemplateID' => $msgTempResult['values'][$msgTempResult['id']]['id'], 'empName' => $mailprm[$this->_targetContactID]['display_name'], 'absenceType' => $this->_absenceType, 'absentDateDurations' => $absentDateDurations, 'startDate' => $submitValues['start_date'], 'endDate' => $submitValues['end_date'], 'empPosition' => $this->_empPosition, 'totDays' => $totDays, 'jobHoursTime' => $this->_jobHoursTime);
     if (!empty($appDays)) {
         $tplParams['appDays'] = $appDays;
     }
     $sendTemplateParams = array('messageTemplateID' => $tplParams['messageTemplateID'], 'contactId' => $this->_targetContactID, 'tplParams' => $tplParams);
     if ($this->_action & CRM_Core_Action::ADD) {
         $activityParam = array('sequential' => 1, 'source_contact_id' => $this->_loginUserID, 'target_contact_id' => $this->_targetContactID, 'assignee_contact_id' => $this->_managerContactID, 'activity_type_id' => $this->_activityTypeID);
         if (array_key_exists('_qf_AbsenceRequest_done_saveandapprove', $submitValues) || $isAdmin) {
             $activityParam['status_id'] = CRM_Utils_Array::key('Completed', $activityStatus);
         } else {
             //we want to keep the activity status in Scheduled for new absence if save button is clicked
             $activityParam['status_id'] = CRM_Utils_Array::key('Scheduled', $activityStatus);
         }
         $result = civicrm_api3('Activity', 'create', $activityParam);
         //save the custom data
         if (!empty($submitValues['hidden_custom'])) {
             $customFields = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeID), CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
             $customValues = CRM_Core_BAO_CustomField::postProcess($submitValues, $customFields, $result['id'], 'Activity');
             CRM_Core_BAO_CustomValueTable::store($customValues, 'civicrm_activity', $result['id']);
         }
         if (!empty($customValues)) {
             $customGroup = array();
             foreach ($customValues as $fieldID => $values) {
                 foreach ($values as $fieldValue) {
                     $customValue = array('data' => $fieldValue['value']);
                     $customFields[$fieldID]['id'] = $fieldID;
                     $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID], TRUE);
                     $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
                 }
             }
             $sendTemplateParams['tplParams']['customGroup'] = $customGroup;
         }
         $activityLeavesParam = array('sequential' => 1, 'source_record_id' => $result['id'], 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Absence', 'name'));
         foreach ($absentDateDurations as $date => $duration) {
             $activityLeavesParam['activity_date_time'] = $date;
             $activityLeavesParam['duration'] = $duration['duration'];
             $activityLeavesParam['status_id'] = $duration['approval'];
             civicrm_api3('Activity', 'create', $activityLeavesParam);
         }
         if (array_key_exists('_qf_AbsenceRequest_done_save', $submitValues)) {
             $sendTemplateParams['from'] = $mailprm[$this->_targetContactID]['email'];
             CRM_Core_Session::setStatus(ts('Absence(s) have been applied.'), ts('Saved'), 'success');
         } elseif (array_key_exists('_qf_AbsenceRequest_done_saveandapprove', $submitValues) || $isAdmin) {
             if (!empty($this->_managerContactID)) {
                 $emailID = civicrm_api3('contact', 'get', array('id' => $this->_loginUserID));
                 $sendTemplateParams['from'] = $emailID['values'][$emailID['id']]['email'];
             }
             $sendTemplateParams['tplParams']['approval'] = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been applied and approved.'), ts('Saved'), 'success');
         }
         $managerContactResult = array();
         if (!empty($this->_managerContactID)) {
             foreach ($this->_managerContactID as $key => $val) {
                 $managerContactResult = civicrm_api3('contact', 'get', array('id' => $val));
                 if (!empty($val) && !empty($managerContactResult['values'])) {
                     $mailprm[$val]['display_name'] = $managerContactResult['values'][$val]['display_name'];
                     $mailprm[$val]['email'] = $managerContactResult['values'][$val]['email'];
                 }
             }
         }
         self::sendAbsenceMail($mailprm, $sendTemplateParams);
         $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
     } elseif ($this->_mode == 'edit') {
         if (array_key_exists('_qf_AbsenceRequest_done_cancelabsence', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Cancelled', $activityStatus);
             $activityParam = array('sequential' => 1, 'id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId);
             $result = civicrm_api3('Activity', 'create', $activityParam);
             $subact = civicrm_api3('Activity', 'get', array('return' => "id", 'source_record_id' => $result['id']));
             foreach ($subact['values'] as $key => $val) {
                 civicrm_api3('Activity', 'create', array('id' => $val['id'], 'status_id' => $statusId));
             }
             $sendTemplateParams['from'] = $mailprm[$this->_targetContactID]['email'];
             $sendTemplateParams['tplParams']['cancel'] = $sendMail = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been Cancelled.'), ts('Cancelled'), 'success');
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$result['id']}"));
         } elseif (array_key_exists('_qf_AbsenceRequest_done_approve', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Completed', $activityStatus);
             $activityParam = array('sequential' => 1, 'id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId);
             $result = civicrm_api3('Activity', 'get', array('source_record_id' => $submitValues['source_record_id'], 'option.limit' => 365));
             foreach ($result['values'] as $row_result) {
                 civicrm_api3('Activity', 'delete', array('id' => $row_result['id']));
             }
             foreach ($absentDateDurations as $date => $duration) {
                 $resultAct = civicrm_api3('Activity', 'create', array('activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Absence', 'name'), 'source_record_id' => $submitValues['source_record_id'], 'activity_date_time' => $date, 'duration' => $duration['duration'], 'status_id' => $duration['approval']));
             }
             $result = civicrm_api3('Activity', 'create', $activityParam);
             if (!empty($this->_managerContactID)) {
                 $emailID = civicrm_api3('contact', 'get', array('id' => $this->_loginUserID));
                 $sendTemplateParams['from'] = $emailID['values'][$emailID['id']]['email'];
             }
             $sendTemplateParams['tplParams']['approval'] = $sendMail = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been Approved.'), ts('Approved'), 'success');
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$result['id']}"));
         } elseif (array_key_exists('_qf_AbsenceRequest_done_reject', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Rejected', $activityStatus);
             $activityParam = array('id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId);
             $result = civicrm_api3('Activity', 'create', $activityParam);
             $subact = civicrm_api3('Activity', 'get', array('return' => "id", 'source_record_id' => $result['id']));
             foreach ($subact['values'] as $key => $val) {
                 civicrm_api3('Activity', 'create', array('id' => $val['id'], 'status_id' => $statusId));
             }
             if (!empty($this->_managerContactID)) {
                 $emailID = civicrm_api3('contact', 'get', array('id' => $this->_loginUserID));
                 $sendTemplateParams['from'] = $emailID['values'][$emailID['id']]['email'];
             }
             $sendTemplateParams['tplParams']['reject'] = $sendMail = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been Rejected.'), ts('Rejected'), 'success');
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$result['id']}"));
         } elseif (array_key_exists('_qf_AbsenceRequest_done_cancel', $submitValues)) {
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
         } else {
             $result = civicrm_api3('Activity', 'get', array('source_record_id' => $submitValues['source_record_id'], 'option.limit' => 365));
             foreach ($result['values'] as $row_result) {
                 civicrm_api3('Activity', 'delete', array('id' => $row_result['id']));
             }
             foreach ($absentDateDurations as $date => $duration) {
                 $result = civicrm_api3('Activity', 'create', array('activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Absence', 'name'), 'source_record_id' => $submitValues['source_record_id'], 'activity_date_time' => $date, 'duration' => $duration['duration'], 'status_id' => $duration['approval']));
             }
             $buttonName = $this->controller->getButtonName();
             if ($buttonName == "_qf_AbsenceRequest_done_save") {
                 $this->_aid = $submitValues['source_record_id'];
                 $sendTemplateParams['from'] = $mailprm[$this->_targetContactID]['email'];
                 $sendTemplateParams['tplParams']['save'] = $sendMail = TRUE;
                 $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
             }
         }
         if (!empty($submitValues['hidden_custom'])) {
             $customFields = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeID), CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
             $customValues = CRM_Core_BAO_CustomField::postProcess($submitValues, $customFields, $result['id'], 'Activity');
             CRM_Core_BAO_CustomValueTable::store($customValues, 'civicrm_activity', $result['id']);
         }
         if (!empty($customValues)) {
             $customGroup = array();
             foreach ($customValues as $fieldID => $values) {
                 foreach ($values as $fieldValue) {
                     $customValue = array('data' => $fieldValue['value']);
                     $customFields[$fieldID]['id'] = $fieldID;
                     $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID], TRUE);
                     $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
                 }
             }
             $sendTemplateParams['tplParams']['customGroup'] = $customGroup;
         }
         if ($sendMail) {
             //send mail to multiple manager
             $managerContactResult = array();
             if (!empty($this->_managerContactID)) {
                 foreach ($this->_managerContactID as $key => $val) {
                     $managerContactResult = civicrm_api3('contact', 'get', array('id' => $val));
                     if (!empty($val) && !empty($managerContactResult['values'])) {
                         $mailprm[$val]['display_name'] = $managerContactResult['values'][$val]['display_name'];
                         $mailprm[$val]['email'] = $managerContactResult['values'][$val]['email'];
                     }
                 }
             }
             self::sendAbsenceMail($mailprm, $sendTemplateParams);
         }
     } else {
         if (CRM_Utils_Request::retrieve('aid', 'Positive', $this)) {
             $activityIDs = CRM_Utils_Request::retrieve('aid', 'Positive', $this);
         }
         if (array_key_exists('_qf_AbsenceRequest_done_cancelabsence', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Cancelled', $activityStatus);
             $statusMsg = ts('Absence(s) have been Cancelled');
         } elseif (array_key_exists('_qf_AbsenceRequest_done_cancel', $submitValues)) {
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
         }
         civicrm_api3('Activity', 'create', array('id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId));
         CRM_Core_Session::setStatus($statusMsg, '', 'success');
         $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$activityIDs}"));
     }
 }
示例#25
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $contactTags = $tagList = array();
     // check if contact tags exists
     if (!empty($params['tag'])) {
         $contactTags = $params['tag'];
     }
     // check if tags are selected from taglists
     if (!empty($params['contact_taglist'])) {
         foreach ($params['contact_taglist'] as $val) {
             if ($val) {
                 if (is_numeric($val)) {
                     $tagList[$val] = 1;
                 } else {
                     $tagIDs = explode(',', $val);
                     if (!empty($tagIDs)) {
                         foreach ($tagIDs as $tagID) {
                             if (is_numeric($tagID)) {
                                 $tagList[$tagID] = 1;
                             }
                         }
                     }
                 }
             }
         }
     }
     $tagSets = CRM_Core_BAO_Tag::getTagsUsedFor('civicrm_contact', FALSE, TRUE);
     foreach ($tagSets as $key => $value) {
         $this->_tags[$key] = $value['name'];
     }
     // merge contact and taglist tags
     $allTags = CRM_Utils_Array::crmArrayMerge($contactTags, $tagList);
     $this->_name = array();
     foreach ($allTags as $key => $dnc) {
         $this->_name[] = $this->_tags[$key];
         list($total, $added, $notAdded) = CRM_Core_BAO_EntityTag::addEntitiesToTag($this->_contactIds, $key);
         $status = array(ts('%count contact tagged', array('count' => $added, 'plural' => '%count contacts tagged')));
         if ($notAdded) {
             $status[] = ts('%count contact already had this tag', array('count' => $notAdded, 'plural' => '%count contacts already had this tag'));
         }
         $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
         CRM_Core_Session::setStatus($status, ts("Added Tag <em>%1</em>", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
     }
 }
 /**
  * Process credit card payment.
  *
  * @param array $submittedValues
  * @param array $lineItem
  *
  * @throws CRM_Core_Exception
  */
 protected function processCreditCard($submittedValues, $lineItem)
 {
     $sendReceipt = $contribution = FALSE;
     $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
     foreach ($unsetParams as $key) {
         if (isset($submittedValues[$key])) {
             unset($submittedValues[$key]);
         }
     }
     $isTest = $this->_mode == 'test' ? 1 : 0;
     // CRM-12680 set $_lineItem if its not set
     if (empty($this->_lineItem) && !empty($lineItem)) {
         $this->_lineItem = $lineItem;
     }
     //Get the require fields value only.
     $params = $this->_params = $submittedValues;
     $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
     // Get the payment processor id as per mode.
     $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $this->assign('displayName', $this->userDisplayName);
     }
     // Set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->userEmail;
     // now set the values for the billing location.
     foreach (array_keys($this->_fields) as $name) {
         $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;
     $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;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype);
     // add all the additional payment params we need
     if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
         $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}"]);
     }
     if (!empty($this->_params["billing_country_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}"]);
     }
     $legacyCreditCardExpiryCheck = FALSE;
     if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) {
         $legacyCreditCardExpiryCheck = TRUE;
     }
     if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) {
         $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'] = $this->_params['total_amount'];
     $this->_params['amount_level'] = 0;
     $this->_params['description'] = ts('Office Credit Card contribution');
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, CRM_Core_Config::singleton()->defaultCurrency);
     $this->_params['payment_action'] = 'Sale';
     if (!empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
     }
     if (!empty($params['soft_credit_to'])) {
         $this->_params['soft_credit_to'] = $params['soft_credit_to'];
         $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
     }
     $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
     $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
     $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     // 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;
     $paymentParams['contactID'] = $this->_contactID;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     $contributionType = new CRM_Financial_DAO_FinancialType();
     $contributionType->id = $params['financial_type_id'];
     // Add some financial type details to the params list
     // if folks need to use it.
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->userEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     // For recurring contribution, create Contribution Record first.
     // Contribution ID, Recurring ID and Contact ID needed
     // When we get a callback from the payment processor, CRM-7115
     if (!empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, NULL, $this->_contactID, $contributionType, TRUE, FALSE, $isTest, $this->_lineItem);
         $paymentParams['contributionID'] = $contribution->id;
         $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
         $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
         $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
     }
     $result = array();
     if ($paymentParams['amount'] > 0.0) {
         // force a re-get of the payment processor in case the form changed it, CRM-7179
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
         try {
             $result = $payment->doPayment($paymentParams, 'contribute');
         } catch (CRM_Core_Exception $e) {
             $message = ts("Payment Processor Error message") . $e->getMessage();
             $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
             // Set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             if (!empty($this->_ppID)) {
                 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
             }
             CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error'));
         }
     }
     $this->_params = array_merge($this->_params, $result);
     $this->_params['receive_date'] = $now;
     if (!empty($this->_params['is_email_receipt'])) {
         $this->_params['receipt_date'] = $now;
     } else {
         $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE);
     }
     $this->set('params', $this->_params);
     $this->assign('trxn_id', $result['trxn_id']);
     $this->assign('receive_date', $this->_params['receive_date']);
     // Result has all the stuff we need
     // lets archive it to a financial transaction
     if ($contributionType->is_deductible) {
         $this->assign('is_deductible', TRUE);
         $this->set('is_deductible', TRUE);
     }
     // Set source if not set
     if (empty($this->_params['source'])) {
         $userID = CRM_Core_Session::singleton()->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     // Build custom data getFields array
     $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('financial_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
     if (empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, $isTest, $this->_lineItem);
     }
     // Send receipt mail.
     if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
         $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $this->_params['contact_id'] = $this->_contactID;
         $this->_params['contribution_id'] = $contribution->id;
         $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
     }
     //process the note
     if ($contribution->id && isset($params['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
     }
     //process premium
     if ($contribution->id && isset($params['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
     }
     //update pledge payment status.
     if ($this->_ppID && $contribution->id) {
         // Store contribution id in payment record.
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
         CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount);
     }
     if ($contribution->id) {
         $statusMsg = ts('The contribution record has been processed.');
         if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     }
 }
示例#27
0
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::del($this->_id);
         return;
     }
     $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
     $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     $isTest = $this->_mode == 'test' ? 1 : 0;
     $lineItems = NULL;
     if (!empty($this->_lineItem)) {
         $lineItems = $this->_lineItem;
     }
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $this->convertDateFieldsToMySQL($formValues);
     $params = $softParams = $ids = array();
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($this->_params['auto_renew'])) {
         $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = NULL;
     if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) {
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     $termsByType = array();
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
             $params['tax_amount'] = $this->_params['tax_amount'];
         }
         $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
         if (!empty($lineItem[$priceSetId])) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 if (!empty($li['membership_type_id'])) {
                     if (!empty($li['membership_num_terms'])) {
                         $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                     }
                 }
                 ///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
                 if ($isQuickConfig && $submittedFinancialType) {
                     $li['financial_type_id'] = $submittedFinancialType;
                 }
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         if (empty($memTypeNumTerms)) {
             $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
         }
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
             //$params[$d] = CRM_Utils_Date::processDate( $date );
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     foreach ($this->_memTypeSelected as $memType) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     }
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-13981, allow different person as a soft-contributor of chosen type
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($this->_params['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             $softParams['contact_id'] = $this->_contactID;
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             if (empty($formValues['source'])) {
                 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
             } else {
                 $params['contribution_source'] = $formValues['source'];
             }
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         if (empty($formValues['total_amount']) && !$priceSetId) {
             // if total amount not provided minimum for membership type is used
             $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee');
         } else {
             $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         }
         if ($priceSetId && !$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $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
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $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}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         }
         // 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['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['description'] = ts('Office Credit Card Membership Signup Contribution');
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         $this->_params['financial_type_id'] = $params['financial_type_id'];
         // 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;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             }
         }
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recuring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $contributionType = new CRM_Financial_DAO_FinancialType();
             $contributionType->id = $params['financial_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, TRUE, FALSE, $isTest, $lineItems);
             //create new soft-credit record, CRM-13981
             if ($softParams) {
                 $softParams['contribution_id'] = $contribution->id;
                 $softParams['currency'] = $contribution->currency;
                 $softParams['amount'] = $contribution->total_amount;
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             $paymentParams['contactID'] = $this->_contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
         }
         if ($params['total_amount'] > 0.0) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $result = $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (!empty($paymentParams['contributionID'])) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (!empty($paymentParams['contributionRecurID'])) {
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
             //assign amount to template if payment was successful
             $this->assign('amount', $params['total_amount']);
         }
         // if the payment processor returns a contribution_status_id -> use it!
         if (isset($result['contribution_status_id'])) {
             $result['payment_status_id'] = $result['contribution_status_id'];
         }
         if (isset($result['payment_status_id'])) {
             // CRM-16737 $result['contribution_status_id'] is deprecated in favour
             // of payment_status_id as the payment processor only knows whether the payment is complete
             // not whether payment completes the contribution
             $params['contribution_status_id'] = $result['payment_status_id'];
         } else {
             $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1;
         }
         if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             // unset send-receipt option, since receipt will be sent when ipn is received.
             unset($this->_params['send_receipt'], $formValues['send_receipt']);
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dp => $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($this->_params['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             //CRM-15366
             if (!empty($softParams) && empty($paymentParams['is_recur'])) {
                 $membershipParams['soft_credit'] = $softParams;
             }
             if (!empty($paymentParams['is_recur']) && CRM_Utils_Array::value('payment_status_id', $result) == 1) {
                 // CRM-16993 we have a situation where line items have already been created.
                 unset($membershipParams['lineItems']);
             }
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
             unset($params['lineItems']);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $fieldType = NULL;
                 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
                     $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
                 }
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 $contributionBAO = new CRM_Contribute_BAO_Contribution();
                 $contributionBAO->id = $params['contribution_id'];
                 $contributionBAO->contact_id = $params['contact_id'];
                 $contributionBAO->find();
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
                 //create new soft-credit record, CRM-13981
                 if ($softParams) {
                     $softParams['contribution_id'] = $params['contribution_id'];
                     while ($contributionBAO->fetch()) {
                         $softParams['currency'] = $contributionBAO->currency;
                         $softParams['amount'] = $contributionBAO->total_amount;
                     }
                     CRM_Contribute_BAO_ContributionSoft::add($softParams);
                 }
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             // FIX ME: need to recheck this
             // here we might updated dates, so get from object.
             foreach ($calcDates[$membership->membership_type_id] as $date => &$val) {
                 if ($membership->{$date}) {
                     $val = $membership->{$date};
                 }
             }
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 if (!empty($softParams)) {
                     $membershipParams['soft_credit'] = $softParams;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
                 unset($params['lineItems']);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$priceSetId])) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $taxAmount = FALSE;
         $totalTaxAmount = 0;
         foreach ($lineItem[$priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
             if ($invoicing && isset($priceFieldOp['tax_amount'])) {
                 $taxAmount = TRUE;
                 $totalTaxAmount += $priceFieldOp['tax_amount'];
             }
         }
         if ($invoicing) {
             $dataArray = array();
             foreach ($lineItem[$priceSetId] as $key => $value) {
                 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                     if (isset($dataArray[$value['tax_rate']])) {
                         $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                     } else {
                         $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                     }
                 }
             }
             if ($taxAmount) {
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
             }
             $this->assign('dataArray', $dataArray);
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
     $membershipIds = $this->_membershipIDs;
     if ($contributionId && !empty($membershipIds)) {
         $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
         if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
             $receiptSend = TRUE;
         }
     }
     if (!empty($formValues['send_receipt']) && $receiptSend) {
         $formValues['contact_id'] = $this->_contactID;
         $formValues['contribution_id'] = $contributionId;
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         //end date can be modified by hooks, so if end date is set then use it.
         $endDate = $membership->end_date ? $membership->end_date : $endDate;
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
         if ($endDate && $endDate !== 'null') {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // FIX ME: fix status messages
         $statusMsg = array();
         foreach ($membershipTypes as $memType => $membershipType) {
             $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName));
             $membership = $createdMemberships[$memType];
             $memEndDate = $membership->end_date ? $membership->end_date : $endDate;
             //get the end date from calculated dates.
             if (!$memEndDate && empty($params['is_recur'])) {
                 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
             }
             if ($memEndDate && $memEndDate !== 'null') {
                 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
                 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
             }
         }
         $statusMsg = implode('<br/>', $statusMsg);
         if ($receiptSend && !empty($mailSend)) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
     }
 }
示例#28
0
 /**
  * Process the form submission.
  *
  *
  * @param array $params
  *
  * @return void
  */
 public function postProcess($params = NULL)
 {
     $transaction = new CRM_Core_Transaction();
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = NULL;
         //block deleting activities which affects
         //case attributes.CRM-4543
         $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
         $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
         if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
             $params = array('id' => $this->_activityId);
             $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, TRUE);
             if ($activityDelete) {
                 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
             }
         } else {
             $statusMsg = ts("Selected Activity cannot be deleted.");
         }
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = NULL;
         $params = array('id' => $this->_activityId);
         $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
         if ($activityRestore) {
             $statusMsg = ts('The selected activity has been restored.<br />');
         }
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     //set parent id if its edit mode
     if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
         $params['parent_id'] = $parentId;
     }
     // store the dates with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     $params['activity_type_id'] = $this->_activityTypeId;
     // format with contact (target contact) values
     if (isset($params['target_contact_id'])) {
         $params['target_contact_id'] = explode(',', $params['target_contact_id']);
     } else {
         $params['target_contact_id'] = array();
     }
     // format activity custom data
     if (!empty($params['hidden_custom'])) {
         if ($this->_activityId) {
             // unset custom fields-id from params since we want custom
             // fields to be saved for new activity.
             foreach ($params as $key => $value) {
                 $match = array();
                 if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) {
                     $params[$match[1] . '-1'] = $params[$key];
                     // for autocomplete transfer hidden value instead of label
                     if ($params[$key] && isset($params[$key . '_id'])) {
                         $params[$match[1] . '-1_id'] = $params[$key . '_id'];
                         unset($params[$key . '_id']);
                     }
                     unset($params[$key]);
                 }
             }
         }
         // build custom data getFields array
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_activityId, 'Activity');
     }
     // assigning formatted value
     if (!empty($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = array();
     }
     if (isset($this->_activityId)) {
         // activity which hasn't been modified by a user yet
         if ($this->_defaults['is_auto'] == 1) {
             $params['is_auto'] = 0;
         }
         // always create a revision of an case activity. CRM-4533
         $newActParams = $params;
         // add target contact values in update mode
         if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
             $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
         }
     }
     if (!isset($newActParams)) {
         // add more attachments if needed for old activity
         CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($params);
         foreach ($this->_caseId as $key => $val) {
             $params['case_id'] = $val;
             // activity create/update
             $activity = CRM_Activity_BAO_Activity::create($params);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($params, $activity);
         }
     } else {
         // since the params we need to set are very few, and we don't want rest of the
         // work done by bao create method , lets use dao object to make the changes
         $params = array('id' => $this->_activityId);
         $params['is_current_revision'] = 0;
         $activity = new CRM_Activity_DAO_Activity();
         $activity->copyValues($params);
         $activity->save();
     }
     // create a new version of activity if activity was found to
     // have been modified/created by user
     if (isset($newActParams)) {
         // set proper original_id
         if (!empty($this->_defaults['original_id'])) {
             $newActParams['original_id'] = $this->_defaults['original_id'];
         } else {
             $newActParams['original_id'] = $activity->id;
         }
         //is_current_revision will be set to 1 by default.
         // add attachments if any
         CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($newActParams);
         foreach ($this->_caseId as $key => $val) {
             $newActParams['case_id'] = $val;
             $activity = CRM_Activity_BAO_Activity::create($newActParams);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($newActParams, $activity);
         }
         // copy files attached to old activity if any, to new one,
         // as long as users have not selected the 'delete attachment' option.
         if (empty($newActParams['is_delete_attachment'])) {
             CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id);
         }
         // copy back params to original var
         $params = $newActParams;
     }
     foreach ($vvalue as $vkey => $vval) {
         if ($vval['actId']) {
             // add tags if exists
             $tagParams = array();
             if (!empty($params['tag'])) {
                 foreach ($params['tag'] as $tag) {
                     $tagParams[$tag] = 1;
                 }
             }
             //save static tags
             CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $vval['actId']);
             //save free tags
             if (isset($params['taglist']) && !empty($params['taglist'])) {
                 CRM_Core_Form_Tag::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
             }
         }
         // update existing case record if needed
         $caseParams = $params;
         $caseParams['id'] = $vval['case_id'];
         if (!empty($caseParams['case_status_id'])) {
             $caseParams['status_id'] = $caseParams['case_status_id'];
         }
         // unset params intended for activities only
         unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']);
         $case = CRM_Case_BAO_Case::create($caseParams);
         // create case activity record
         $caseParams = array('activity_id' => $vval['actId'], 'case_id' => $vval['case_id']);
         CRM_Case_BAO_Case::processCaseActivity($caseParams);
     }
     // Insert civicrm_log record for the activity (e.g. store the
     // created / edited by contact id and date for the activity)
     // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
     // send copy to selected contacts.
     $mailStatus = '';
     $mailToContacts = array();
     //CRM-5695
     //check for notification settings for assignee contacts
     $selectedContacts = array('contact_check');
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
         $selectedContacts[] = 'assignee_contact_id';
     }
     foreach ($vvalue as $vkey => $vval) {
         foreach ($selectedContacts as $dnt => $val) {
             if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) {
                 if ($val == 'contact_check') {
                     $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
                 } else {
                     $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
                     $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
                 }
                 //build an associative array with unique email addresses.
                 foreach ($params[$val] as $key => $value) {
                     if ($val == 'contact_check') {
                         $id = $key;
                     } else {
                         $id = $value;
                     }
                     if (isset($id) && array_key_exists($id, $this->_relatedContacts) && isset($this->_relatedContacts[$id]['email'])) {
                         //if email already exists in array then append with ', ' another role only otherwise add it to array.
                         if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
                             $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
                             $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
                         } else {
                             $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
                         }
                     }
                 }
             }
         }
         $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId);
         $result = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts, $extraParams);
         if (empty($result)) {
             $mailStatus = '';
         }
         // create follow up activity if needed
         $followupStatus = '';
         if (!empty($params['followup_activity_type_id'])) {
             $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($vval['actId'], $params);
             if ($followupActivity) {
                 $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $vval['case_id']);
                 CRM_Case_BAO_Case::processCaseActivity($caseParams);
                 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
             }
         }
         $title = ts("%1 Saved", array(1 => $this->_activityTypeName));
         CRM_Core_Session::setStatus($followupStatus . $mailStatus, $title, 'success');
     }
 }
示例#29
0
 /**
  * process membership records
  *
  * @param array $params associated array of submitted values
  *
  * @access public
  *
  * @return bool
  */
 private function processMembership(&$params)
 {
     $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate');
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     // get the price set associated with offline memebership
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
     $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             foreach ($dateTypes as $dateField => $dateVariable) {
                 ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]);
             }
             $calcDates = array();
             $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate);
             foreach ($calcDates as $memType => $calcDate) {
                 foreach ($dates as $d) {
                     //first give priority to form values then calDates.
                     $date = CRM_Utils_Array::value($d, $value);
                     if (!$date) {
                         $date = CRM_Utils_Array::value($d, $calcDate);
                     }
                     $value[$d] = CRM_Utils_Date::processDate($date);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             if (!empty($value['membership_status'])) {
                 $value['status_id'] = $value['membership_status'];
                 unset($value['membership_status']);
             }
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membershipTypeId);
             if (!empty($value['financial_type'])) {
                 $value['financial_type_id'] = $value['financial_type'];
             }
             if (!empty($value['payment_instrument'])) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             // handle soft credit
             if (is_array(CRM_Utils_Array::value('soft_credit_contact_id', $params)) && !empty($params['soft_credit_contact_id'][$key]) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
             }
             if (!empty($value['receive_date'])) {
                 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             unset($value['financial_type']);
             unset($value['payment_instrument']);
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // make entry in line item for contribution
             $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]);
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (!empty($editedResults)) {
                 unset($this->_priceSet['fields']);
                 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
                 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
                 $fid = $editedResults['id'];
                 $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']);
                 $editedResults = array();
                 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
                 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
                 if (!empty($value['total_amount'])) {
                     $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
                 }
                 $fieldID = key($this->_priceSet['fields']);
                 $value['price_' . $fieldID] = $editedResults['id'];
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
                 //CRM-11529 for backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                     foreach ($lineItem[$priceSetId] as &$values) {
                         $values['financial_type_id'] = $value['financial_type_id'];
                     }
                 }
                 $value['lineItems'] = $lineItem;
                 $value['processPriceSet'] = TRUE;
             }
             // end of contribution related section
             unset($value['membership_type']);
             unset($value['membership_start_date']);
             unset($value['membership_end_date']);
             $value['is_renew'] = false;
             if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
                 $this->_params = $params;
                 $value['is_renew'] = true;
                 $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($value['contact_id'], $value['membership_type_id'], FALSE, $this, NULL, NULL, $value['custom']);
                 // make contribution entry
                 CRM_Member_BAO_Membership::recordMembershipContribution(array_merge($value, array('membership_id' => $membership->id)));
             } else {
                 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $value['contribution_id'], 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($membership->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['membership_id'] = $membership->id;
                 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
             }
         }
     }
     return TRUE;
 }
示例#30
0
 /**
  * setDefault componet specific profile fields.
  *
  * @param array $fields
  *   Profile fields.
  * @param int $componentId
  *   ComponetID.
  * @param string $component
  *   Component name.
  * @param array $defaults
  *   An array of default values.
  *
  * @param bool $isStandalone
  */
 public static function setComponentDefaults(&$fields, $componentId, $component, &$defaults, $isStandalone = FALSE)
 {
     if (!$componentId || !in_array($component, array('Contribute', 'Membership', 'Event', 'Activity'))) {
         return;
     }
     $componentBAO = $componentSubType = NULL;
     switch ($component) {
         case 'Membership':
             $componentBAO = 'CRM_Member_BAO_Membership';
             $componentBAOName = 'Membership';
             $componentSubType = array('membership_type_id');
             break;
         case 'Contribute':
             $componentBAO = 'CRM_Contribute_BAO_Contribution';
             $componentBAOName = 'Contribution';
             $componentSubType = array('financial_type_id');
             break;
         case 'Event':
             $componentBAO = 'CRM_Event_BAO_Participant';
             $componentBAOName = 'Participant';
             $componentSubType = array('role_id', 'event_id', 'event_type_id');
             break;
         case 'Activity':
             $componentBAO = 'CRM_Activity_BAO_Activity';
             $componentBAOName = 'Activity';
             $componentSubType = array('activity_type_id');
             break;
     }
     $values = array();
     $params = array('id' => $componentId);
     //get the component values.
     CRM_Core_DAO::commonRetrieve($componentBAO, $params, $values);
     if ($componentBAOName == 'Participant') {
         $values += array('event_type_id' => CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values['event_id'], 'event_type_id'));
     }
     $formattedGroupTree = array();
     $dateTimeFields = array('participant_register_date', 'activity_date_time', 'receive_date', 'receipt_date', 'cancel_date', 'thankyou_date', 'membership_start_date', 'membership_end_date', 'join_date');
     foreach ($fields as $name => $field) {
         $fldName = $isStandalone ? $name : "field[{$componentId}][{$name}]";
         if (in_array($name, $dateTimeFields)) {
             $timefldName = $isStandalone ? "{$name}_time" : "field[{$componentId}][{$name}_time]";
             if (!empty($values[$name])) {
                 list($defaults[$fldName], $defaults[$timefldName]) = CRM_Utils_Date::setDateDefaults($values[$name]);
             }
         } elseif (array_key_exists($name, $values)) {
             $defaults[$fldName] = $values[$name];
         } elseif ($name == 'participant_note') {
             $noteDetails = CRM_Core_BAO_Note::getNote($componentId, 'civicrm_participant');
             $defaults[$fldName] = array_pop($noteDetails);
         } elseif (in_array($name, array('financial_type', 'payment_instrument', 'participant_status', 'participant_role'))) {
             $defaults[$fldName] = $values["{$name}_id"];
         } elseif ($name == 'membership_type') {
             // since membership_type field is a hierselect -
             $defaults[$fldName][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values['membership_type_id'], 'member_of_contact_id', 'id');
             $defaults[$fldName][1] = $values['membership_type_id'];
         } elseif ($name == 'membership_status') {
             $defaults[$fldName] = $values['status_id'];
         } elseif ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($name, TRUE)) {
             if (empty($formattedGroupTree)) {
                 //get the groupTree as per subTypes.
                 $groupTree = array();
                 foreach ($componentSubType as $subType) {
                     $subTree = CRM_Core_BAO_CustomGroup::getTree($componentBAOName, CRM_Core_DAO::$_nullObject, $componentId, 0, $values[$subType]);
                     $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $subTree);
                 }
                 $formattedGroupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, CRM_Core_DAO::$_nullObject);
                 CRM_Core_BAO_CustomGroup::setDefaults($formattedGroupTree, $defaults);
             }
             //FIX ME: We need to loop defaults, but once we move to custom_1_x convention this code can be simplified.
             foreach ($defaults as $customKey => $customValue) {
                 if ($customFieldDetails = CRM_Core_BAO_CustomField::getKeyID($customKey, TRUE)) {
                     if ($name == 'custom_' . $customFieldDetails[0]) {
                         //hack to set default for checkbox
                         //basically this is for weired field name like field[33][custom_19]
                         //we are converting this field name to array structure and assign value.
                         $skipValue = FALSE;
                         foreach ($formattedGroupTree as $tree) {
                             if (!empty($tree['fields'][$customFieldDetails[0]])) {
                                 if ('CheckBox' == CRM_Utils_Array::value('html_type', $tree['fields'][$customFieldDetails[0]])) {
                                     $skipValue = TRUE;
                                     $defaults['field'][$componentId][$name] = $customValue;
                                     break;
                                 } elseif (CRM_Utils_Array::value('data_type', $tree['fields'][$customFieldDetails[0]]) == 'Date') {
                                     $skipValue = TRUE;
                                     // CRM-6681, $default contains formatted date, time values.
                                     $defaults[$fldName] = $customValue;
                                     if (!empty($defaults[$customKey . '_time'])) {
                                         $defaults['field'][$componentId][$name . '_time'] = $defaults[$customKey . '_time'];
                                     }
                                 }
                             }
                         }
                         if (!$skipValue || $isStandalone) {
                             $defaults[$fldName] = $customValue;
                         }
                         unset($defaults[$customKey]);
                         break;
                     }
                 }
             }
         }
     }
 }