/** * Function to build the compose PDF letter form * * @param $form * * @return None * @access public */ public static function commonLetterCompose(&$form) { //get the tokens. $tokens = CRM_Core_SelectValues::contactTokens(); if (CRM_Utils_System::getClassName($form) == 'CRM_Mailing_Form_Upload') { $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens); } //@todo move this fn onto the form if (CRM_Utils_System::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') { $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens); } if (method_exists($form, 'listTokens')) { $tokens = array_merge($form->listTokens(), $tokens); } //sorted in ascending order tokens by ignoring word case natcasesort($tokens); $form->assign('tokens', json_encode($tokens)); $form->add('select', 'token1', ts('Insert Tokens'), $tokens, FALSE, array('size' => "5", 'multiple' => TRUE, 'onchange' => "return tokenReplHtml(this);")); $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE); if (!empty($form->_templates)) { $form->assign('templates', TRUE); $form->add('select', 'template', ts('Select Template'), array('' => ts('- select -')) + $form->_templates, FALSE, array('onChange' => "selectValue( this.value );")); $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL); } $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE, array('onclick' => "showSaveDetails(this);")); $form->add('text', 'saveTemplateName', ts('Template Title')); $form->addWysiwyg('html_message', ts('Your Letter'), array('cols' => '80', 'rows' => '8', 'onkeyup' => "return verify(this)")); $action = CRM_Utils_Request::retrieve('action', 'String', $form, FALSE); if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Task_PDF' && $action == CRM_Core_Action::VIEW) { $form->freeze('html_message'); } }
/** * 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; }
/** * Process the form after the input has been submitted and validated. * * * @param CRM_Core_Form $form * * @return void */ public static function postProcess(&$form) { // check and ensure that $thisValues = $form->controller->exportValues($form->getName()); $fromSmsProviderId = $thisValues['sms_provider_id']; // process message template if (!empty($thisValues['saveTemplate']) || !empty($thisValues['updateTemplate'])) { $messageTemplate = array('msg_text' => $thisValues['sms_text_message'], 'is_active' => TRUE); if (!empty($thisValues['saveTemplate'])) { $messageTemplate['msg_title'] = $thisValues['saveTemplateName']; CRM_Core_BAO_MessageTemplate::add($messageTemplate); } if (!empty($thisValues['template']) && !empty($thisValues['updateTemplate'])) { $messageTemplate['id'] = $thisValues['template']; unset($messageTemplate['msg_title']); CRM_Core_BAO_MessageTemplate::add($messageTemplate); } } // format contact details array to handle multiple sms from same contact $formattedContactDetails = array(); $tempPhones = array(); foreach ($form->_contactIds as $key => $contactId) { $phone = $form->_toContactPhone[$key]; if ($phone) { $phoneKey = "{$contactId}::{$phone}"; if (!in_array($phoneKey, $tempPhones)) { $tempPhones[] = $phoneKey; if (!empty($form->_contactDetails[$contactId])) { $formattedContactDetails[] = $form->_contactDetails[$contactId]; } } } } // $smsParams carries all the arguments provided on form (or via hooks), to the provider->send() method // this gives flexibity to the users / implementors to add their own args via hooks specific to their sms providers $smsParams = $thisValues; unset($smsParams['sms_text_message']); $smsParams['provider_id'] = $fromSmsProviderId; $contactIds = array_keys($form->_contactDetails); $allContactIds = array_keys($form->_allContactDetails); list($sent, $activityId, $countSuccess) = CRM_Activity_BAO_Activity::sendSMS($formattedContactDetails, $thisValues, $smsParams, $contactIds); if ($countSuccess > 0) { CRM_Core_Session::setStatus(ts('One message was sent successfully.', array('plural' => '%count messages were sent successfully.', 'count' => $countSuccess)), ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $countSuccess)), 'success'); } if (is_array($sent)) { // At least one PEAR_Error object was generated. // Display the error messages to the user. $status = '<ul>'; foreach ($sent as $errMsg) { $status .= '<li>' . $errMsg . '</li>'; } $status .= '</ul>'; CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($sent), 'plural' => '%count Messages Not Sent')), 'info'); } else { //Display the name and number of contacts for those sms is not sent. $smsNotSent = array_diff_assoc($allContactIds, $contactIds); if (!empty($smsNotSent)) { $not_sent = array(); foreach ($smsNotSent as $index => $contactId) { $displayName = $form->_allContactDetails[$contactId]['display_name']; $phone = $form->_allContactDetails[$contactId]['phone']; $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contactId}"); $not_sent[] = "<a href='{$contactViewUrl}' title='{$phone}'>{$displayName}</a>"; } $status = '(' . ts('because no phone number on file or communication preferences specify DO NOT SMS or Contact is deceased'); if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') { $status .= ' ' . ts("or the contact is not part of the activity '%1'", array(1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT)); } $status .= ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>'; CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($smsNotSent), 'plural' => '%count Messages Not Sent')), 'info'); } } }
/** * Process the form submission. * * * @return void */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Core_BAO_MessageTemplate::del($this->_id); } elseif ($this->_action & CRM_Core_Action::VIEW) { // currently, the above action is used solely for previewing default workflow templates CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/messageTemplates', 'selectedChild=workflow&reset=1')); } else { $params = array(); // store the submitted values in an array $params = $this->exportValues(); if ($this->_action & CRM_Core_Action::UPDATE) { $params['id'] = $this->_id; } if ($this->_workflow_id) { $params['workflow_id'] = $this->_workflow_id; $params['is_active'] = TRUE; } $messageTemplate = CRM_Core_BAO_MessageTemplate::add($params); CRM_Core_Session::setStatus(ts('The Message Template \'%1\' has been saved.', array(1 => $messageTemplate->msg_title)), ts('Saved'), 'success'); if ($this->_workflow_id) { CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/messageTemplates', 'selectedChild=workflow&reset=1')); } else { CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/messageTemplates', 'selectedChild=user&reset=1')); } } }
/** * 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; }
/** * @param array $values * The submitted form values. * @return CRM_Core_DAO_ActionSchedule */ public function parseActionSchedule($values) { $params = array(); $keys = array('title', 'subject', 'absolute_date', 'group_id', 'record_activity', 'limit_to', 'mode', 'sms_provider_id', 'from_name', 'from_email'); foreach ($keys as $key) { $params[$key] = CRM_Utils_Array::value($key, $values); } $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0); $moreKeys = array('start_action_offset', 'start_action_unit', 'start_action_condition', 'start_action_date', 'repetition_frequency_unit', 'repetition_frequency_interval', 'end_frequency_unit', 'end_frequency_interval', 'end_action', 'end_date'); if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) { $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate); $params['is_repeat'] = 0; foreach ($moreKeys as $mkey) { $params[$mkey] = 'null'; } } else { $params['absolute_date'] = 'null'; foreach ($moreKeys as $mkey) { $params[$mkey] = CRM_Utils_Array::value($mkey, $values); } } $params['body_text'] = CRM_Utils_Array::value('text_message', $values); $params['sms_body_text'] = CRM_Utils_Array::value('sms_text_message', $values); $params['body_html'] = CRM_Utils_Array::value('html_message', $values); if (CRM_Utils_Array::value('recipient', $values) == 'manual') { $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values); $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (CRM_Utils_Array::value('recipient', $values) == 'group') { $params['group_id'] = $values['group_id']; $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (isset($values['recipient_listing']) && isset($values['limit_to']) && !CRM_Utils_System::isNull($values['recipient_listing']) && !CRM_Utils_System::isNull($values['limit_to'])) { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('recipient_listing', $values)); $params['group_id'] = $params['recipient_manual'] = 'null'; } else { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null'; } if (!empty($this->_mappingID) && !empty($this->_compId)) { $params['mapping_id'] = $this->_mappingID; $params['entity_value'] = $this->_compId; $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']); } else { $params['mapping_id'] = $values['entity'][0]; if ($params['mapping_id'] == 1) { $params['limit_to'] = 1; } $entity_value = CRM_Utils_Array::value(1, $values['entity'], array()); $entity_status = CRM_Utils_Array::value(2, $values['entity'], array()); $params['entity_value'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_value); $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_status); } $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0); if (CRM_Utils_Array::value('is_repeat', $values) == 0) { $params['repetition_frequency_unit'] = 'null'; $params['repetition_frequency_interval'] = 'null'; $params['end_frequency_unit'] = 'null'; $params['end_frequency_interval'] = 'null'; $params['end_action'] = 'null'; $params['end_date'] = 'null'; } // multilingual options $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, array()); $params['filter_contact_language'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['filter_contact_language']); $params['communication_language'] = CRM_Utils_Array::value('communication_language', $values, NULL); if ($this->_action & CRM_Core_Action::UPDATE) { $params['id'] = $this->_id; } elseif ($this->_action & CRM_Core_Action::ADD) { // we do this only once, so name never changes $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64); } $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS'); if ($params['mode'] == 'Email' || empty($params['sms_provider_id'])) { unset($modePrefixes['SMS']); } elseif ($params['mode'] == 'SMS') { unset($modePrefixes['Mail']); } //TODO: handle postprocessing of SMS and/or Email info based on $modePrefixes $composeFields = array('template', 'saveTemplate', 'updateTemplate', 'saveTemplateName'); $msgTemplate = NULL; //mail template is composed foreach ($modePrefixes as $prefix) { $composeParams = array(); foreach ($composeFields as $key) { $key = $prefix . $key; if (!empty($values[$key])) { $composeParams[$key] = $values[$key]; } } if (!empty($composeParams[$prefix . 'updateTemplate'])) { $templateParams = array('is_active' => TRUE); if ($prefix == 'SMS') { $templateParams += array('msg_text' => $params['sms_body_text'], 'is_sms' => TRUE); } else { $templateParams += array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject']); } $templateParams['id'] = $values[$prefix . 'template']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if (!empty($composeParams[$prefix . 'saveTemplate'])) { $templateParams = array('is_active' => TRUE); if ($prefix == 'SMS') { $templateParams += array('msg_text' => $params['sms_body_text'], 'is_sms' => TRUE); } else { $templateParams += array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject']); } $templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if ($prefix == 'SMS') { if (isset($msgTemplate->id)) { $params['sms_template_id'] = $msgTemplate->id; } else { $params['sms_template_id'] = CRM_Utils_Array::value('SMStemplate', $values); } } else { if (isset($msgTemplate->id)) { $params['msg_template_id'] = $msgTemplate->id; } else { $params['msg_template_id'] = CRM_Utils_Array::value('template', $values); } } } $actionSchedule = new CRM_Core_DAO_ActionSchedule(); $actionSchedule->copyValues($params); return $actionSchedule; }
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)); }
/** * 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 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); } }
/** * 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')); } }
/** * 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')); } }
/** * 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 after the input has been submitted and validated. * * @param CRM_Core_Form $form */ public static function postProcess(&$form) { if (count($form->_contactIds) > self::MAX_EMAILS_KILL_SWITCH) { CRM_Core_Error::fatal(ts('Please do not use this task to send a lot of emails (greater than %1). We recommend using CiviMail instead.', array(1 => self::MAX_EMAILS_KILL_SWITCH))); } // check and ensure that $formValues = $form->controller->exportValues($form->getName()); $fromEmail = $formValues['fromEmailAddress']; $from = CRM_Utils_Array::value($fromEmail, $form->_emails); $subject = $formValues['subject']; // CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields $elements = array('cc_id', 'bcc_id'); $additionalDetails = NULL; $ccValues = $bccValues = array(); foreach ($elements as $element) { if (!empty($formValues[$element])) { $allEmails = explode(',', $formValues[$element]); foreach ($allEmails as $value) { list($contactId, $email) = explode('::', $value); $contactURL = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$contactId}", TRUE); switch ($element) { case 'cc_id': $ccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>'; $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>"; break; case 'bcc_id': $bccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>'; $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>"; break; } } } } $cc = $bcc = ''; if (!empty($ccValues)) { $cc = implode(',', $ccValues['email']); $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']); } if (!empty($bccValues)) { $bcc = implode(',', $bccValues['email']); $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']); } // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects if (isset($form->_caseId) && is_numeric($form->_caseId)) { $hash = substr(sha1(CIVICRM_SITE_KEY . $form->_caseId), 0, 7); $subject = "[case #{$hash}] {$subject}"; } // process message template if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) { $messageTemplate = array('msg_text' => $formValues['text_message'], 'msg_html' => $formValues['html_message'], 'msg_subject' => $formValues['subject'], 'is_active' => TRUE); if (!empty($formValues['saveTemplate'])) { $messageTemplate['msg_title'] = $formValues['saveTemplateName']; CRM_Core_BAO_MessageTemplate::add($messageTemplate); } if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) { $messageTemplate['id'] = $formValues['template']; unset($messageTemplate['msg_title']); CRM_Core_BAO_MessageTemplate::add($messageTemplate); } } $attachments = array(); CRM_Core_BAO_File::formatAttachment($formValues, $attachments, NULL, NULL); // format contact details array to handle multiple emails from same contact $formattedContactDetails = array(); $tempEmails = array(); foreach ($form->_contactIds as $key => $contactId) { // if we dont have details on this contactID, we should ignore // potentially this is due to the contact not wanting to receive email if (!isset($form->_contactDetails[$contactId])) { continue; } $email = $form->_toContactEmails[$key]; // prevent duplicate emails if same email address is selected CRM-4067 // we should allow same emails for different contacts $emailKey = "{$contactId}::{$email}"; if (!in_array($emailKey, $tempEmails)) { $tempEmails[] = $emailKey; $details = $form->_contactDetails[$contactId]; $details['email'] = $email; unset($details['email_id']); $formattedContactDetails[] = $details; } } // send the mail list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail($formattedContactDetails, $subject, $formValues['text_message'], $formValues['html_message'], NULL, NULL, $from, $attachments, $cc, $bcc, array_keys($form->_toContactDetails), $additionalDetails); $followupStatus = ''; if ($sent) { $followupActivity = NULL; if (!empty($formValues['followup_activity_type_id'])) { $params['followup_activity_type_id'] = $formValues['followup_activity_type_id']; $params['followup_activity_subject'] = $formValues['followup_activity_subject']; $params['followup_date'] = $formValues['followup_date']; $params['followup_date_time'] = $formValues['followup_date_time']; $params['target_contact_id'] = $form->_contactIds; $params['followup_assignee_contact_id'] = explode(',', $formValues['followup_assignee_contact_id']); $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activityId, $params); $followupStatus = ts('A followup activity has been scheduled.'); if (Civi::settings()->get('activity_assignee_notification')) { if ($followupActivity) { $mailToFollowupContacts = array(); $assignee = array($followupActivity->id); $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($assignee, TRUE, FALSE); foreach ($assigneeContacts as $values) { $mailToFollowupContacts[$values['email']] = $values; } $sentFollowup = CRM_Activity_BAO_Activity::sendToAssignee($followupActivity, $mailToFollowupContacts); if ($sentFollowup) { $followupStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s)."); } } } } $count_success = count($form->_toContactDetails); CRM_Core_Session::setStatus(ts('One message was sent successfully. ', array('plural' => '%count messages were sent successfully. ', 'count' => $count_success)) . $followupStatus, ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $count_success)), 'success'); } // Display the name and number of contacts for those email is not sent. // php 5.4 throws out a notice since the values of these below arrays are arrays. // the behavior is not documented in the php manual, but it does the right thing // suppressing the notices to get things in good shape going forward $emailsNotSent = @array_diff_assoc($form->_allContactDetails, $form->_contactDetails); if ($emailsNotSent) { $not_sent = array(); foreach ($emailsNotSent as $contactId => $values) { $displayName = $values['display_name']; $email = $values['email']; $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contactId}"); $not_sent[] = "<a href='{$contactViewUrl}' title='{$email}'>{$displayName}</a>" . ($values['on_hold'] ? '(' . ts('on hold') . ')' : ''); } $status = '(' . ts('because no email address on file or communication preferences specify DO NOT EMAIL or Contact is deceased or Primary email address is On Hold') . ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>'; CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($emailsNotSent), 'plural' => '%count Messages Not Sent')), 'info'); } if (isset($form->_caseId)) { // if case-id is found in the url, create case activity record $cases = explode(',', $form->_caseId); foreach ($cases as $key => $val) { if (is_numeric($val)) { $caseParams = array('activity_id' => $activityId, 'case_id' => $val); CRM_Case_BAO_Case::processCaseActivity($caseParams); } } } }
/** * @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; }
/** * Function to process the form * * @access public * * @return void */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { // delete reminder CRM_Core_BAO_ActionSchedule::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success'); if ($this->_context == 'event' && $this->_eventId) { $url = CRM_Utils_System::url('civicrm/event/manage/reminder', "reset=1&action=update&id={$this->_eventId}"); $session = CRM_Core_Session::singleton(); $session->pushUserContext($url); } return; } $values = $this->controller->exportValues($this->getName()); $keys = array('title', 'subject', 'absolute_date', 'group_id', 'record_activity', 'limit_to', 'mode', 'sms_provider_id', 'from_name', 'from_email'); foreach ($keys as $key) { $params[$key] = CRM_Utils_Array::value($key, $values); } $moreKeys = array('start_action_offset', 'start_action_unit', 'start_action_condition', 'start_action_date', 'repetition_frequency_unit', 'repetition_frequency_interval', 'end_frequency_unit', 'end_frequency_interval', 'end_action', 'end_date'); if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) { $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate); foreach ($moreKeys as $mkey) { $params[$mkey] = 'null'; } } else { $params['absolute_date'] = 'null'; foreach ($moreKeys as $mkey) { $params[$mkey] = CRM_Utils_Array::value($mkey, $values); } } $params['body_text'] = CRM_Utils_Array::value('text_message', $values); $params['body_html'] = CRM_Utils_Array::value('html_message', $values); if (CRM_Utils_Array::value('recipient', $values) == 'manual') { $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values); $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (CRM_Utils_Array::value('recipient', $values) == 'group') { $params['group_id'] = $values['group_id']; $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (!CRM_Utils_System::isNull($values['recipient_listing'])) { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('recipient_listing', $values)); $params['group_id'] = $params['recipient_manual'] = 'null'; } else { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null'; } $params['mapping_id'] = $values['entity'][0]; $entity_value = $values['entity'][1]; $entity_status = $values['entity'][2]; foreach (array('entity_value', 'entity_status') as $key) { $params[$key] = implode(CRM_Core_DAO::VALUE_SEPARATOR, ${$key}); } $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0); $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0); if (CRM_Utils_Array::value('is_repeat', $values) == 0) { $params['repetition_frequency_unit'] = 'null'; $params['repetition_frequency_interval'] = 'null'; $params['end_frequency_unit'] = 'null'; $params['end_frequency_interval'] = 'null'; $params['end_action'] = 'null'; $params['end_date'] = 'null'; } if ($this->_action & CRM_Core_Action::UPDATE) { $params['id'] = $this->_id; } elseif ($this->_action & CRM_Core_Action::ADD) { // we do this only once, so name never changes $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64); } $composeFields = array('template', 'saveTemplate', 'updateTemplate', 'saveTemplateName'); $msgTemplate = NULL; //mail template is composed $composeParams = array(); foreach ($composeFields as $key) { if (!empty($values[$key])) { $composeParams[$key] = $values[$key]; } } if (!empty($composeParams['updateTemplate'])) { $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE); $templateParams['id'] = $values['template']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if (!empty($composeParams['saveTemplate'])) { $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE); $templateParams['msg_title'] = $composeParams['saveTemplateName']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if (isset($msgTemplate->id)) { $params['msg_template_id'] = $msgTemplate->id; } else { $params['msg_template_id'] = CRM_Utils_Array::value('template', $values); } $bao = CRM_Core_BAO_ActionSchedule::add($params); // we need to set this on the form so that hooks can identify the created entity $this->set('id', $bao->id); $bao->free(); $status = ts("Your new Reminder titled %1 has been saved.", array(1 => "<strong>{$values['title']}</strong>")); if ($this->_action & CRM_Core_Action::UPDATE) { $status = ts("Your Reminder titled %1 has been updated.", array(1 => "<strong>{$values['title']}</strong>")); if ($this->_context == 'event' && $this->_eventId) { $url = CRM_Utils_System::url('civicrm/event/manage/reminder', "reset=1&action=update&id={$this->_eventId}"); $session = CRM_Core_Session::singleton(); $session->pushUserContext($url); } } CRM_Core_Session::setStatus($status, ts('Saved'), 'success'); }
/** * Function for validation * * @param array $params (ref.) an assoc array of name/value pairs * * @param $files * @param $self * * @return mixed true or array of errors * @access public * @static */ static function formRule($params, $files, $self) { if (!empty($_POST['_qf_Import_refresh'])) { return TRUE; } $errors = array(); $template = CRM_Core_Smarty::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->id = $self->_mailingID; $mailing->find(TRUE); $session = CRM_Core_Session::singleton(); $values = array('contact_id' => $session->get('userID'), 'version' => 3); require_once 'api/api.php'; $contact = civicrm_api('contact', 'get', $values); //CRM-4524 $contact = reset($contact['values']); $verp = array_flip(array('optOut', 'reply', 'unsubscribe', 'resubscribe', 'owner')); foreach ($verp as $key => $value) { $verp[$key]++; } $urls = array_flip(array('forward', 'optOutUrl', 'unsubscribeUrl', 'resubscribeUrl')); foreach ($urls as $key => $value) { $urls[$key]++; } $skipTextFile = $self->get('skipTextFile'); if (!$params['upload_type']) { if (!isset($files['textFile']) || !file_exists($files['textFile']['tmp_name'])) { if (!$skipTextFile) { $errors['textFile'] = ts('Please provide a Text'); } } } else { if (empty($params['text_message'])) { $errors['text_message'] = ts('Please provide a Text'); } else { if (!empty($params['text_message'])) { $messageCheck = CRM_Utils_Array::value('text_message', $params); if ($messageCheck && strlen($messageCheck) > CRM_SMS_Provider::MAX_SMS_CHAR) { $errors['text_message'] = ts("You can configure the SMS message body up to %1 characters", array(1 => CRM_SMS_Provider::MAX_SMS_CHAR)); } } } if (!empty($params['saveTemplate']) && empty($params['saveTemplateName'])) { $errors['saveTemplateName'] = ts('Please provide a Template Name.'); } } if ($params['upload_type'] || file_exists(CRM_Utils_Array::value('tmp_name', $files['textFile'])) || !$params['upload_type'] && $params['text_message']) { if (!$params['upload_type']) { $str = file_get_contents($files['textFile']['tmp_name']); $name = $files['textFile']['name']; } else { $str = $params['text_message']; $name = 'text message'; } $dataErrors = array(); /* Do a full token replacement on a dummy verp, the current * contact and domain, and the first organization. */ // here we make a dummy mailing object so that we // can retrieve the tokens that we need to replace // so that we do get an invalid token error // this is qute hacky and I hope that there might // be a suggestion from someone on how to // make it a bit more elegant $dummy_mail = new CRM_Mailing_BAO_Mailing(); $mess = "body_text"; $dummy_mail->{$mess} = $str; $tokens = $dummy_mail->getTokens(); $str = CRM_Utils_Token::replaceSubscribeInviteTokens($str); $str = CRM_Utils_Token::replaceDomainTokens($str, $domain, NULL, $tokens['text']); $str = CRM_Utils_Token::replaceMailingTokens($str, $mailing, NULL, $tokens['text']); $str = CRM_Utils_Token::replaceOrgTokens($str, $org); $str = CRM_Utils_Token::replaceActionTokens($str, $verp, $urls, NULL, $tokens['text']); $str = CRM_Utils_Token::replaceContactTokens($str, $contact, NULL, $tokens['text']); $unmatched = CRM_Utils_Token::unmatchedTokens($str); $contentCheck = CRM_Utils_String::htmlToText($str); if (!empty($unmatched) && 0) { foreach ($unmatched as $token) { $dataErrors[] = '<li>' . ts('Invalid token code') . ' {' . $token . '}</li>'; } } if (strlen($contentCheck) > CRM_SMS_Provider::MAX_SMS_CHAR) { $dataErrors[] = '<li>' . ts('The body of the SMS cannot exceed %1 characters.', array(1 => CRM_SMS_Provider::MAX_SMS_CHAR)) . '</li>'; } if (!empty($dataErrors)) { $errors['textFile'] = ts('The following errors were detected in %1:', array(1 => $name)) . ' <ul>' . implode('', $dataErrors) . '</ul>'; } } $templateName = CRM_Core_BAO_MessageTemplate::getMessageTemplates(); if (!empty($params['saveTemplate']) && in_array(CRM_Utils_Array::value('saveTemplateName', $params), $templateName)) { $errors['saveTemplate'] = ts('Duplicate Template Name.'); } return empty($errors) ? TRUE : $errors; }
/** * 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); }
/** * Build the compose mail form. * * @param CRM_Core_Form $form * * @return void */ public static function commonCompose(&$form) { //get the tokens. $tokens = array(); if (method_exists($form, 'listTokens')) { $tokens = array_merge($form->listTokens(), $tokens); } //sorted in ascending order tokens by ignoring word case $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens)); $templates = array(); $textFields = array('text_message' => ts('HTML Format'), 'sms_text_message' => ts('SMS Message')); $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS'); $className = CRM_Utils_System::getClassName($form); if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' && $className != 'CRM_Contact_Form_Task_SMS') { $form->add('wysiwyg', 'html_message', ts('HTML Format'), array('cols' => '80', 'rows' => '8', 'onkeyup' => "return verify(this)")); if ($className != 'CRM_Admin_Form_ScheduleReminders') { unset($modePrefixes['SMS']); } } else { unset($textFields['text_message']); unset($modePrefixes['Mail']); } //insert message Text by selecting "Select Template option" foreach ($textFields as $id => $label) { $prefix = NULL; if ($id == 'sms_text_message') { $prefix = "SMS"; $form->assign('max_sms_length', CRM_SMS_Provider::MAX_SMS_CHAR); } $form->add('textarea', $id, $label, array('cols' => '80', 'rows' => '8', 'onkeyup' => "return verify(this, '{$prefix}')")); } foreach ($modePrefixes as $prefix) { if ($prefix == 'SMS') { $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE, TRUE); } else { $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE); } if (!empty($templates[$prefix])) { $form->assign('templates', TRUE); $form->add('select', "{$prefix}template", ts('Use Template'), array('' => ts('- select -')) + $templates[$prefix], FALSE, array('onChange' => "selectValue( this.value, '{$prefix}');")); } $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL); $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE, array('onclick' => "showSaveDetails(this, '{$prefix}');")); $form->add('text', "{$prefix}saveTemplateName", ts('Template Title')); } // I'm not sure this is ever called. $action = CRM_Utils_Request::retrieve('action', 'String', $form, FALSE); if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Task_PDF' && $action == CRM_Core_Action::VIEW) { $form->freeze('html_message'); } }
/** * 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 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); } } }
/** * 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)); } } }
/** * Validation. * * @param array $params * (ref.) an assoc array of name/value pairs. * * @param $files * @param $self * * @return bool|array * mixed true or array of errors */ public static function formRule($params, $files, $self) { if (!empty($_POST['_qf_Import_refresh'])) { return TRUE; } $errors = array(); $template = CRM_Core_Smarty::singleton(); if (isset($params['html_message'])) { $htmlMessage = str_replace(array("\n", "\r"), ' ', $params['html_message']); $htmlMessage = str_replace("'", "\\'", $htmlMessage); $template->assign('htmlContent', $htmlMessage); } $domain = CRM_Core_BAO_Domain::getDomain(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->id = $self->_mailingID; $mailing->find(TRUE); $session = CRM_Core_Session::singleton(); $values = array('contact_id' => $session->get('userID'), 'version' => 3); require_once 'api/api.php'; $contact = civicrm_api('contact', 'get', $values); //CRM-4524 $contact = reset($contact['values']); $verp = array_flip(array('optOut', 'reply', 'unsubscribe', 'resubscribe', 'owner')); foreach ($verp as $key => $value) { $verp[$key]++; } $urls = array_flip(array('forward', 'optOutUrl', 'unsubscribeUrl', 'resubscribeUrl')); foreach ($urls as $key => $value) { $urls[$key]++; } // set $header and $footer foreach (array('header', 'footer') as $part) { ${$part} = array(); if ($params["{$part}_id"]) { //echo "found<p>"; $component = new CRM_Mailing_BAO_Component(); $component->id = $params["{$part}_id"]; $component->find(TRUE); ${$part}['textFile'] = $component->body_text; ${$part}['htmlFile'] = $component->body_html; $component->free(); } else { ${$part}['htmlFile'] = ${$part}['textFile'] = ''; } } $skipTextFile = $self->get('skipTextFile'); $skipHtmlFile = $self->get('skipHtmlFile'); if (!$params['upload_type']) { if ((!isset($files['textFile']) || !file_exists($files['textFile']['tmp_name'])) && (!isset($files['htmlFile']) || !file_exists($files['htmlFile']['tmp_name']))) { if (!($skipTextFile || $skipHtmlFile)) { $errors['textFile'] = ts('Please provide either a Text or HTML formatted message - or both.'); } } } else { if (empty($params['text_message']) && empty($params['html_message'])) { $errors['html_message'] = ts('Please provide either a Text or HTML formatted message - or both.'); } if (!empty($params['saveTemplate']) && empty($params['saveTemplateName'])) { $errors['saveTemplateName'] = ts('Please provide a Template Name.'); } } foreach (array('text', 'html') as $file) { if (!$params['upload_type'] && !file_exists(CRM_Utils_Array::value('tmp_name', $files[$file . 'File']))) { continue; } if ($params['upload_type'] && !$params[$file . '_message']) { continue; } if (!$params['upload_type']) { $str = file_get_contents($files[$file . 'File']['tmp_name']); $name = $files[$file . 'File']['name']; } else { $str = $params[$file . '_message']; $str = $file == 'html' ? str_replace('%7B', '{', str_replace('%7D', '}', $str)) : $str; $name = $file . ' message'; } /* append header/footer */ $str = $header[$file . 'File'] . $str . $footer[$file . 'File']; $dataErrors = array(); /* First look for missing tokens */ if (!CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'disable_mandatory_tokens_check')) { $err = CRM_Utils_Token::requiredTokens($str); if ($err !== TRUE) { foreach ($err as $token => $desc) { $dataErrors[] = '<li>' . ts('This message is missing a required token - {%1}: %2', array(1 => $token, 2 => $desc)) . '</li>'; } } } /* Do a full token replacement on a dummy verp, the current * contact and domain, and the first organization. */ // here we make a dummy mailing object so that we // can retrieve the tokens that we need to replace // so that we do get an invalid token error // this is qute hacky and I hope that there might // be a suggestion from someone on how to // make it a bit more elegant $dummy_mail = new CRM_Mailing_BAO_Mailing(); $mess = "body_{$file}"; $dummy_mail->{$mess} = $str; $tokens = $dummy_mail->getTokens(); $str = CRM_Utils_Token::replaceSubscribeInviteTokens($str); $str = CRM_Utils_Token::replaceDomainTokens($str, $domain, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceMailingTokens($str, $mailing, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceOrgTokens($str, $org); $str = CRM_Utils_Token::replaceActionTokens($str, $verp, $urls, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceContactTokens($str, $contact, NULL, $tokens[$file]); $unmatched = CRM_Utils_Token::unmatchedTokens($str); if (!empty($unmatched) && 0) { foreach ($unmatched as $token) { $dataErrors[] = '<li>' . ts('Invalid token code') . ' {' . $token . '}</li>'; } } if (!empty($dataErrors)) { $errors[$file . 'File'] = ts('The following errors were detected in %1:', array(1 => $name)) . ' <ul>' . implode('', $dataErrors) . '</ul><br /><a href="' . CRM_Utils_System::docURL2('Sample CiviMail Messages', TRUE, NULL, NULL, NULL, "wiki") . '" target="_blank">' . ts('More information on required tokens...') . '</a>'; } } $templateName = CRM_Core_BAO_MessageTemplate::getMessageTemplates(); if (!empty($params['saveTemplate']) && in_array(CRM_Utils_Array::value('saveTemplateName', $params), $templateName)) { $errors['saveTemplate'] = ts('Duplicate Template Name.'); } return empty($errors) ? TRUE : $errors; }
/** * 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 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); } } } }
/** * 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; }
/** * 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; } }
/** * 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; }
/** * browse all entities. * * @internal param int $action * * @return void * @access public */ function browse() { $action = func_num_args() ? func_get_arg(0) : NULL; if ($this->_action & CRM_Core_Action::ADD) { return; } $links = $this->links(); if ($action == NULL) { if (!empty($links)) { $action = array_sum(array_keys($links)); } } if ($action & CRM_Core_Action::DISABLE) { $action -= CRM_Core_Action::DISABLE; } if ($action & CRM_Core_Action::ENABLE) { $action -= CRM_Core_Action::ENABLE; } $messageTemplate = new CRM_Core_BAO_MessageTemplate(); $messageTemplate->orderBy('msg_title' . ' asc'); $userTemplates = array(); $workflowTemplates = array(); // find all objects $messageTemplate->find(); while ($messageTemplate->fetch()) { $values[$messageTemplate->id] = array(); CRM_Core_DAO::storeValues($messageTemplate, $values[$messageTemplate->id]); // populate action links $this->action($messageTemplate, $action, $values[$messageTemplate->id], $links, CRM_Core_Permission::EDIT); if (!$messageTemplate->workflow_id) { $userTemplates[$messageTemplate->id] = $values[$messageTemplate->id]; } elseif (!$messageTemplate->is_reserved) { $workflowTemplates[$messageTemplate->id] = $values[$messageTemplate->id]; } } $rows = array('userTemplates' => $userTemplates, 'workflowTemplates' => $workflowTemplates); $this->assign('rows', $rows); }
/** * Function to process the form * * @access public * * @return void */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { // delete reminder CRM_Core_BAO_ActionSchedule::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success'); return; } $values = $this->controller->exportValues($this->getName()); $keys = array('title', 'subject', 'absolute_date', 'group_id', 'record_activity', 'limit_to'); foreach ($keys as $key) { $params[$key] = CRM_Utils_Array::value($key, $values); } $moreKeys = array('start_action_offset', 'start_action_unit', 'start_action_condition', 'start_action_date', 'repetition_frequency_unit', 'repetition_frequency_interval', 'end_frequency_unit', 'end_frequency_interval', 'end_action', 'end_date'); if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) { $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate); foreach ($moreKeys as $mkey) { $params[$mkey] = 'null'; } } else { $params['absolute_date'] = 'null'; foreach ($moreKeys as $mkey) { $params[$mkey] = CRM_Utils_Array::value($mkey, $values); } } $params['body_text'] = CRM_Utils_Array::value('text_message', $values); $params['body_html'] = CRM_Utils_Array::value('html_message', $values); if (CRM_Utils_Array::value('recipient', $values) == 'manual') { $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values); $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (CRM_Utils_Array::value('recipient', $values) == 'group') { $params['group_id'] = $values['group_id']; $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null'; } elseif (!CRM_Utils_System::isNull($values['recipient_listing'])) { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('recipient_listing', $values)); $params['group_id'] = $params['recipient_manual'] = 'null'; } else { $params['recipient'] = CRM_Utils_Array::value('recipient', $values); $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null'; } $params['mapping_id'] = $this->_mappingID; $params['entity_value'] = $this->_id; $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']); $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0); $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0); if (CRM_Utils_Array::value('is_repeat', $values) == 0) { $params['repetition_frequency_unit'] = 'null'; $params['repetition_frequency_interval'] = 'null'; $params['end_frequency_unit'] = 'null'; $params['end_frequency_interval'] = 'null'; $params['end_action'] = 'null'; $params['end_date'] = 'null'; } $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64); $composeFields = array('template', 'saveTemplate', 'updateTemplate', 'saveTemplateName'); $msgTemplate = NULL; //mail template is composed $composeParams = array(); foreach ($composeFields as $key) { if (!empty($values[$key])) { $composeParams[$key] = $values[$key]; } } if (!empty($composeParams['updateTemplate'])) { $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE); $templateParams['id'] = $values['template']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if (!empty($composeParams['saveTemplate'])) { $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE); $templateParams['msg_title'] = $composeParams['saveTemplateName']; $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams); } if (isset($msgTemplate->id)) { $params['msg_template_id'] = $msgTemplate->id; } else { $params['msg_template_id'] = CRM_Utils_Array::value('template', $values); } CRM_Core_BAO_ActionSchedule::add($params, $ids); $status = ts("Your new Reminder titled %1 has been saved.", array(1 => "<strong>{$values['title']}</strong>")); CRM_Core_Session::setStatus($status, ts('Saved'), 'success'); parent::endPostProcess(); }
/** * 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")); } }