/** * Based on input, create participant row for transferee and send email * * return @ void */ public function participantTransfer($participant) { $contactDetails = array(); $contactIds[] = $participant->contact_id; list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant'); foreach ($currentContactDetails as $contactId => $contactValues) { $contactDetails[$contactId] = $contactValues; } $participantRoles = CRM_Event_PseudoConstant::participantRole(); $participantDetails = array(); $query = "SELECT * FROM civicrm_participant WHERE id = " . $participant->id; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id); } $domainValues = array(); if (empty($domainValues)) { $domain = CRM_Core_BAO_Domain::getDomain(); $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens()); foreach ($tokens['domain'] as $token) { $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain); } } $eventDetails = array(); $eventParams = array('id' => $participant->event_id); CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails); //get default participant role. $eventDetails['participant_role'] = CRM_Utils_Array::value($eventDetails['default_role_id'], $participantRoles); //get the location info $locParams = array('entity_id' => $participant->event_id, 'entity_table' => 'civicrm_event'); $eventDetails['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE); $toEmail = CRM_Utils_Array::value('email', $contactDetails[$participant->contact_id]); if ($toEmail) { //take a receipt from as event else domain. $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>'; if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) { $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>'; } $participantName = $contactDetails[$participant->contact_id]['display_name']; $tplParams = array('event' => $eventDetails, 'participant' => $participantDetails[$participant->id], 'participantID' => $participant->id, 'participant_status' => 'Registered'); $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_online_receipt', 'contactId' => $participantDetails[$participant->id]['contact_id'], 'tplParams' => $tplParams, 'from' => $receiptFrom, 'toName' => $participantName, 'toEmail' => $toEmail, 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails), 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails)); CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } }
/** * Send email receipt. * * @param CRM_Core_Form $form * Form object. * @param array $formValues * @param object $membership * Object. * * @return bool * true if mail was sent successfully */ public static function emailReceipt(&$form, &$formValues, &$membership) { // retrieve 'from email id' for acknowledgement $receiptFrom = $formValues['from_email_address']; if (!empty($formValues['payment_instrument_id'])) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']]; } // retrieve custom data $customFields = $customValues = array(); if (property_exists($form, '_groupTree') && !empty($form->_groupTree)) { foreach ($form->_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', '=', $membership->id, 0, 0)); // check whether its a test drive if ($form->_mode == 'test') { $members[] = array('member_test', '=', 1, 0, 0); } CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members); if ($form->_mode) { if (!empty($form->_params['billing_first_name'])) { $name = $form->_params['billing_first_name']; } if (!empty($form->_params['billing_middle_name'])) { $name .= " {$form->_params['billing_middle_name']}"; } if (!empty($form->_params['billing_last_name'])) { $name .= " {$form->_params['billing_last_name']}"; } $form->assign('billingName', $name); // assign the address formatted up for display $addressParts = array("street_address-{$form->_bltID}", "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "state_province-{$form->_bltID}", "country-{$form->_bltID}"); $addressFields = array(); foreach ($addressParts as $part) { list($n, $id) = explode('-', $part); if (isset($form->_params['billing_' . $part])) { $addressFields[$n] = $form->_params['billing_' . $part]; } } $form->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $form->assign('credit_card_exp_date', $date); $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number'])); $form->assign('credit_card_type', $form->_params['credit_card_type']); $form->assign('contributeMode', 'direct'); $form->assign('isAmountzero', 0); $form->assign('is_pay_later', 0); $form->assign('isPrimary', 1); } $form->assign('module', 'Membership'); $form->assign('contactID', $formValues['contact_id']); $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues))); if (!empty($formValues['contribution_id'])) { $form->assign('contributionID', $formValues['contribution_id']); } elseif (isset($form->_onlinePendingContributionId)) { $form->assign('contributionID', $form->_onlinePendingContributionId); } if (!empty($formValues['contribution_status_id'])) { $form->assign('contributionStatusID', $formValues['contribution_status_id']); $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name')); } if (!empty($formValues['is_renew'])) { $form->assign('receiptType', 'membership renewal'); } else { $form->assign('receiptType', 'membership signup'); } $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues))); $form->assign('formValues', $formValues); if (empty($lineItem)) { $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y')); if (!CRM_Utils_System::isNull($membership->end_date)) { $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y')); } $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)); } $form->assign('customValues', $customValues); $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry'); if (empty($form->_contributorDisplayName) || empty($form->_contributorEmail) || $isBatchProcess) { // in this case the form is being called statically from the batch editing screen // having one class in the form layer call another statically is not greate // & we should aim to move this function to the BAO layer in future. // however, we can assume that the contact_id passed in by the batch // function will be the recipient list($form->_contributorDisplayName, $form->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']); if (empty($form->_receiptContactId) || $isBatchProcess) { $form->_receiptContactId = $formValues['contact_id']; } } $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $eventTaxAmt = $template->get_template_vars('totalTaxAmount'); $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $isEmailPdf = TRUE; } else { $isEmailPdf = FALSE; } list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $form->_receiptContactId, 'from' => $receiptFrom, 'toName' => $form->_contributorDisplayName, 'toEmail' => $form->_contributorEmail, 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf, 'contributionId' => $formValues['contribution_id'], 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW))); return TRUE; }
/** * Function that sends e-mail copy of activity * * @param $clientId * @param int $activityId activity Id * @param array $contacts array of related contact * * @param null $attachments * @param $caseId * * @return void * @access public */ static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) { if (!$activityId) { return; } $tplParams = $activityInfo = array(); //if its a case activity if ($caseId) { $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id'); $nonCaseActivityTypes = CRM_Core_PseudoConstant::activityType(); if (!empty($nonCaseActivityTypes[$activityTypeId])) { $anyActivity = TRUE; } else { $anyActivity = FALSE; } $tplParams['isCaseActivity'] = 1; $tplParams['client_id'] = $clientId; } else { $anyActivity = TRUE; } $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process(); $isRedact = $xmlProcessorProcess->getRedactActivityEmail(); $xmlProcessorReport = new CRM_Case_XMLProcessor_Report(); $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact); if ($caseId) { $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId); } $tplParams['activity'] = $activityInfo; foreach ($tplParams['activity']['fields'] as $k => $val) { if (CRM_Utils_Array::value('label', $val) == ts('Subject')) { $activitySubject = $val['value']; break; } } $session = CRM_Core_Session::singleton(); // CRM-8926 If user is not logged in, use the activity creator as userID if (!($userID = $session->get('userID'))) { $userID = CRM_Activity_BAO_Activity::getSourceContactID($activityId); } //also create activities simultaneously of this copy. $activityParams = array(); $activityParams['source_record_id'] = $activityId; $activityParams['source_contact_id'] = $userID; $activityParams['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name'); $activityParams['activity_date_time'] = date('YmdHis'); $activityParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'); $activityParams['medium_id'] = CRM_Core_OptionGroup::getValue('encounter_medium', 'email', 'name'); $activityParams['case_id'] = $caseId; $activityParams['is_auto'] = 0; $activityParams['target_id'] = $clientId; $tplParams['activitySubject'] = $activitySubject; // if it’s a case activity, add hashed id to the template (CRM-5916) if ($caseId) { $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY . $caseId), 0, 7); } $result = array(); list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); $receiptFrom = "{$name} <{$address}>"; $recordedActivityParams = array(); foreach ($contacts as $mail => $info) { $tplParams['contact'] = $info; self::buildPermissionLinks($tplParams, $activityParams); $displayName = CRM_Utils_Array::value('display_name', $info); list($result[CRM_Utils_Array::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_case', 'valueName' => 'case_activity', 'contactId' => CRM_Utils_Array::value('contact_id', $info), 'tplParams' => $tplParams, 'from' => $receiptFrom, 'toName' => $displayName, 'toEmail' => $mail, 'attachments' => $attachments)); $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName; $activityParams['details'] = $message; if (!empty($result[$info['contact_id']])) { /* * Really only need to record one activity with all the targets combined. * Originally the template was going to possibly have different content, e.g. depending on permissions, * but it's always the same content at the moment. */ if (empty($recordedActivityParams)) { $recordedActivityParams = $activityParams; } else { $recordedActivityParams['subject'] .= "; {$displayName}"; } $recordedActivityParams['target_contact_id'][] = $info['contact_id']; } else { unset($result[CRM_Utils_Array::value('contact_id', $info)]); } } if (!empty($recordedActivityParams)) { $activity = CRM_Activity_BAO_Activity::create($recordedActivityParams); //create case_activity record if its case activity. if ($caseId) { $caseParams = array('activity_id' => $activity->id, 'case_id' => $caseId); self::processCaseActivity($caseParams); } } return $result; }
/** * Function used to send notification mail to pcp owner. * * This is used by contribution and also event PCPs. * * @param object $contribution * @param object $contributionSoft * Contribution object. */ public static function pcpNotifyOwner($contribution, $contributionSoft) { $params = array('id' => $contributionSoft->pcp_id); CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo); $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id'); if ($ownerNotifyID != CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'no_notifications', 'name') && ($ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name') && CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id, 'is_notify') || $ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'all_owners', 'name'))) { $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$contributionSoft->pcp_id}", TRUE, NULL, FALSE, TRUE); // set email in the template here if (CRM_Core_BAO_LocationType::getBilling()) { list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id, FALSE, CRM_Core_BAO_LocationType::getBilling()); } // get primary location email if no email exist( for billing location). if (!$email) { list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id); } list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft->contact_id); $tplParams = array('page_title' => $pcpInfo['title'], 'receive_date' => $contribution->receive_date, 'total_amount' => $contributionSoft->amount, 'donors_display_name' => $donorName, 'donors_email' => $email, 'pcpInfoURL' => $pcpInfoURL, 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll, 'currency' => $contributionSoft->currency); $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_owner_notify', 'contactId' => $contributionSoft->contact_id, 'toEmail' => $ownerEmail, 'toName' => $ownerName, 'from' => "{$domainValues['0']} <{$domainValues['1']}>", 'tplParams' => $tplParams, 'PDFFilename' => 'receipt.pdf'); CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } }
/** * Process that send tell a friend e-mails * * @param int $contactID * @param array $values * * @return void */ public static function sendMail($contactID, &$values) { list($fromName, $email) = CRM_Contact_BAO_Contact::getContactDetails($contactID); // if no $fromName (only email collected from originating contact) - list returns single space if (trim($fromName) == '') { $fromName = $email; } // use contact email, CRM-4963 if (empty($values['email_from'])) { $values['email_from'] = $email; } foreach ($values['email'] as $displayName => $emailTo) { if ($emailTo) { // FIXME: factor the below out of the foreach loop CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_friend', 'valueName' => 'friend', 'contactId' => $contactID, 'tplParams' => array($values['module'] => $values['module'], 'senderContactName' => $fromName, 'title' => $values['title'], 'generalLink' => $values['general_link'], 'pageURL' => $values['page_url'], 'senderMessage' => $values['message']), 'from' => "{$fromName} (via {$values['domain']}) <{$values['email_from']}>", 'toName' => $displayName, 'toEmail' => $emailTo, 'replyTo' => $email)); } } }
/** * Process that send e-mails * * @return void * @access public */ static function sendMail($contactID, &$values, $isTest = FALSE, $returnMessageText = FALSE) { //TODO:: check if from email address is entered $config = CRM_Booking_BAO_BookingConfig::getConfig(); $template = CRM_Core_Smarty::singleton(); list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID); //send email only when email is present if ($email) { $bookingId = $values['booking_id']; //get latest booking status $params = array('id' => $bookingId); $bookingLatest = civicrm_api3('Booking', 'get', $params); $bookingStatusValueItems = CRM_Booking_BAO_Booking::buildOptions('status_id', 'create'); //get booking status option values $bookingLatestStatus = $bookingStatusValueItems[$bookingLatest['values'][$bookingId]['status_id']]; //get booking detail $bookingDetail = CRM_Booking_BAO_Booking::getBookingDetails($values['booking_id']); $slots = CRM_Utils_Array::value('slots', $bookingDetail); $subSlots = CRM_Utils_Array::value('sub_slots', $bookingDetail); $adhocCharges = CRM_Utils_Array::value('adhoc_charges', $bookingDetail); $cancellationCharges = CRM_Utils_Array::value('cancellation_charges', $bookingDetail); //get contacts associating with booking $contactIds = array(); $contactIds['primary_contact'] = CRM_Utils_Array::value('primary_contact_id', $values); $contactIds['secondary_contact'] = CRM_Utils_Array::value('secondary_contact_id', $values); $contactsDetail = array(); foreach (array_filter($contactIds) as $k => $contactIdItem) { //get contact detail $contactDetail = array(); $params = array('contact_id' => $contactIdItem); $contactDetailResult = civicrm_api3('Contact', 'get', $params); $contactValues = CRM_Utils_Array::value($contactDetailResult['id'], $contactDetailResult['values']); foreach ($contactValues as $key => $contactItem) { $contactDetail[$key] = $contactItem; } $contactsDetail[$k] = $contactDetail; } //get Price elements(Subtotal, Discount, Total) $booking_amount = CRM_Booking_BAO_Booking::getBookingAmount($values['booking_id']); //get date booking made $dateBookingMade = new DateTime($values['booking_date']); $tplParams = array('email' => $email, 'today_date' => date('d.m.Y'), 'receipt_header_message' => $values['receipt_header_message'], 'receipt_footer_message' => $values['receipt_footer_message'], 'booking_id' => $bookingId, 'booking_title' => $values['booking_title'], 'booking_status' => $bookingLatestStatus, 'booking_date_made' => $values['booking_date'], 'booking_start_date' => $values['booking_start_date'], 'booking_end_date' => $values['booking_end_date'], 'booking_event_day' => $dateBookingMade->format('l'), 'booking_subtotal' => number_format($booking_amount['total_amount'] + $booking_amount['discount_amount'], 2, '.', ''), 'booking_total' => number_format($booking_amount['total_amount'], 2, '.', ''), 'booking_discount' => number_format($booking_amount['discount_amount'], 2, '.', ''), 'participants_estimate' => $values['participants_estimate'], 'participants_actual' => $values['participants_actual'], 'contacts' => $contactsDetail, 'slots' => $slots, 'sub_slots' => $subSlots, 'adhoc_charges' => $adhocCharges, 'cancellation_charges' => $cancellationCharges); $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_booking', 'valueName' => 'booking_offline_receipt', 'contactId' => $contactID, 'isTest' => $isTest, 'tplParams' => $tplParams, 'PDFFilename' => 'bookingReceipt.pdf'); //get include payment check box //if(CRM_Utils_Array::value('include_payment_info', $values)){ if (CRM_Utils_Array::value('contribution', $bookingDetail)) { //get contribution record $contribution = array(); $contributionResult = CRM_Utils_Array::value('contribution', $bookingDetail); foreach ($contributionResult as $kx => $ctbItem) { $contribution = $ctbItem; } $sendTemplateParams['tplParams']['contribution'] = $contribution; //calculate Amount outstanding $sendTemplateParams['tplParams']['amount_outstanding'] = number_format($booking_amount['total_amount'] - $contribution['total_amount'], 2, '.', ''); } //TODO:: add line item tpl params if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) { $sendTemplateParams['tplParams']['lineItem'] = $lineItem; } $sendTemplateParams['from'] = $values['from_email_address']; $sendTemplateParams['toName'] = $displayName; $sendTemplateParams['toEmail'] = $email; //$sendTemplateParams['autoSubmitted'] = TRUE; $cc = CRM_Utils_Array::value('cc_email_address', $config); if ($cc) { $sendTemplateParams['cc'] = $cc; } $bcc = CRM_Utils_Array::value('bcc_email_address', $config); if ($bcc) { $sendTemplateParams['bcc'] = $bcc; } list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); if ($sent && CRM_Utils_Array::value('log_confirmation_email', $config)) { //check log_email_confirmaiton $session =& CRM_Core_Session::singleton(); $userId = $session->get('userID'); // which is contact id of the user //create activity for sending email $params = array('option_group_name' => 'activity_type', 'name' => CRM_Booking_Utils_Constants::ACTIVITY_TYPE_SEND_EMAIL); $optionValue = civicrm_api3('OptionValue', 'get', $params); $activityTypeId = $optionValue['values'][$optionValue['id']]['value']; $params = array('source_contact_id' => $userId, 'activity_type_id' => $activityTypeId, 'subject' => ts('Send Booking Confirmation Email'), 'activity_date_time' => date('YmdHis'), 'target_contact_id' => $contactID, 'details' => $message, 'status_id' => 2, 'priority_id' => 2); $result = civicrm_api3('Activity', 'create', $params); } if ($returnMessageText) { return array('subject' => $subject, 'body' => $message, 'to' => $displayName, 'html' => $html); } } }
/** * takes an associative array and sends a thank you or email verification email * * @param array $params (reference ) an assoc array of name/value pairs * * @param $sendEmailMode * * @throws Exception * @return void @access public * @static */ public static function sendEmail($params, $sendEmailMode) { /* sendEmailMode * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK * connected user via login/pwd - thank you * or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you * or login using fb connect - thank you + click to add msg to fb wall * * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM * send a confirmation request email */ // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it $petitionGroupName = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'petition_contacts', NULL, 'Petition Contacts'); $dao = new CRM_Contact_DAO_Group(); $dao->title = $petitionGroupName; if (!$dao->find(TRUE)) { $dao->is_active = 1; $dao->visibility = 'User and User Admin Only'; $dao->save(); } $group_id = $dao->id; // get petition info $petitionParams['id'] = $params['sid']; $petitionInfo = array(); CRM_Campaign_BAO_Survey::retrieve($petitionParams, $petitionInfo); if (empty($petitionInfo)) { CRM_Core_Error::fatal('Petition doesn\'t exist.'); } //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $toName = CRM_Contact_BAO_Contact::displayName($params['contactId']); $replyTo = "do-not-reply@{$emailDomain}"; // set additional general message template params (custom tokens to use in email msg templates) // tokens then available in msg template as {$petition.title}, etc $petitionTokens['title'] = $petitionInfo['title']; $petitionTokens['petitionId'] = $params['sid']; $tplParams['petition'] = $petitionTokens; switch ($sendEmailMode) { case CRM_Campaign_Form_Petition_Signature::EMAIL_THANK: // add this contact to the CIVICRM_PETITION_CONTACTS group // Cannot pass parameter 1 by reference $p = array($params['contactId']); CRM_Contact_BAO_GroupContact::addContactsToGroup($p, $group_id, 'API'); if ($params['email-Primary']) { CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_sign', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'])); } break; case CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM: // create mailing event subscription record for this contact // this will allow using a hash key to confirm email address by sending a url link $se = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $params['email-Primary'], $params['contactId'], 'profile'); // require_once 'CRM/Core/BAO/Domain.php'; // $domain = CRM_Core_BAO_Domain::getDomain(); $config = CRM_Core_Config::singleton(); $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart(); $replyTo = implode($config->verpSeparator, array($localpart . 'c', $se->contact_id, $se->id, $se->hash)) . "@{$emailDomain}"; $confirmUrl = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE); $confirmUrlPlainText = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE, NULL, FALSE); // set email specific message template params and assign to tplParams $petitionTokens['confirmUrl'] = $confirmUrl; $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText; $tplParams['petition'] = $petitionTokens; if ($params['email-Primary']) { CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_confirmation_needed', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'], 'confirmUrl' => $confirmUrl)); } break; } }
/** * @param $events_in_cart * @param array $params */ public function emailReceipt($events_in_cart, $params) { $contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id); $state_province = new CRM_Core_DAO_StateProvince(); $state_province->id = $params["billing_state_province_id-{$this->_bltID}"]; $state_province->find(); $state_province->fetch(); $country = new CRM_Core_DAO_Country(); $country->id = $params["billing_country_id-{$this->_bltID}"]; $country->find(); $country->fetch(); foreach ($this->line_items as &$line_item) { $location_params = array('entity_id' => $line_item['event']->id, 'entity_table' => 'civicrm_event'); $line_item['location'] = CRM_Core_BAO_Location::getValues($location_params, TRUE); CRM_Core_BAO_Address::fixAddress($line_item['location']['address'][1]); } $send_template_params = array('table' => 'civicrm_msg_template', 'contactId' => $this->payer_contact_id, 'from' => $this->getDefaultFrom(), 'groupName' => 'msg_tpl_workflow_event', 'isTest' => FALSE, 'toEmail' => $contact_details[1], 'toName' => $contact_details[0], 'tplParams' => array('billing_name' => "{$params['billing_first_name']} {$params['billing_last_name']}", 'billing_city' => $params["billing_city-{$this->_bltID}"], 'billing_country' => $country->name, 'billing_postal_code' => $params["billing_postal_code-{$this->_bltID}"], 'billing_state' => $state_province->abbreviation, 'billing_street_address' => $params["billing_street_address-{$this->_bltID}"], 'credit_card_exp_date' => $params['credit_card_exp_date'], 'credit_card_type' => $params['credit_card_type'], 'credit_card_number' => "************" . substr($params['credit_card_number'], -4, 4), 'discounts' => $this->discounts, 'email' => $contact_details[1], 'events_in_cart' => $events_in_cart, 'line_items' => $this->line_items, 'name' => $contact_details[0], 'transaction_id' => $params['trxn_id'], 'transaction_date' => $params['trxn_date'], 'is_pay_later' => $this->is_pay_later, 'pay_later_receipt' => $this->pay_later_receipt), 'valueName' => 'event_registration_receipt', 'PDFFilename' => ts('confirmation') . '.pdf'); $template_params_to_copy = array('billing_name', 'billing_city', 'billing_country', 'billing_postal_code', 'billing_state', 'billing_street_address', 'credit_card_exp_date', 'credit_card_type', 'credit_card_number'); foreach ($template_params_to_copy as $template_param_to_copy) { $this->set($template_param_to_copy, $send_template_params['tplParams'][$template_param_to_copy]); } CRM_Core_BAO_MessageTemplate::sendTemplate($send_template_params); }
/** * Send email receipt. * * @param CRM_Core_Form $form * instance of Contribution form. * @param array $params * (reference ) an assoc array of name/value pairs. * @param bool $ccContribution * is it credit card contribution. * * @return array */ public static function emailReceipt(&$form, &$params, $ccContribution = FALSE) { $form->assign('receiptType', 'contribution'); // Retrieve Financial Type Name from financial_type_id $params['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $params['financial_type_id']); if (!empty($params['payment_instrument_id'])) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $params['paidBy'] = $paymentInstrument[$params['payment_instrument_id']]; if ($params['paidBy'] != 'Check' && isset($params['check_number'])) { unset($params['check_number']); } } // retrieve individual prefix value for honoree if (isset($params['soft_credit'])) { $softCreditTypes = $softCredits = array(); foreach ($params['soft_credit'] as $key => $softCredit) { $softCredits[$key] = array('Name' => $softCredit['contact_name'], 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency'])); $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; } $form->assign('softCreditTypes', $softCreditTypes); $form->assign('softCredits', $softCredits); } // retrieve premium product name and assigned fulfilled // date to template if (!empty($params['hidden_Premium'])) { if (isset($params['product_name']) && is_array($params['product_name']) && !empty($params['product_name'])) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $params['product_name'][0]; $productOptionID = $params['product_name'][1]; $productDAO->find(TRUE); $params['product_name'] = $productDAO->name; $params['product_sku'] = $productDAO->sku; if (empty($params['product_option']) && !empty($form->_options[$productDAO->id])) { $params['product_option'] = $form->_options[$productDAO->id][$productOptionID]; } } if (!empty($params['fulfilled_date'])) { $form->assign('fulfilled_date', CRM_Utils_Date::processDate($params['fulfilled_date'])); } } $form->assign('ccContribution', $ccContribution); if ($ccContribution) { //build the name. $name = CRM_Utils_Array::value('billing_first_name', $params); if (!empty($params['billing_middle_name'])) { $name .= " {$params['billing_middle_name']}"; } $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $params); $name = trim($name); $form->assign('billingName', $name); //assign the address formatted up for display $addressParts = array("street_address" => "billing_street_address-{$form->_bltID}", "city" => "billing_city-{$form->_bltID}", "postal_code" => "billing_postal_code-{$form->_bltID}", "state_province" => "state_province-{$form->_bltID}", "country" => "country-{$form->_bltID}"); $addressFields = array(); foreach ($addressParts as $name => $field) { $addressFields[$name] = CRM_Utils_Array::value($field, $params); } $form->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $form->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params)); $form->assign('credit_card_exp_date', $date); $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number'])); } else { //offline contribution // assigned various dates to the templates $form->assign('receipt_date', CRM_Utils_Date::processDate($params['receipt_date'])); if (!empty($params['cancel_date'])) { $form->assign('cancel_date', CRM_Utils_Date::processDate($params['cancel_date'])); } if (!empty($params['thankyou_date'])) { $form->assign('thankyou_date', CRM_Utils_Date::processDate($params['thankyou_date'])); } if ($form->_action & CRM_Core_Action::UPDATE) { $form->assign('lineItem', empty($form->_lineItems) ? FALSE : $form->_lineItems); } } //handle custom data if (!empty($params['hidden_custom'])) { $contribParams = array(array('contribution_id', '=', $params['contribution_id'], 0, 0)); if ($form->_mode == 'test') { $contribParams[] = array('contribution_test', '=', 1, 0, 0); } //retrieve custom data $customGroup = array(); foreach ($form->_groupTree as $groupID => $group) { $customFields = $customValues = array(); if ($groupID == 'info') { continue; } foreach ($group['fields'] as $k => $field) { $field['title'] = $field['label']; $customFields["custom_{$k}"] = $field; } //build the array of customgroup contain customfields. CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $contribParams); $customGroup[$group['title']] = $customValues; } //assign all custom group and corresponding fields to template. $form->assign('customGroup', $customGroup); } $form->assign_by_ref('formValues', $params); list($contributorDisplayName, $contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']); $form->assign('contactID', $params['contact_id']); $form->assign('contributionID', $params['contribution_id']); if (!empty($params['currency'])) { $form->assign('currency', $params['currency']); } if (!empty($params['receive_date'])) { $form->assign('receive_date', CRM_Utils_Date::processDate($params['receive_date'])); } $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $eventTaxAmt = $template->get_template_vars('totalTaxAmount'); $prefixValue = Civi::settings()->get('contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $isEmailPdf = TRUE; } else { $isEmailPdf = FALSE; } list($sendReceipt, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_offline_receipt', 'contactId' => $params['contact_id'], 'contributionId' => $params['contribution_id'], 'from' => $params['from_email_address'], 'toName' => $contributorDisplayName, 'toEmail' => $contributorEmail, 'isTest' => $form->_mode == 'test', 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf)); return $sendReceipt; }
/** * @todo per totten's suggestion, wrap all these writes in a transaction; * see http://wiki.civicrm.org/confluence/display/CRMDOC43/Transaction+Reference */ function postProcess() { $cid = CRM_Utils_Array::value('userID', $_SESSION['CiviCRM'], NULL); $values = $this->controller->exportValues(); $profileFields = array(); foreach ($this->getProfileIDs() as $profileID) { $profileFields += CRM_Core_BAO_UFGroup::getFields($profileID); } $profileValues = array_intersect_key($values, $profileFields); $activityValues = array_diff_key($values, $profileValues); // Search for duplicate if (!$cid) { $dedupeParams = CRM_Dedupe_Finder::formatParams($profileValues, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual'); if ($ids) { $cid = $ids[0]; } } $cid = CRM_Contact_BAO_Contact::createProfileContact($profileValues, $profileFields, $cid); $activity_statuses = CRM_Activity_BAO_Activity::buildOptions('status_id', 'create'); $projectNeeds = array(); foreach ($this->_needs as $need) { $activityValues['volunteer_need_id'] = $need['id']; $activityValues['activity_date_time'] = CRM_Utils_Array::value('start_time', $need); $activityValues['assignee_contact_id'] = $cid; $activityValues['is_test'] = $this->_mode === 'test' ? 1 : 0; // below we assume that volunteers are always signing up only themselves; // for now this is a safe assumption, but we may need to revisit this. $activityValues['source_contact_id'] = $cid; // Set status to Available if user selected Flexible Need, else set to Scheduled. if (CRM_Utils_Array::value('is_flexible', $need)) { $activityValues['status_id'] = CRM_Utils_Array::key('Available', $activity_statuses); } else { $activityValues['status_id'] = CRM_Utils_Array::key('Scheduled', $activity_statuses); } $activityValues['time_scheduled_minutes'] = CRM_Utils_Array::value('duration', $need); CRM_Volunteer_BAO_Assignment::createVolunteerActivity($activityValues); if (!array_key_exists($need['project_id'], $projectNeeds)) { $projectNeeds[$need['project_id']] = array(); } $need['role'] = $need['role_label']; $need['description'] = $need['role_description']; $need['duration'] = CRM_Utils_Array::value('duration', $need); $projectNeeds[$need['project_id']][$need['id']] = $need; } // Send confirmation email to volunteer list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($cid); list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); if ($email) { $tplParams = $this->prepareTplParams($projectNeeds); $sendTemplateParams = array('contactId' => $cid, 'from' => "{$domainEmailName} <" . $domainEmailAddress . ">", 'groupName' => 'msg_tpl_workflow_volunteer', 'isTest' => $this->_mode === 'test', 'toName' => $displayName, 'toEmail' => $email, 'tplParams' => array("volunteer_projects" => $tplParams), 'valueName' => 'volunteer_registration'); $bcc = array(); foreach ($tplParams as $data) { foreach ($data['contacts'] as $manager) { $bcc[$manager['contact_id']] = "{$manager['display_name']} <{$manager['email']}>"; } } if (count($bcc)) { $sendTemplateParams['bcc'] = implode(', ', $bcc); } CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } $statusMsg = ts('You are scheduled to volunteer. Thank you!', array('domain' => 'org.civicrm.volunteer')); CRM_Core_Session::setStatus($statusMsg, '', 'success'); CRM_Utils_System::redirect($this->_destination); }
/** * @param $params * * @return mixed */ function emailReceipt(&$params) { $updatedLineItem = CRM_Price_BAO_LineItem::getLineItems($this->_participantId, 'participant', NULL, FALSE); $lineItem = array(); if ($updatedLineItem) { $lineItem[] = $updatedLineItem; } $this->assign('lineItem', empty($lineItem) ? FALSE : $lineItem); // offline receipt sending 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 (array_keys($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', $this->contributionAmt); $this->assign('isPrimary', 1); $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params)); } $this->assign('register_date', $params['register_date']); $template = CRM_Core_Smarty::singleton(); // 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($this->_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('contactID', $this->_contactId); $this->assign('participantID', $this->_participantId); $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $this->_contactId, 'isTest' => FALSE, '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 && !$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); } list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); return $mailSent; }
/** * Version agnostic receipt sending function. * * @param array $params */ function _sendReceipt($params) { if (_versionAtLeast(4.4)) { list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($params); } else { list($sent) = CRM_Core_BAO_MessageTemplates::sendTemplate($params); } return $sent; }
/** * Process the form. * * @return void */ public function postProcess() { $params = $this->controller->exportValues($this->_name); $status = NULL; // now set the values for the billing location. foreach ($this->_fields as $name => $value) { $fields[$name] = 1; } $fields["email-{$this->_bltID}"] = 1; $processorParams = array(); foreach ($params as $key => $val) { $key = str_replace('billing_', '', $key); list($key) = explode('-', $key); $processorParams[$key] = $val; } $processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE); $processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE); $processorParams['month'] = $processorParams['credit_card_exp_date']['M']; $processorParams['year'] = $processorParams['credit_card_exp_date']['Y']; $processorParams['subscriptionId'] = $this->_subscriptionDetails->subscription_id; $processorParams['amount'] = $this->_subscriptionDetails->amount; $updateSubscription = $this->_paymentProcessorObj->updateSubscriptionBillingInfo($message, $processorParams); if (is_a($updateSubscription, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($updateSubscription); } elseif ($updateSubscription) { $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_subscriptionDetails->contact_id, 'contact_type'); $contact =& CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_subscriptionDetails->contact_id, NULL, NULL, $ctype); // build tpl params if ($this->_subscriptionDetails->membership_id) { $inputParams = array('id' => $this->_subscriptionDetails->membership_id); CRM_Member_BAO_Membership::getValues($inputParams, $tplParams); $tplParams = $tplParams[$this->_subscriptionDetails->membership_id]; $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']); $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']); $status = ts('Billing details for your automatically renewed %1 membership have been updated.', array(1 => $tplParams['membershipType'])); $msgTitle = ts('Details Updated'); $msgType = 'success'; } else { $status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.', array(1 => $this->_subscriptionDetails->amount, 2 => $this->_subscriptionDetails->frequency_interval, 3 => $this->_subscriptionDetails->frequency_unit)); $msgTitle = ts('Details Updated'); $msgType = 'success'; $tplParams = array('recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval, 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit, 'amount' => $this->_subscriptionDetails->amount); } // format new address for display $addressParts = array("street_address", "city", "postal_code", "state_province", "country"); foreach ($addressParts as $part) { $addressParts[$part] = CRM_Utils_Array::value($part, $processorParams); } $tplParams['address'] = CRM_Utils_Address::format($addressParts); // format old address to store in activity details $this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE); $this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE); $addressParts = array("street_address", "city", "postal_code", "state_province", "country"); foreach ($addressParts as $part) { $key = "{$part}-{$this->_bltID}"; $addressParts[$part] = CRM_Utils_Array::value($key, $this->_defaults); } $this->_defaults['address'] = CRM_Utils_Address::format($addressParts); // format new billing name $name = $processorParams['first_name']; if (!empty($processorParams['middle_name'])) { $name .= " {$processorParams['middle_name']}"; } $name .= ' ' . $processorParams['last_name']; $name = trim($name); $tplParams['billingName'] = $name; // format old billing name $name = $this->_defaults['first_name']; if (!empty($this->_defaults['middle_name'])) { $name .= " {$this->_defaults['middle_name']}"; } $name .= ' ' . $this->_defaults['last_name']; $name = trim($name); $this->_defaults['billingName'] = $name; $message .= "\n<br/><br/>New Billing Name and Address\n<br/>==============================\n<br/>{$tplParams['billingName']}\n<br/>{$tplParams['address']}\n\n<br/><br/>Previous Billing Name and Address\n<br/>==================================\n<br/>{$this->_defaults['billingName']}\n<br/>{$this->_defaults['address']}"; $activityParams = array('source_contact_id' => $this->_subscriptionDetails->contact_id, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Update Recurring Contribution Billing Details', 'name'), 'subject' => ts('Recurring Contribution Billing Details Updated'), 'details' => $message, 'activity_date_time' => date('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name')); $session = CRM_Core_Session::singleton(); $cid = $session->get('userID'); if ($cid) { $activityParams['target_contact_id'][] = $activityParams['source_contact_id']; $activityParams['source_contact_id'] = $cid; } CRM_Activity_BAO_Activity::create($activityParams); // send notification if ($this->_subscriptionDetails->contribution_page_id) { CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $this->_subscriptionDetails->contribution_page_id, $value, array('title', 'receipt_from_name', 'receipt_from_email')); $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>'; } else { $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>"; } list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id); $tplParams['contact'] = array('display_name' => $donorDisplayName); $date = CRM_Utils_Date::format($processorParams['credit_card_exp_date']); $tplParams['credit_card_exp_date'] = CRM_Utils_Date::mysqlToIso($date); $tplParams['credit_card_number'] = CRM_Utils_System::mungeCreditCard($processorParams['credit_card_number']); $tplParams['credit_card_type'] = $processorParams['credit_card_type']; $sendTemplateParams = array('groupName' => $this->_subscriptionDetails->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution', 'valueName' => $this->_subscriptionDetails->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing', 'contactId' => $this->_subscriptionDetails->contact_id, 'tplParams' => $tplParams, 'isTest' => $this->_subscriptionDetails->is_test, 'PDFFilename' => 'receipt.pdf', 'from' => $receiptFrom, 'toName' => $donorDisplayName, 'toEmail' => $donorEmail); list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } else { $status = ts('There was some problem updating the billing details.'); $msgTitle = ts('Update Error'); $msgType = 'error'; } $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); if ($userID && $status) { $session->setStatus($status, $msgTitle, $msgType); } elseif (!$userID) { if ($status) { CRM_Utils_System::setUFMessage($status); } $result = (int) ($updateSubscription && isset($ctype)); if (isset($tplParams)) { $session->set('resultParams', $tplParams); } return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus', "reset=1&task=billing&result={$result}")); } }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { $status = $message = NULL; $cancelSubscription = TRUE; $params = $this->controller->exportValues($this->_name); if ($this->_selfService) { // for self service force sending-request & notify if ($this->_paymentProcessorObj->isSupported('cancelSubscription')) { $params['send_cancel_request'] = 1; } if ($this->_donorEmail) { $params['is_notify'] = 1; } } if (CRM_Utils_Array::value('send_cancel_request', $params) == 1) { $cancelParams = array('subscriptionId' => $this->_subscriptionDetails->subscription_id); $cancelSubscription = $this->_paymentProcessorObj->cancelSubscription($message, $cancelParams); } if (is_a($cancelSubscription, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($cancelSubscription); } elseif ($cancelSubscription) { $activityParams = array('subject' => $this->_mid ? ts('Auto-renewal membership cancelled') : ts('Recurring contribution cancelled'), 'details' => $message); $cancelStatus = CRM_Contribute_BAO_ContributionRecur::cancelRecurContribution($this->_subscriptionDetails->recur_id, CRM_Core_DAO::$_nullObject, $activityParams); if ($cancelStatus) { $tplParams = array(); if ($this->_mid) { $inputParams = array('id' => $this->_mid); CRM_Member_BAO_Membership::getValues($inputParams, $tplParams); $tplParams = $tplParams[$this->_mid]; $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']); $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']); $status = ts('The automatic renewal of your %1 membership has been cancelled as requested. This does not affect the status of your membership - you will receive a separate notification when your membership is up for renewal.', array(1 => $tplParams['membershipType'])); $msgTitle = 'Membership Renewal Cancelled'; $msgType = 'info'; } else { $tplParams['recur_frequency_interval'] = $this->_subscriptionDetails->frequency_interval; $tplParams['recur_frequency_unit'] = $this->_subscriptionDetails->frequency_unit; $tplParams['amount'] = $this->_subscriptionDetails->amount; $tplParams['contact'] = array('display_name' => $this->_donorDisplayName); $status = ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(1 => $this->_subscriptionDetails->amount, 2 => $this->_subscriptionDetails->frequency_interval, 3 => $this->_subscriptionDetails->frequency_unit)); $msgTitle = 'Contribution Cancelled'; $msgType = 'success'; } if (CRM_Utils_Array::value('is_notify', $params) == 1) { if ($this->_subscriptionDetails->contribution_page_id) { CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $this->_subscriptionDetails->contribution_page_id, $value, array('title', 'receipt_from_name', 'receipt_from_email')); $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>'; } else { $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>"; } // send notification $sendTemplateParams = array('groupName' => $this->_mode == 'auto_renew' ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution', 'valueName' => $this->_mode == 'auto_renew' ? 'membership_autorenew_cancelled' : 'contribution_recurring_cancelled', 'contactId' => $this->_subscriptionDetails->contact_id, 'tplParams' => $tplParams, 'PDFFilename' => 'receipt.pdf', 'from' => $receiptFrom, 'toName' => $this->_donorDisplayName, 'toEmail' => $this->_donorEmail); list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } } else { $msgType = 'error'; $msgTitle = ts('Error'); if ($params['send_cancel_request'] == 1) { $status = ts('Recurring contribution was cancelled successfully by the processor, but could not be marked as cancelled in the database.'); } else { $status = ts('Recurring contribution could not be cancelled in the database.'); } } } else { $status = ts('The recurring contribution could not be cancelled.'); $msgTitle = 'Error Cancelling Contribution'; $msgType = 'error'; } $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); if ($userID && $status) { $session->setStatus($status, $msgTitle, $msgType); } elseif (!$userID) { if ($status) { CRM_Utils_System::setUFMessage($status); } // keep result as 1, since we not displaying anything on the redirected page anyway return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus', "reset=1&task=cancel&result=1")); } }
/** * Process that send notification e-mails * * @param int $contactID * Contact id. * @param array $values * Associative array of name/value pair. */ public static function commonSendMail($contactID, &$values) { if (!$contactID || !$values) { return; } $template = CRM_Core_Smarty::singleton(); $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name'); self::profileDisplay($values['id'], $values['values'], $template); $emailList = explode(',', $values['email']); $contactLink = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contactID}", TRUE, NULL, FALSE, FALSE, TRUE); //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 » Communications » FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl))); } foreach ($emailList as $emailTo) { // FIXME: take the below out of the foreach loop CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_uf', 'valueName' => 'uf_notify', 'contactId' => $contactID, 'tplParams' => array('displayName' => $displayName, 'currentDate' => date('r'), 'contactLink' => $contactLink), 'from' => "{$domainEmailName} <{$domainEmailAddress}>", 'toEmail' => $emailTo)); } }
/** * 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'); }
/** * 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); } }
/** * Send the emails for Recurring Contribution Notication. * * @param string $type * TxnType. * @param int $contactID * Contact id for contributor. * @param int $pageID * Contribution page id. * @param object $recur * Object of recurring contribution table. * @param bool|object $autoRenewMembership is it a auto renew membership. * * @return void */ public static function recurringNotify($type, $contactID, $pageID, $recur, $autoRenewMembership = FALSE) { $value = array(); if ($pageID) { CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $pageID, $value, array('title', 'is_email_receipt', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt')); } $isEmailReceipt = CRM_Utils_Array::value('is_email_receipt', $value[$pageID]); $isOfflineRecur = FALSE; if (!$pageID && $recur->id) { $isOfflineRecur = TRUE; } if ($isEmailReceipt || $isOfflineRecur) { if ($pageID) { $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$pageID]) . '" <' . $value[$pageID]['receipt_from_email'] . '>'; $receiptFromName = $value[$pageID]['receipt_from_name']; $receiptFromEmail = $value[$pageID]['receipt_from_email']; } else { $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>"; $receiptFromName = $domainValues[0]; $receiptFromEmail = $domainValues[1]; } list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE); $templatesParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_recurring_notify', 'contactId' => $contactID, 'tplParams' => array('recur_frequency_interval' => $recur->frequency_interval, 'recur_frequency_unit' => $recur->frequency_unit, 'recur_installments' => $recur->installments, 'recur_start_date' => $recur->start_date, 'recur_end_date' => $recur->end_date, 'recur_amount' => $recur->amount, 'recur_txnType' => $type, 'displayName' => $displayName, 'receipt_from_name' => $receiptFromName, 'receipt_from_email' => $receiptFromEmail, 'auto_renew_membership' => $autoRenewMembership), 'from' => $receiptFrom, 'toName' => $displayName, 'toEmail' => $email); //CRM-13811 if ($pageID) { $templatesParams['cc'] = CRM_Utils_Array::value('cc_receipt', $value[$pageID]); $templatesParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $value[$pageID]); } if ($recur->id) { // in some cases its just recurringNotify() thats called for the first time and these urls don't get set. // like in PaypalPro, & therefore we set it here additionally. $template = CRM_Core_Smarty::singleton(); $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj'); $url = $paymentProcessor->subscriptionURL($recur->id, 'recur'); $template->assign('cancelSubscriptionUrl', $url); $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'billing'); $template->assign('updateSubscriptionBillingUrl', $url); $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'update'); $template->assign('updateSubscriptionUrl', $url); } list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams); if ($sent) { CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.'); } else { CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.'); } } }
/** * Process that send e-mails * * @param $contactID * @param $values * @param $participantId * @param bool $isTest * @param bool $returnMessageText * * @return void * @access public */ static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) { $template = CRM_Core_Smarty::singleton(); $gIds = array('custom_pre_id' => $values['custom_pre_id'], 'custom_post_id' => $values['custom_post_id']); //get the params submitted by participant. $participantParams = CRM_Utils_Array::value($participantId, $values['params'], array()); if (!$returnMessageText) { //send notification email if field values are set (CRM-1941) foreach ($gIds as $key => $gIdValues) { if ($gIdValues) { if (!is_array($gIdValues)) { $gIdValues = array($gIdValues); } foreach ($gIdValues as $gId) { $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify'); if ($email) { //get values of corresponding profile fields for notification list($profileValues) = self::buildCustomDisplay($gId, NULL, $contactID, $template, $participantId, $isTest, TRUE, $participantParams); list($profileValues) = $profileValues; $val = array('id' => $gId, 'values' => $profileValues, 'email' => $email); CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val); } } } } } if ($values['event']['is_email_confirm'] || $returnMessageText) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID); //send email only when email is present if (isset($email) || $returnMessageText) { $preProfileID = CRM_Utils_Array::value('custom_pre_id', $values); $postProfileID = CRM_Utils_Array::value('custom_post_id', $values); if (!empty($values['params']['additionalParticipant'])) { $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values, $preProfileID); $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values, $postProfileID); } self::buildCustomDisplay($preProfileID, 'customPre', $contactID, $template, $participantId, $isTest, NULL, $participantParams); self::buildCustomDisplay($postProfileID, 'customPost', $contactID, $template, $participantId, $isTest, NULL, $participantParams); $sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId); $tplParams = array_merge($values, $participantParams, array('email' => $email, 'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $values['event']), 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $values['event']), 'contributeMode' => CRM_Utils_Array::value('contributeMode', $template->_tpl_vars), 'participantID' => $participantId, 'conference_sessions' => $sessions, 'credit_card_number' => CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $participantParams)), 'credit_card_exp_date' => CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $participantParams))))); // CRM-13890 : NOTE wait list condition need to be given so that // wait list message is shown properly in email i.e. WRT online event registration template if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) { $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id'); $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($statusId, NULL, 'label'); } $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_online_receipt', 'contactId' => $contactID, 'isTest' => $isTest, 'tplParams' => $tplParams, 'PDFFilename' => ts('confirmation') . '.pdf'); // address required during receipt processing (pdf and email receipt) if ($displayAddress = CRM_Utils_Array::value('address', $values)) { $sendTemplateParams['tplParams']['address'] = $displayAddress; $sendTemplateParams['tplParams']['contributeMode'] = NULL; } // set lineItem details if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) { // check if additional prticipant, if so filter only to relevant ones // CRM-9902 if (!empty($values['params']['additionalParticipant'])) { $ownLineItems = array(); foreach ($lineItem as $liKey => $liValue) { $firstElement = array_pop($liValue); if ($firstElement['entity_id'] == $participantId) { $ownLineItems[0] = $lineItem[$liKey]; break; } } if (!empty($ownLineItems)) { $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems; } } else { $sendTemplateParams['tplParams']['lineItem'] = $lineItem; } } if ($returnMessageText) { list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); return array('subject' => $subject, 'body' => $message, 'to' => $displayName, 'html' => $html); } else { $sendTemplateParams['from'] = CRM_Utils_Array::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array::value('confirm_from_email', $values['event']) . ">"; $sendTemplateParams['toName'] = $displayName; $sendTemplateParams['toEmail'] = $email; $sendTemplateParams['autoSubmitted'] = TRUE; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values['event']); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values['event']); CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } } } }
/** * called after the user submits the form. * * * @return void */ public function postProcess() { // store the submitted values in an array $params = $this->exportValues(); if ($this->_selfService && $this->_donorEmail) { // for self service force notify $params['is_notify'] = 1; } // if this is an update of an existing recurring contribution, pass the ID $params['id'] = $this->_subscriptionDetails->recur_id; $message = ''; $params['subscriptionId'] = $this->_subscriptionDetails->subscription_id; $updateSubscription = TRUE; if ($this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) { $updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params); } if (is_a($updateSubscription, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($updateSubscription); $status = ts('Could not update the Recurring contribution details'); $msgTitle = ts('Update Error'); $msgType = 'error'; } elseif ($updateSubscription) { // save the changes $result = CRM_Contribute_BAO_ContributionRecur::add($params); $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.', array(1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency), 2 => $this->_subscriptionDetails->frequency_interval, 3 => $this->_subscriptionDetails->frequency_unit, 4 => $params['installments'])); $msgTitle = ts('Update Success'); $msgType = 'success'; $contactID = $this->_subscriptionDetails->contact_id; if ($this->_subscriptionDetails->amount != $params['amount']) { $message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.", array(1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency), 2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency))) . ' '; } if ($this->_subscriptionDetails->installments != $params['installments']) { $message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", array(1 => $this->_subscriptionDetails->installments, 2 => $params['installments'])) . ' '; } $activityParams = array('source_contact_id' => $contactID, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Update Recurring Contribution', 'name'), 'subject' => ts('Recurring Contribution Updated'), 'details' => $message, 'activity_date_time' => date('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name')); $session = CRM_Core_Session::singleton(); $cid = $session->get('userID'); if ($cid) { $activityParams['target_contact_id'][] = $activityParams['source_contact_id']; $activityParams['source_contact_id'] = $cid; } CRM_Activity_BAO_Activity::create($activityParams); if (!empty($params['is_notify'])) { // send notification if ($this->_subscriptionDetails->contribution_page_id) { CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $this->_subscriptionDetails->contribution_page_id, $value, array('title', 'receipt_from_name', 'receipt_from_email')); $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>'; } else { $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>"; } list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID); $tplParams = array('recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval, 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit, 'amount' => CRM_Utils_Money::format($params['amount']), 'installments' => $params['installments']); $tplParams['contact'] = array('display_name' => $donorDisplayName); $tplParams['receipt_from_email'] = $receiptFrom; $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_recurring_edit', 'contactId' => $contactID, 'tplParams' => $tplParams, 'isTest' => $this->_subscriptionDetails->is_test, 'PDFFilename' => 'receipt.pdf', 'from' => $receiptFrom, 'toName' => $donorDisplayName, 'toEmail' => $donorEmail); list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } } $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); if ($userID && $status) { CRM_Core_Session::setStatus($status, $msgTitle, $msgType); } elseif (!$userID) { if ($status) { CRM_Utils_System::setUFMessage($status); } // keep result as 1, since we not displaying anything on the redirected page anyway return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus', "reset=1&task=update&result=1")); } }
/** * Sends a template. * * @param array $params */ function civicrm_api3_message_template_send($params) { // Change external param names to internal ones $fieldSpec = array(); _civicrm_api3_message_template_send_spec($fieldSpec); foreach ($fieldSpec as $field => $spec) { if (isset($spec['api.aliases']) && array_key_exists($field, $params)) { $params[CRM_Utils_Array::first($spec['api.aliases'])] = $params[$field]; unset($params[$field]); } } if (empty($params['messageTemplateID'])) { if (empty($params['groupName']) || empty($params['valueName'])) { // Can't use civicrm_api3_verify_mandatory for this because it would give the wrong field names throw new API_Exception("Mandatory key(s) missing from params array: requires id or option_group_name + option_value_name", "mandatory_missing", array("fields" => array('id', 'option_group_name', 'option_value_name'))); } } CRM_Core_BAO_MessageTemplate::sendTemplate($params); }
/** * @param array $params * * @return mixed */ public function emailReceipt(&$params) { // email receipt sending // send message template if ($this->_component == 'event') { $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id'); $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title'); CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventId, $events, $returnProperties); $event = $events[$eventId]; unset($event['start_date']); unset($event['end_date']); $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' => $eventId, 'entity_table' => 'civicrm_event'); $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE); $this->assign('location', $location); } } // assign payment info here $paymentConfig['confirm_email_text'] = CRM_Utils_Array::value('confirm_email_text', $params); $this->assign('paymentConfig', $paymentConfig); $isRefund = $this->_paymentType == 'refund' ? TRUE : FALSE; $this->assign('isRefund', $isRefund); if ($isRefund) { $this->assign('totalPaid', $this->_amtPaid); $this->assign('totalAmount', $this->_amtTotal); $this->assign('refundAmount', $params['total_amount']); } else { $balance = $this->_amtTotal - ($this->_amtPaid + $params['total_amount']); $paymentsComplete = $balance == 0 ? 1 : 0; $this->assign('amountOwed', $balance); $this->assign('totalAmount', $this->_amtTotal); $this->assign('paymentAmount', $params['total_amount']); $this->assign('paymentsComplete', $paymentsComplete); } $this->assign('contactDisplayName', $this->_contributorDisplayName); // assign trxn details $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $params)); $this->assign('receive_date', CRM_Utils_Array::value('trxn_date', $params)); $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); if (array_key_exists('payment_instrument_id', $params)) { $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument)); } $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params)); $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'payment_or_refund_notification', 'contactId' => $this->_contactId, 'PDFFilename' => ts('notification') . '.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 && !$this->_toDoNotEmail) { if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) { $receiptFrom = $params['from_email_address']; } $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); } list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); return $mailSent; }
public static function updatePledgeStatus($params) { $returnMessages = array(); $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE); $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); //unset statues that we never use for pledges foreach (array('Completed', 'Cancelled', 'Failed') as $statusKey) { if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) { unset($allStatus[$key]); } } $statusIds = implode(',', array_keys($allStatus)); $updateCnt = 0; $query = "\nSELECT pledge.contact_id as contact_id,\n pledge.id as pledge_id,\n pledge.amount as amount,\n payment.scheduled_date as scheduled_date,\n pledge.create_date as create_date,\n payment.id as payment_id,\n pledge.currency as currency,\n pledge.contribution_page_id as contribution_page_id,\n payment.reminder_count as reminder_count,\n pledge.max_reminders as max_reminders,\n payment.reminder_date as reminder_date,\n pledge.initial_reminder_day as initial_reminder_day,\n pledge.additional_reminder_day as additional_reminder_day,\n pledge.status_id as pledge_status,\n payment.status_id as payment_status,\n pledge.is_test as is_test,\n pledge.campaign_id as campaign_id,\n SUM(payment.scheduled_amount) as amount_due,\n ( SELECT sum(civicrm_pledge_payment.actual_amount)\n FROM civicrm_pledge_payment\n WHERE civicrm_pledge_payment.status_id = 1\n AND civicrm_pledge_payment.pledge_id = pledge.id\n ) as amount_paid\n FROM civicrm_pledge pledge, civicrm_pledge_payment payment\n WHERE pledge.id = payment.pledge_id\n AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )\n GROUP By payment.id\n "; $dao = CRM_Core_DAO::executeQuery($query); $now = date('Ymd'); $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array(); while ($dao->fetch()) { $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id); $pledgeDetails[$dao->payment_id] = array('scheduled_date' => $dao->scheduled_date, 'amount_due' => $dao->amount_due, 'amount' => $dao->amount, 'amount_paid' => $dao->amount_paid, 'create_date' => $dao->create_date, 'contact_id' => $dao->contact_id, 'pledge_id' => $dao->pledge_id, 'checksumValue' => $checksumValue, 'contribution_page_id' => $dao->contribution_page_id, 'reminder_count' => $dao->reminder_count, 'max_reminders' => $dao->max_reminders, 'reminder_date' => $dao->reminder_date, 'initial_reminder_day' => $dao->initial_reminder_day, 'additional_reminder_day' => $dao->additional_reminder_day, 'pledge_status' => $dao->pledge_status, 'payment_status' => $dao->payment_status, 'is_test' => $dao->is_test, 'currency' => $dao->currency, 'campaign_id' => $dao->campaign_id); $contactIds[$dao->contact_id] = $dao->contact_id; $pledgeStatus[$dao->pledge_id] = $dao->pledge_status; if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'), $now) && $dao->payment_status != array_search('Overdue', $allStatus)) { $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id; } } // process the updating script... foreach ($pledgePayments as $pledgeId => $paymentIds) { // 1. update the pledge /pledge payment status. returns new status when an update happens $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})"; $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds, array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE); if ($newStatus != $pledgeStatus[$pledgeId]) { $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}"; $updateCnt += 1; } } if ($sendReminders) { // retrieve domain tokens $domain = CRM_Core_BAO_Domain::getDomain(); $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens()); $domainValues = array(); foreach ($tokens['domain'] as $token) { $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain); } //get the domain email address, since we don't carry w/ object. $domainValue = CRM_Core_BAO_Domain::getNameAndEmail(); $domainValues['email'] = $domainValue[1]; // retrieve contact tokens // this function does NOT return Deceased contacts since we don't want to send them email list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, $tokens, 'CRM_UpdatePledgeRecord'); // assign domain values to template $template = CRM_Core_Smarty::singleton(); $template->assign('domain', $domainValues); //set receipt from $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>'; foreach ($pledgeDetails as $paymentId => $details) { if (array_key_exists($details['contact_id'], $contactDetails)) { $contactId = $details['contact_id']; $pledgerName = $contactDetails[$contactId]['display_name']; } else { continue; } if (empty($details['reminder_date'])) { $nextReminderDate = new DateTime($details['scheduled_date']); $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day"); $nextReminderDate = $nextReminderDate->format("Ymd"); } else { $nextReminderDate = new DateTime($details['reminder_date']); $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day"); $nextReminderDate = $nextReminderDate->format("Ymd"); } if ($details['reminder_count'] < $details['max_reminders'] && $nextReminderDate <= $now) { $toEmail = $doNotEmail = $onHold = NULL; if (!empty($contactDetails[$contactId]['email'])) { $toEmail = $contactDetails[$contactId]['email']; } if (!empty($contactDetails[$contactId]['do_not_email'])) { $doNotEmail = $contactDetails[$contactId]['do_not_email']; } if (!empty($contactDetails[$contactId]['on_hold'])) { $onHold = $contactDetails[$contactId]['on_hold']; } // 2. send acknowledgement mail if ($toEmail && !($doNotEmail || $onHold)) { //assign value to template $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0); $template->assign('contact', $contactDetails[$contactId]); $template->assign('next_payment', $details['scheduled_date']); $template->assign('amount_due', $details['amount_due']); $template->assign('checksumValue', $details['checksumValue']); $template->assign('contribution_page_id', $details['contribution_page_id']); $template->assign('pledge_id', $details['pledge_id']); $template->assign('scheduled_payment_date', $details['scheduled_date']); $template->assign('amount', $details['amount']); $template->assign('create_date', $details['create_date']); $template->assign('currency', $details['currency']); list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_pledge', 'valueName' => 'pledge_reminder', 'contactId' => $contactId, 'from' => $receiptFrom, 'toName' => $pledgerName, 'toEmail' => $toEmail)); // 3. update pledge payment details if ($mailSent) { CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId); $activityType = 'Pledge Reminder'; $activityParams = array('subject' => $subject, 'source_contact_id' => $contactId, 'source_record_id' => $paymentId, 'assignee_contact_id' => $contactId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($now), 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']), 'is_test' => $details['is_test'], 'status_id' => 2, 'campaign_id' => $details['campaign_id']); if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) { $returnMessages[] = "Failed creating Activity for acknowledgment"; return array('is_error' => 1, 'message' => $returnMessages); } $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}"; } } } } // end foreach on $pledgeDetails } // end if ( $sendReminders ) $returnMessages[] = "{$updateCnt} records updated."; return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages)); }
/** * Function to send absence email * * @access public * @static */ public static function sendAbsenceMail($mailprm, $sendTemplateParams) { foreach ($mailprm as $k => $v) { $sendTemplateParams['tplParams']['displayName'] = $v['display_name']; $sendTemplateParams['toName'] = $v['display_name']; $sendTemplateParams['toEmail'] = $v['email']; list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } }
/** * 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(' ', '', $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}")); } }
/** * Process the form submission. * * * @return void */ public function postProcess() { $params = $this->controller->exportValues($this->_name); $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active', 'is_notify'); 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); //create page in wordpress create_wp_campaign($pcp->title, $pcp->contact_id, $pcp->id); CRM_Core_Error::debug_log_message("Calling create_wp_campaign.... Params title: {$pcp->title}, contact_id: {$pcp->contact_id}, pcp_id: {$pcp->id} "); // add attachments as needed CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_pcp', $pcp->id); $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 » Communications » 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')); } }
/** * Send mail and create activity * when participant status changed. * * @param int $participantId * Participant id. * @param array $participantValues * Participant detail values. status id for participants. * @param array $eventDetails * Required event details. * @param array $contactDetails * Required contact details. * @param array $domainValues * Required domain values. * @param string $mailType * (eg 'approval', 'confirm', 'expired' ). * * @return bool */ public static function sendTransitionParticipantMail($participantId, $participantValues, $eventDetails, $contactDetails, &$domainValues, $mailType) { //send emails. $mailSent = FALSE; //don't send confirmation mail to additional //since only primary able to confirm registration. if (!empty($participantValues['registered_by_id']) && $mailType == 'Confirm') { return $mailSent; } $toEmail = CRM_Utils_Array::value('email', $contactDetails); if ($toEmail) { $contactId = $participantValues['contact_id']; $participantName = $contactDetails['display_name']; //calculate the checksum value. $checksumValue = NULL; if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) { $checksumLife = 'inf'; $endDate = CRM_Utils_Array::value('end_date', $eventDetails); if ($endDate) { $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60); } $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife); } //take a receipt from as event else domain. $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>'; if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) { $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>'; } list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'participant_' . strtolower($mailType), 'contactId' => $contactId, 'tplParams' => array('contact' => $contactDetails, 'domain' => $domainValues, 'participant' => $participantValues, 'event' => $eventDetails, 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails), 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails), 'isAdditional' => $participantValues['registered_by_id'], 'isExpired' => $mailType == 'Expired', 'isConfirm' => $mailType == 'Confirm', 'checksumValue' => $checksumValue), 'from' => $receiptFrom, 'toName' => $participantName, 'toEmail' => $toEmail, 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails), 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails))); // 3. create activity record. if ($mailSent) { $now = date('YmdHis'); $activityType = 'Event Registration'; $activityParams = array('subject' => $subject, 'source_contact_id' => $contactId, 'source_record_id' => $participantId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($now), 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']), 'is_test' => $participantValues['is_test'], 'status_id' => 2); if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) { CRM_Core_Error::fatal('Failed creating Activity for expiration mail'); } } } return $mailSent; }
/** * Process form submission. * * This function is also accessed by a unit test. */ protected function submit() { $this->storeContactFields($this->_params); $this->beginPostProcess(); $now = CRM_Utils_Date::getToday(NULL, 'YmdHis'); $this->convertDateFieldsToMySQL($this->_params); $this->assign('receive_date', $this->_params['receive_date']); $this->processBillingAddress(); list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID')); $this->_params['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params, CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee')); $this->_membershipId = $this->_id; $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($this->_params, $this->_id, 'Membership'); if (empty($this->_params['financial_type_id'])) { $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id'); } $contributionRecurID = NULL; $this->assign('membershipID', $this->_id); $this->assign('contactID', $this->_contactID); $this->assign('module', 'Membership'); $this->assign('receiptType', 'membership renewal'); $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency; $this->_params['invoice_id'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE)); if (!empty($this->_params['send_receipt'])) { $this->_params['receipt_date'] = $now; $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($this->_params['receipt_date'])); } else { $this->_params['receipt_date'] = NULL; } if ($this->_mode) { $this->_params['register_date'] = $now; $this->_params['description'] = ts("Contribution submitted by a staff person using member's credit card for renewal"); $this->_params['amount'] = $this->_params['total_amount']; // 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 = $this->_paymentProcessor['object']; if (!empty($this->_params['auto_renew'])) { $contributionRecurParams = $this->processRecurringContribution($paymentParams); $contributionRecurID = $contributionRecurParams['contributionRecurID']; $paymentParams = array_merge($paymentParams, $contributionRecurParams); } $result = $payment->doPayment($paymentParams); $this->_params = array_merge($this->_params, $result); $this->_params['contribution_status_id'] = $result['payment_status_id']; $this->_params['trxn_id'] = $result['trxn_id']; $this->_params['payment_instrument_id'] = 1; $this->_params['is_test'] = $this->_mode == 'live' ? 0 : 1; $this->set('params', $this->_params); $this->assign('trxn_id', $result['trxn_id']); } $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = CRM_Utils_Date::processDate($this->_params['renewal_date']) : NULL; // 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', $this->_params))) { $numRenewTerms = $this->_params['num_terms']; } //if contribution status is pending then set pay later $this->_params['is_pay_later'] = FALSE; if ($this->_params['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) { $this->_params['is_pay_later'] = 1; } // These variable sets prior to renewMembership may not be required for this form. They were in // a function this form shared with other forms. $membershipSource = NULL; if (!empty($this->_params['membership_source'])) { $membershipSource = $this->_params['membership_source']; } $isPending = $this->_params['contribution_status_id'] == 2 ? TRUE : FALSE; list($renewMembership) = CRM_Member_BAO_Membership::renewMembership($this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership, $renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId, $isPending, $contributionRecurID, $membershipSource, $this->_params['is_pay_later'], CRM_Utils_Array::value('campaign_id', $this->_params)); $this->endDate = CRM_Utils_Date::processDate($renewMembership->end_date); $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name'); if (!empty($this->_params['record_contribution']) || $this->_mode) { // set the source $this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})"; //create line items $lineItem = array(); $this->_params = $this->setPriceSetParameters($this->_params); CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$this->_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', $this->_params)) { foreach ($lineItem[$this->_priceSetId] as &$li) { $li['financial_type_id'] = $submittedFinancialType; } } if (!empty($lineItem)) { $this->_params['lineItems'] = $lineItem; $this->_params['processPriceSet'] = TRUE; } //assign contribution contact id to the field expected by recordMembershipContribution if ($this->_contributorContactID != $this->_contactID) { $this->_params['contribution_contact_id'] = $this->_contributorContactID; if (!empty($this->_params['soft_credit_type_id'])) { $this->_params['soft_credit'] = array('soft_credit_type_id' => $this->_params['soft_credit_type_id'], 'contact_id' => $this->_contactID); } } $this->_params['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($this->_params, array('membership_id' => $renewMembership->id)); CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams); } if (!empty($this->_params['send_receipt'])) { $receiptFrom = $this->_params['from_email_address']; if (!empty($this->_params['payment_instrument_id'])) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $this->_params['paidBy'] = $paymentInstrument[$this->_params['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', $this->_params); if (!empty($this->_params['contribution_id'])) { $this->assign('contributionID', $this->_params['contribution_id']); } $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id)); $this->assign('customValues', $customValues); $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date)); $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date)); if ($this->_mode) { // 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) = explode('-', $part); if (isset($this->_params['billing_' . $part])) { $addressFields[$n] = $this->_params['billing_' . $part]; } } $this->assign('address', CRM_Utils_Address::format($addressFields)); $this->assign('contributeMode', 'direct'); $this->assign('isAmountzero', 0); $this->assign('is_pay_later', 0); $this->assign('isPrimary', 1); $this->assign('receipt_text_renewal', $this->_params['receipt_text']); if ($this->_mode == 'test') { $this->assign('action', '1024'); } } list($this->isMailSent) = 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')); } }
/** * Send notfication email to supporter * 1. when their PCP status is changed by site admin. * 2. when supporter initially creates a Personal Campaign Page ($isInitial set to true). * * @param int $pcpId * Campaign page id. * @param int $newStatus * Pcp status id. * @param bool|int $isInitial is it the first time, campaign page has been created by the user * * @param string $component * * @throws Exception * @return null */ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE, $component = 'contribute') { $pcpStatusName = CRM_Core_OptionGroup::values("pcp_status", FALSE, FALSE, FALSE, NULL, 'name'); $pcpStatus = CRM_Core_OptionGroup::values("pcp_status"); $config = CRM_Core_Config::singleton(); if (!isset($pcpStatus[$newStatus])) { return FALSE; } require_once 'Mail/mime.php'; //set loginUrl $loginURL = $config->userSystem->getLoginURL(); // used in subject templates $contribPageTitle = self::getPcpPageTitle($pcpId, $component); $tplParams = array('loginUrl' => $loginURL, 'contribPageTitle' => $contribPageTitle, 'pcpId' => $pcpId); //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 » Communications » FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl))); } $receiptFrom = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>'; // get recipient (supporter) name and email $params = array('id' => $pcpId); CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo); list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($pcpInfo['contact_id']); // get pcp block info list($blockId, $eid) = self::getPcpBlockEntityId($pcpId, $component); $params = array('id' => $blockId); CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlockInfo); // assign urls required in email template if ($pcpStatusName[$newStatus] == 'Approved') { $tplParams['isTellFriendEnabled'] = $pcpBlockInfo['is_tellfriend_enabled']; if ($pcpBlockInfo['is_tellfriend_enabled']) { $pcpTellFriendURL = CRM_Utils_System::url('civicrm/friend', "reset=1&eid={$pcpId}&blockId={$blockId}&pcomponent=pcp", TRUE, NULL, FALSE, TRUE); $tplParams['pcpTellFriendURL'] = $pcpTellFriendURL; } } $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcpId}", TRUE, NULL, FALSE, TRUE); $tplParams['pcpInfoURL'] = $pcpInfoURL; $tplParams['contribPageTitle'] = $contribPageTitle; if ($emails = CRM_Utils_Array::value('notify_email', $pcpBlockInfo)) { $emailArray = explode(',', $emails); $tplParams['pcpNotifyEmailAddress'] = $emailArray[0]; } // get appropriate message based on status $tplParams['pcpStatus'] = $pcpStatus[$newStatus]; $tplName = $isInitial ? 'pcp_supporter_notify' : 'pcp_status_change'; list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => $tplName, 'contactId' => $pcpInfo['contact_id'], 'tplParams' => $tplParams, 'from' => $receiptFrom, 'toName' => $name, 'toEmail' => $address)); return $sent; }
/** * Implmentation of hook_civicrm_post * * This hook is called after a db write on some core objects. * pre and post hooks are useful for developers building more * complex applications and need to perform operations before * CiviCRM takes action * * http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_post * * @param $op - operation being performed with CiviCRM object. * @param $objectName * @param $objectId - the unique identifier for the object. tagID in case of EntityTag * @param $objectRef - the reference to the object if available. For case of EntityTag it is an array of (entityTable, entityIDs) * */ function joinrenew_civicrm_post($op, $objectName, $objectId, &$objectRef) { //for Subscriptions //Membership: type - No way to see online only vs print //LineItem: field 7 value 12 /********************[ Handle Gift Memberships ]********************/ if ($op == "create" && $objectName == "LineItem") { //Gift Memberships //for Giftmembership page: if ($objectRef->price_field_id == 252 && $objectRef->qty > 0) { if (($objectRef->price_field_id == JR_GIFTMEMBERSHIP_FIELD_ID || $objectRef->price_field_id == GMSA_GIFTMEMBERSHIP_FIELD_ID) && $objectRef->qty > 0) { if (array_key_exists("GiftMembership", $_SESSION)) { $i = 1; $output = ""; while ($i <= $objectRef->qty) { if (array_key_exists($i, $_SESSION['GiftMembership'])) { $output .= $_SESSION['GiftMembership'][$i]['name'] . "<" . $_SESSION['GiftMembership'][$i]['email'] . ">\n"; } $i++; } $sql = "INSERT INTO `civicrm_value_old_transaction_data_20` (entity_id, gift_membership_details_201) VALUES (" . $objectRef->contribution_id . ", %1)"; CRM_Core_DAO::executeQuery($sql, array(1 => array($output, "String"))); $params = array('id' => $_SESSION['CiviCRM']['userID'], 'sequential' => 1, 'return' => "display_name"); $result = civicrm_api3("Contact", "get", $params); $name = ""; if ($result['is_error'] == 0 and $result['count'] > 0) { $name = $result['values'][0]['display_name'] . " "; } //Create the code $code = uniqid("GM"); //$count = $params = array("code" => $code, "description" => "GM:" . date("Y-m-d") . ":" . $name . ":" . $_SESSION['CiviCRM']['userID'] . ":", "amount" => 100, "amount_type" => 1, "count_max" => $objectRef->qty, "count_use" => 0, "pricesets" => array(13, 24), "memberships" => array(), "is_active" => 1, "filters" => array(), "autodiscount" => array(), "discount_msg_enabled" => 0, "discount_msg" => "", 'multi_valued' => array('pricesets' => "", 'memberships' => "")); $result = civicrm_api3("DiscountCode", "create", $params); //Send the email $_SESSION['GiftMemberships']['code'] = $code; $sendTemplateParams = array('messageTemplateID' => 67, 'contactId' => $_SESSION['CiviCRM']['userID'], 'isTest' => false, 'PDFFilename' => 'GiftMembership.pdf'); $sendTemplateParams['from'] = "Heather Cacanindin <*****@*****.**>"; $sendTemplateParams['cc'] = "Heather Cacanindin <*****@*****.**>"; //$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values); $i = 1; while ($i <= $objectRef->qty) { if (array_key_exists($i, $_SESSION['GiftMembership'])) { $_SESSION['GiftMemberships']['name'] = $_SESSION['GiftMembership'][$i]['name']; $sendTemplateParams['toName'] = $_SESSION['GiftMembership'][$i]['name']; $sendTemplateParams['toEmail'] = $_SESSION['GiftMembership'][$i]['email']; list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } $i++; } unset($_SESSION['GiftMembership']); } } //AJB Online Only if ($objectRef->price_field_id == 67 && ($objectRef->price_field_value_id == 143 || $objectRef->price_field_value_id == 143)) { //todo: Populate whatever field/relationship we need based on purchased lineitems } } }