/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return FALSE; } // before we proceed lets just check if this contact is already 'Added' // if so, we should ignore this request and hence avoid sending multiple // emails - CRM-11157 $details = CRM_Contact_BAO_GroupContact::getMembershipDetail($contact_id, $se->group_id); if ($details && $details->status == 'Added') { // This contact is already subscribed // lets return the group title return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $se->group_id, 'title'); } $transaction = new CRM_Core_Transaction(); $ce = new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(TRUE); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE); $mailParams = array('groupName' => 'Mailing Event ' . $component->component_type, 'subject' => $component->subject, 'from' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'toEmail' => $email, 'toName' => $display_name, 'replyTo' => "do-not-reply@{$emailDomain}", 'returnPath' => "do-not-reply@{$emailDomain}", 'html' => $html, 'text' => $text); // send - ignore errors because the desired status change has already been successful $unused_result = CRM_Utils_Mail::send($mailParams); return $group->title; }
/** * Run dashboard * * @return none * @access public */ function run() { $resetCache = CRM_Utils_Request::retrieve('resetCache', 'Positive', CRM_Core_DAO::$_nullObject); if ($resetCache) { CRM_Core_BAO_Dashboard::resetDashletCache(); } CRM_Utils_System::setTitle(ts('CiviCRM Home')); $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); // call hook to get html from other modules // ignored but needed to prevent warnings $contentPlacement = CRM_Utils_Hook::DASHBOARD_BELOW; $html = CRM_Utils_Hook::dashboard($contactID, $contentPlacement); if (is_array($html)) { $this->assign_by_ref('hookContent', $html); $this->assign('hookContentPlacement', $contentPlacement); } //check that default FROM email address, owner (domain) organization name and default mailbox are configured. $fromEmailOK = TRUE; $ownerOrgOK = TRUE; $defaultMailboxOK = TRUE; // Don't put up notices if user doesn't have administer CiviCRM permission if (CRM_Core_Permission::check('administer CiviCRM')) { $destination = CRM_Utils_System::url('civicrm/dashboard', 'reset=1', FALSE, NULL, FALSE); $destination = urlencode($destination); list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE); if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') { $fixEmailUrl = CRM_Utils_System::url("civicrm/admin/domain", "action=update&reset=1&civicrmDestination={$destination}"); $this->assign('fixEmailUrl', $fixEmailUrl); $fromEmailOK = FALSE; } $domain = CRM_Core_BAO_Domain::getDomain(); $domainName = $domain->name; if (!$domainName || $domainName == 'Default Domain Name') { $fixOrgUrl = CRM_Utils_System::url("civicrm/admin/domain", "action=update&reset=1&civicrmDestination={$destination}"); $this->assign('fixOrgUrl', $fixOrgUrl); $ownerOrgOK = FALSE; } $config = CRM_Core_Config::singleton(); if (in_array('CiviMail', $config->enableComponents) && CRM_Core_BAO_MailSettings::defaultDomain() == "FIXME.ORG") { $fixDefaultMailbox = CRM_Utils_System::url('civicrm/admin/mailSettings', "reset=1&civicrmDestination={$destination}"); $this->assign('fixDefaultMailbox', $fixDefaultMailbox); $defaultMailboxOK = FALSE; } } $this->assign('fromEmailOK', $fromEmailOK); $this->assign('ownerOrgOK', $ownerOrgOK); $this->assign('defaultMailboxOK', $defaultMailboxOK); return parent::run(); }
/** * Apply the various CRM_Utils_Token helpers. * * @param TokenRenderEvent $e */ public function onRender(TokenRenderEvent $e) { $isHtml = $e->message['format'] == 'text/html'; $useSmarty = !empty($e->context['smarty']); $e->string = \CRM_Utils_Token::replaceDomainTokens($e->string, \CRM_Core_BAO_Domain::getDomain(), $isHtml, $e->message['tokens'], $useSmarty); if (!empty($e->context['contact'])) { $e->string = \CRM_Utils_Token::replaceContactTokens($e->string, $e->context['contact'], $isHtml, $e->message['tokens'], FALSE, $useSmarty); // FIXME: This may depend on $contact being merged with hook values. $e->string = \CRM_Utils_Token::replaceHookTokens($e->string, $e->context['contact'], $e->context['hookTokenCategories'], $isHtml, $useSmarty); \CRM_Utils_Token::replaceGreetingTokens($e->string, NULL, $e->context['contact']['contact_id'], NULL, $useSmarty); } if ($useSmarty) { $smarty = \CRM_Core_Smarty::singleton(); $e->string = $smarty->fetch("string:" . $e->string); } }
/** * Generic file to retrieve all the constants and * pseudo constants used in CiviCRM * */ function civicrm_domain_get() { require_once 'CRM/Core/BAO/Domain.php'; $dao = CRM_Core_BAO_Domain::getDomain(); $values = array(); $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_domain'); require_once 'CRM/Core/BAO/Location.php'; $values['location'] = CRM_Core_BAO_Location::getValues($params, true); $address_array = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'state_province_id', 'postal_code', 'country_id', 'geo_code_1', 'geo_code_2'); require_once 'CRM/Core/OptionGroup.php'; $domain[$dao->id] = array('id' => $dao->id, 'domain_name' => $dao->name, 'description' => $dao->description, 'domain_email' => CRM_Utils_Array::value('email', $values['location']['email'][1]), 'domain_phone' => array('phone_type' => CRM_Core_OptionGroup::getLabel('phone_type', CRM_Utils_Array::value('phone_type_id', $values['location']['phone'][1])), 'phone' => CRM_Utils_Array::value('phone', $values['location']['phone'][1]))); foreach ($address_array as $value) { $domain[$dao->id]['domain_address'][$value] = CRM_Utils_Array::value($value, $values['location']['address'][1]); } list($domain[$dao->id]['from_name'], $domain[$dao->id]['from_email']) = CRM_Core_BAO_Domain::getNameAndEmail(); return $domain; }
/** * Singleton function used to manage this object. * * @param bool $loadFromDB * whether to load from the database. * @param bool $force * whether to force a reconstruction. * * @return CRM_Core_Config */ public static function &singleton($loadFromDB = TRUE, $force = FALSE) { if (self::$_singleton === NULL || $force) { $GLOBALS['civicrm_default_error_scope'] = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'handle')); $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'simpleHandler')); if (defined('E_DEPRECATED')) { error_reporting(error_reporting() & ~E_DEPRECATED); } self::$_singleton = new CRM_Core_Config(); \Civi\Core\Container::boot($loadFromDB); if ($loadFromDB && self::$_singleton->dsn) { $domain = \CRM_Core_BAO_Domain::getDomain(); \CRM_Core_BAO_ConfigSetting::applyLocale(\Civi::settings($domain->id), $domain->locales); unset($errorScope); CRM_Utils_Hook::config(self::$_singleton); self::$_singleton->authenticate(); // Extreme backward compat: $config binds to active domain at moment of setup. self::$_singleton->getSettings(); Civi::service('settings_manager')->useDefaults(); } } return self::$_singleton; }
/** * 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); } }
/** * 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; }
/** * Create a new forward event, create a new contact if necessary * * @param $job_id * @param $queue_id * @param $hash * @param $forward_email * @param null $fromEmail * @param null $comment * * @return bool */ public static function &forward($job_id, $queue_id, $hash, $forward_email, $fromEmail = NULL, $comment = NULL) { $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash); $successfulForward = FALSE; $contact_id = NULL; if (!$q) { return $successfulForward; } /* Find the email address/contact, if it exists */ $contact = CRM_Contact_BAO_Contact::getTableName(); $location = CRM_Core_BAO_Location::getTableName(); $email = CRM_Core_BAO_Email::getTableName(); $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName(); $job = CRM_Mailing_BAO_MailingJob::getTableName(); $mailing = CRM_Mailing_BAO_Mailing::getTableName(); $forward = self::getTableName(); $domain = CRM_Core_BAO_Domain::getDomain(); $dao = new CRM_Core_Dao(); $dao->query("\n SELECT {$contact}.id as contact_id,\n {$email}.id as email_id,\n {$contact}.do_not_email as do_not_email,\n {$queueTable}.id as queue_id\n FROM ({$email}, {$job} as temp_job)\n INNER JOIN {$contact}\n ON {$email}.contact_id = {$contact}.id\n LEFT JOIN {$queueTable}\n ON {$email}.id = {$queueTable}.email_id\n LEFT JOIN {$job}\n ON {$queueTable}.job_id = {$job}.id\n AND temp_job.mailing_id = {$job}.mailing_id\n WHERE {$queueTable}.job_id = {$job_id}\n AND {$email}.email = '" . CRM_Utils_Type::escape($forward_email, 'String') . "'"); $dao->fetch(); $transaction = new CRM_Core_Transaction(); if (isset($dao->queue_id) || isset($dao->do_not_email) && $dao->do_not_email == 1) { /* We already sent this mailing to $forward_email, or we should * never email this contact. Give up. */ return $successfulForward; } require_once 'api/api.php'; $contactParams = array('email' => $forward_email, 'version' => 3); $contactValues = civicrm_api('contact', 'get', $contactParams); $count = $contactValues['count']; if ($count == 0) { /* If the contact does not exist, create one. */ $formatted = array('contact_type' => 'Individual', 'version' => 3); $locationType = CRM_Core_BAO_LocationType::getDefault(); $value = array('email' => $forward_email, 'location_type_id' => $locationType->id); require_once 'CRM/Utils/DeprecatedUtils.php'; _civicrm_api3_deprecated_add_formatted_param($value, $formatted); $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP; $formatted['fixAddress'] = TRUE; $contact = civicrm_api('contact', 'create', $formatted); if (civicrm_error($contact)) { return $successfulForward; } $contact_id = $contact['id']; } $email = new CRM_Core_DAO_Email(); $email->email = $forward_email; $email->find(TRUE); $email_id = $email->id; if (!$contact_id) { $contact_id = $email->contact_id; } /* Create a new queue event */ $queue_params = array('email_id' => $email_id, 'contact_id' => $contact_id, 'job_id' => $job_id); $queue = CRM_Mailing_Event_BAO_Queue::create($queue_params); $forward = new CRM_Mailing_Event_BAO_Forward(); $forward->time_stamp = date('YmdHis'); $forward->event_queue_id = $queue_id; $forward->dest_queue_id = $queue->id; $forward->save(); $dao->reset(); $dao->query(" SELECT {$job}.mailing_id as mailing_id\n FROM {$job}\n WHERE {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer')); $dao->fetch(); $mailing_obj = new CRM_Mailing_BAO_Mailing(); $mailing_obj->id = $dao->mailing_id; $mailing_obj->find(TRUE); $config = CRM_Core_Config::singleton(); $mailer = $config->getMailer(); $recipient = NULL; $attachments = NULL; $message = $mailing_obj->compose($job_id, $queue->id, $queue->hash, $queue->contact_id, $forward_email, $recipient, FALSE, NULL, $attachments, TRUE, $fromEmail); //append comment if added while forwarding. if (count($comment)) { $message->_txtbody = CRM_Utils_Array::value('body_text', $comment) . $message->_txtbody; if (!empty($comment['body_html'])) { $message->_htmlbody = $comment['body_html'] . '<br />---------------Original message---------------------<br />' . $message->_htmlbody; } } $body = $message->get(); $headers = $message->headers(); $result = NULL; if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $result = $mailer->send($recipient, $headers, $body); unset($errorScope); } $params = array('event_queue_id' => $queue->id, 'job_id' => $job_id, 'hash' => $queue->hash); if (is_a($result, 'PEAR_Error')) { /* Register the bounce event */ $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage())); CRM_Mailing_Event_BAO_Bounce::create($params); } else { $successfulForward = TRUE; /* Register the delivery event */ CRM_Mailing_Event_BAO_Delivered::create($params); } $transaction->commit(); return $successfulForward; }
/** * Format an address string from address fields and a format string. * * Format an address basing on the address fields provided. * Use Setting's address_format if there's no format specified. * * @param array $fields * The address fields. * @param string $format * The desired address format. * @param bool $microformat * If true indicates, the address to be built in hcard-microformat standard. * @param bool $mailing * If true indicates, the call has been made from mailing label. * @param bool $individualFormat * If true indicates, the call has been made for the contact of type 'individual'. * * @param null $tokenFields * * @return string * formatted address string * */ public static function format($fields, $format = NULL, $microformat = FALSE, $mailing = FALSE, $individualFormat = FALSE, $tokenFields = NULL) { static $config = NULL; if (!$format) { $format = Civi::settings()->get('address_format'); } if ($mailing) { $format = Civi::settings()->get('mailing_format'); } $formatted = $format; $fullPostalCode = CRM_Utils_Array::value('postal_code', $fields); if (!empty($fields['postal_code_suffix'])) { $fullPostalCode .= "-{$fields['postal_code_suffix']}"; } // make sure that some of the fields do have values $emptyFields = array('supplemental_address_1', 'supplemental_address_2', 'state_province_name', 'county'); foreach ($emptyFields as $f) { if (!isset($fields[$f])) { $fields[$f] = NULL; } } //CRM-16876 Display countries in all caps when in mailing mode. if ($mailing && !empty($fields['country'])) { if (Civi::settings()->get('hideCountryMailingLabels')) { $domain = CRM_Core_BAO_Domain::getDomain(); $domainLocation = CRM_Core_BAO_Location::getValues(array('contact_id' => $domain->contact_id)); $domainAddress = $domainLocation['address'][1]; $domainCountryId = $domainAddress['country_id']; if ($fields['country'] == CRM_Core_PseudoConstant::country($domainCountryId)) { $fields['country'] = NULL; } else { //Capitalization display on uppercase to contries with special characters $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER, "UTF-8"); } } else { $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER, "UTF-8"); } } $contactName = CRM_Utils_Array::value('display_name', $fields); if (!$individualFormat) { if (isset($fields['id'])) { $type = CRM_Contact_BAO_Contact::getContactType($fields['id']); } else { $type = 'Individual'; } if ($type == 'Individual') { $contactName = CRM_Utils_Array::value('addressee_display', $fields); } } if (!$microformat) { // replacements in case of Individual Name Format $replacements = array('contact.display_name' => CRM_Utils_Array::value('display_name', $fields), 'contact.individual_prefix' => CRM_Utils_Array::value('individual_prefix', $fields), 'contact.formal_title' => CRM_Utils_Array::value('formal_title', $fields), 'contact.first_name' => CRM_Utils_Array::value('first_name', $fields), 'contact.middle_name' => CRM_Utils_Array::value('middle_name', $fields), 'contact.last_name' => CRM_Utils_Array::value('last_name', $fields), 'contact.individual_suffix' => CRM_Utils_Array::value('individual_suffix', $fields), 'contact.address_name' => CRM_Utils_Array::value('address_name', $fields), 'contact.street_address' => CRM_Utils_Array::value('street_address', $fields), 'contact.supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', $fields), 'contact.supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', $fields), 'contact.city' => CRM_Utils_Array::value('city', $fields), 'contact.state_province_name' => CRM_Utils_Array::value('state_province_name', $fields), 'contact.county' => CRM_Utils_Array::value('county', $fields), 'contact.state_province' => CRM_Utils_Array::value('state_province', $fields), 'contact.postal_code' => $fullPostalCode, 'contact.country' => CRM_Utils_Array::value('country', $fields), 'contact.world_region' => CRM_Utils_Array::value('world_region', $fields), 'contact.geo_code_1' => CRM_Utils_Array::value('geo_code_1', $fields), 'contact.geo_code_2' => CRM_Utils_Array::value('geo_code_2', $fields), 'contact.current_employer' => CRM_Utils_Array::value('current_employer', $fields), 'contact.nick_name' => CRM_Utils_Array::value('nick_name', $fields), 'contact.email' => CRM_Utils_Array::value('email', $fields), 'contact.im' => CRM_Utils_Array::value('im', $fields), 'contact.do_not_email' => CRM_Utils_Array::value('do_not_email', $fields), 'contact.do_not_phone' => CRM_Utils_Array::value('do_not_phone', $fields), 'contact.do_not_mail' => CRM_Utils_Array::value('do_not_mail', $fields), 'contact.do_not_sms' => CRM_Utils_Array::value('do_not_sms', $fields), 'contact.do_not_trade' => CRM_Utils_Array::value('do_not_trade', $fields), 'contact.job_title' => CRM_Utils_Array::value('job_title', $fields), 'contact.birth_date' => CRM_Utils_Array::value('birth_date', $fields), 'contact.gender' => CRM_Utils_Array::value('gender', $fields), 'contact.is_opt_out' => CRM_Utils_Array::value('is_opt_out', $fields), 'contact.preferred_mail_format' => CRM_Utils_Array::value('preferred_mail_format', $fields), 'contact.phone' => CRM_Utils_Array::value('phone', $fields), 'contact.home_URL' => CRM_Utils_Array::value('home_URL', $fields), 'contact.contact_source' => CRM_Utils_Array::value('contact_source', $fields), 'contact.external_identifier' => CRM_Utils_Array::value('external_identifier', $fields), 'contact.contact_id' => CRM_Utils_Array::value('id', $fields), 'contact.household_name' => CRM_Utils_Array::value('display_name', $fields), 'contact.organization_name' => CRM_Utils_Array::value('display_name', $fields), 'contact.legal_name' => CRM_Utils_Array::value('legal_name', $fields), 'contact.preferred_communication_method' => CRM_Utils_Array::value('preferred_communication_method', $fields), 'contact.communication_style' => CRM_Utils_Array::value('communication_style', $fields), 'contact.addressee' => CRM_Utils_Array::value('addressee_display', $fields), 'contact.email_greeting' => CRM_Utils_Array::value('email_greeting_display', $fields), 'contact.postal_greeting' => CRM_Utils_Array::value('postal_greeting_display', $fields)); } else { $replacements = array('contact.address_name' => "<span class=\"address-name\">" . $fields['address_name'] . "</span>", 'contact.street_address' => "<span class=\"street-address\">" . $fields['street_address'] . "</span>", 'contact.supplemental_address_1' => "<span class=\"extended-address\">" . $fields['supplemental_address_1'] . "</span>", 'contact.supplemental_address_2' => $fields['supplemental_address_2'], 'contact.city' => "<span class=\"locality\">" . $fields['city'] . "</span>", 'contact.state_province_name' => "<span class=\"region\">" . $fields['state_province_name'] . "</span>", 'contact.county' => "<span class=\"region\">" . $fields['county'], 'contact.state_province' => "<span class=\"region\">" . $fields['state_province'] . "</span>", 'contact.postal_code' => "<span class=\"postal-code\">" . $fullPostalCode . "</span>", 'contact.country' => "<span class=\"country-name\">" . $fields['country'] . "</span>", 'contact.world_region' => "<span class=\"region\">" . $fields['world_region'] . "</span>"); // erase all empty ones, so we dont get blank lines foreach (array_keys($replacements) as $key) { $exactKey = substr($key, 0, 8) == 'contact.' ? substr($key, 8) : $key; if ($key != 'contact.postal_code' && CRM_Utils_Array::value($exactKey, $fields) == NULL) { $replacements[$key] = ''; } } if (empty($fullPostalCode)) { $replacements['contact.postal_code'] = ''; } } // replacements in case of Custom Token if (stristr($formatted, 'custom_')) { $customToken = array_keys($fields); foreach ($customToken as $value) { if (substr($value, 0, 7) == 'custom_') { $replacements["contact.{$value}"] = $fields["{$value}"]; } } } // also sub all token fields if ($tokenFields) { foreach ($tokenFields as $token) { $replacements["{$token}"] = CRM_Utils_Array::value("{$token}", $fields); } } // for every token, replace {fooTOKENbar} with fooVALUEbar if // the value is not empty, otherwise drop the whole {fooTOKENbar} foreach ($replacements as $token => $value) { if ($value && is_string($value) || is_numeric($value)) { $formatted = preg_replace("/{([^{}]*)\\b{$token}\\b([^{}]*)}/u", "\${1}{$value}\${2}", $formatted); } else { $formatted = preg_replace("/{[^{}]*\\b{$token}\\b[^{}]*}/u", '', $formatted); } } // drop any {...} constructs from lines' ends if (!$microformat) { $formatted = "\n{$formatted}\n"; } else { if ($microformat == 1) { $formatted = "\n<div class=\"location vcard\"><span class=\"adr\">\n{$formatted}</span></div>\n"; } else { $formatted = "\n<div class=\"vcard\"><span class=\"adr\">{$formatted}</span></div>\n"; } } $formatted = preg_replace('/\\n{[^{}]*}/u', "\n", $formatted); $formatted = preg_replace('/{[^{}]*}\\n/u', "\n", $formatted); // if there are any 'sibling' {...} constructs, replace them with the // contents of the first one; for example, when there's no state_province: // 1. {city}{, }{state_province}{ }{postal_code} // 2. San Francisco{, }{ }12345 // 3. San Francisco, 12345 $formatted = preg_replace('/{([^{}]*)}({[^{}]*})+/u', '\\1', $formatted); // drop any remaining curly braces leaving their contents $formatted = str_replace(array('{', '}'), '', $formatted); // drop any empty lines left after the replacements $formatted = preg_replace('/^[ \\t]*[\\r\\n]+/m', '', $formatted); if (!$microformat) { $finalFormatted = $formatted; } else { // remove \n from each line and only add at the end // this hack solves formatting issue, when we convert nl2br $lines = array(); $count = 1; $finalFormatted = NULL; $formattedArray = explode("\n", $formatted); $formattedArray = array_filter($formattedArray); foreach ($formattedArray as $line) { $line = trim($line); if ($line) { if ($count > 1 && $count < count($formattedArray)) { $line = "{$line}\n"; } $finalFormatted .= $line; $count++; } } } return $finalFormatted; }
/** * @param $contactId * @param $to * @param $scheduleID * @param $from * @param $tokenParams * * @return bool|null * @throws CRM_Core_Exception */ static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) { $email = $to['email']; $phoneNumber = $to['phone']; $schedule = new CRM_Core_DAO_ActionSchedule(); $schedule->id = $scheduleID; $domain = CRM_Core_BAO_Domain::getDomain(); $result = NULL; $hookTokens = array(); if ($schedule->find(TRUE)) { $body_text = $schedule->body_text; $body_html = $schedule->body_html; $sms_body_text = $schedule->sms_body_text; $body_subject = $schedule->subject; if (!$body_text) { $body_text = CRM_Utils_String::htmlToText($body_html); } $params = array(array('contact_id', '=', $contactId, 0, 0)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params); //CRM-4524 $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { return NULL; } // merge activity tokens with contact array $contact = array_merge($contact, $tokenParams); //CRM-5734 CRM_Utils_Hook::tokenValues($contact, $contactId); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text'); foreach ($type as $bodyType => $value) { $dummy_mail = new CRM_Mailing_BAO_Mailing(); if ($bodyType == 'sms_body_text') { $dummy_mail->body_text = ${$bodyType}; } else { $dummy_mail->{${$bodyType}} = ${$bodyType}; } $tokens = $dummy_mail->getTokens(); if (${$bodyType}) { CRM_Utils_Token::replaceGreetingTokens(${$bodyType}, NULL, $contact['contact_id']); ${$bodyType} = CRM_Utils_Token::replaceDomainTokens(${$bodyType}, $domain, TRUE, $tokens[$value], TRUE); ${$bodyType} = CRM_Utils_Token::replaceContactTokens(${$bodyType}, $contact, FALSE, $tokens[$value], FALSE, TRUE); ${$bodyType} = CRM_Utils_Token::replaceComponentTokens(${$bodyType}, $contact, $tokens[$value], TRUE, FALSE); ${$bodyType} = CRM_Utils_Token::replaceHookTokens(${$bodyType}, $contact, $categories, TRUE); } } $html = $body_html; $text = $body_text; $sms_text = $sms_body_text; $smarty = CRM_Core_Smarty::singleton(); foreach (array('text', 'html', 'sms_text') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } $matches = array(); preg_match_all('/(?<!\\{|\\\\)\\{(\\w+\\.\\w+)\\}(?!\\})/', $body_subject, $matches, PREG_PATTERN_ORDER); $subjectToken = NULL; if ($matches[1]) { foreach ($matches[1] as $token) { list($type, $name) = preg_split('/\\./', $token, 2); if ($name) { if (!isset($subjectToken[$type])) { $subjectToken[$type] = array(); } $subjectToken[$type][] = $name; } } } $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE); $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE); $messageSubject = $smarty->fetch("string:{$messageSubject}"); if ($schedule->mode == 'SMS' or $schedule->mode == 'User_Preference') { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID') ? $session->get('userID') : $contactId; $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id, 'activity_subject' => $messageSubject); $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS', 'name'); $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'subject' => $messageSubject, 'details' => $sms_text, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name')); $activity = CRM_Activity_BAO_Activity::create($activityParams); CRM_Activity_BAO_Activity::sendSMSMessage($contactId, $sms_text, $html, $smsParams, $activity->id, $userID); } if ($schedule->mode == 'Email' or $schedule->mode == 'User_Preference') { // set up the parameters for CRM_Utils_Mail::send $mailParams = array('groupName' => 'Scheduled Reminder Sender', 'from' => $from, 'toName' => $contact['display_name'], 'toEmail' => $email, 'subject' => $messageSubject, 'entity' => 'action_schedule', 'entity_id' => $scheduleID); if (!$html || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both') { // render the & entities in text mode, so that the links work $mailParams['text'] = str_replace('&', '&', $text); } if ($html && ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both')) { $mailParams['html'] = $html; } $result = CRM_Utils_Mail::send($mailParams); } } $schedule->free(); return $result; }
/** * Cancel this participant and finish, send cancellation email. At this point no * auto-cancellation of payment is handled, so payment needs to be manually cancelled * * return @void */ public function cancelParticipant($params) { //set participant record status to Cancelled, refund payment if possible // send email to participant and admin, and log Activity $value = array(); $value['id'] = $this->_participant_id; $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")); $value['status_id'] = $cancelledId; CRM_Event_BAO_Participant::create($value); $domainValues = array(); $domain = CRM_Core_BAO_Domain::getDomain(); $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens()); foreach ($tokens['domain'] as $token) { $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain); } $participantRoles = array(); $participantRoles = CRM_Event_PseudoConstant::participantRole(); $participantDetails = array(); $query = "SELECT * FROM civicrm_participant WHERE id = {$this->_participant_id}"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id); } $eventDetails = array(); $eventParams = array('id' => $this->_event_id); CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]); //get default participant role. $eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles); //get the location info $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event'); $eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE); //get contact details $contactIds[$this->_contact_id] = $this->_contact_id; list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant'); foreach ($currentContactDetails as $contactId => $contactValues) { $contactDetails[$this->_contact_id] = $contactValues; } //send a 'cancelled' email to user, and cc the event's cc_confirm email $mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_participant_id, $participantDetails[$this->_participant_id], $eventDetails[$this->_event_id], $contactDetails[$this->_contact_id], $domainValues, "Cancelled", ""); $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name)); $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email)); CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success'); $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true"); CRM_Utils_System::redirect($url); }
/** * Send a response email informing the contact of the groups from which he. * has been unsubscribed. * * @param string $queue_id * The queue event ID. * @param array $groups * List of group IDs. * @param bool $is_domain * Is this domain-level?. * @param int $job * The job ID. */ public static function send_unsub_response($queue_id, $groups, $is_domain = FALSE, $job) { $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); $jobObject = new CRM_Mailing_BAO_MailingJob(); $jobTable = $jobObject->getTableName(); $mailingObject = new CRM_Mailing_DAO_Mailing(); $mailingTable = $mailingObject->getTableName(); $contactsObject = new CRM_Contact_DAO_Contact(); $contacts = $contactsObject->getTableName(); $emailObject = new CRM_Core_DAO_Email(); $email = $emailObject->getTableName(); $queueObject = new CRM_Mailing_Event_BAO_Queue(); $queue = $queueObject->getTableName(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $dao = new CRM_Mailing_BAO_Mailing(); $dao->query(" SELECT * FROM {$mailingTable}\n INNER JOIN {$jobTable} ON\n {$jobTable}.mailing_id = {$mailingTable}.id\n WHERE {$jobTable}.id = {$job}"); $dao->fetch(); $component = new CRM_Mailing_BAO_Component(); if ($is_domain) { $component->id = $dao->optout_id; } else { $component->id = $dao->unsubscribe_id; } $component->find(TRUE); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$contacts}.id as contact_id,\n {$email}.email as email,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); if ($groups) { foreach ($groups as $key => $value) { if (!$value) { unset($groups[$key]); } } } $message = new Mail_mime("\n"); list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email); $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceUnsubscribeTokens($html, $domain, $groups, TRUE, $eq->contact_id, $eq->hash); $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, NULL, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceUnsubscribeTokens($text, $domain, $groups, FALSE, $eq->contact_id, $eq->hash); $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, NULL, $tokens['text']); $message->setTxtBody($text); } $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); CRM_Mailing_BAO_Mailing::addMessageIdHeader($headers, 'u', $job, $queue_id, $eq->hash); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); $mailer = \Civi::service('pear_mail'); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($eq->email, $h, $b); unset($errorScope); } }
/** * 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; }
/** * Send an email from the specified template based on an array of params. * * @param array $params * A string-keyed array of function params, see function body for details. * * @return array * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ public static function sendTemplate($params) { $defaults = array('groupName' => NULL, 'valueName' => NULL, 'messageTemplateID' => NULL, 'contactId' => NULL, 'tplParams' => array(), 'from' => NULL, 'toName' => NULL, 'toEmail' => NULL, 'cc' => NULL, 'bcc' => NULL, 'replyTo' => NULL, 'attachments' => NULL, 'isTest' => FALSE, 'PDFFilename' => NULL); $params = array_merge($defaults, $params); CRM_Utils_Hook::alterMailParams($params, 'messageTemplate'); if ((!$params['groupName'] || !$params['valueName']) && !$params['messageTemplateID']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing.")); } if ($params['messageTemplateID']) { // fetch the three elements from the db based on id $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt WHERE mt.id = %1 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['messageTemplateID'], 'String')); } else { // fetch the three elements from the db based on option_group and option_value names $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt JOIN civicrm_option_value ov ON workflow_id = ov.id JOIN civicrm_option_group og ON ov.option_group_id = og.id WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String')); } $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { if ($params['messageTemplateID']) { CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID']))); } else { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } } $mailContent = array('subject' => $dao->subject, 'text' => $dao->text, 'html' => $dao->html, 'format' => $dao->format); $dao->free(); CRM_Utils_Hook::alterMailContent($mailContent); // add the test banner (if requested) if ($params['isTest']) { $query = "SELECT msg_subject subject, msg_text text, msg_html html\n FROM civicrm_msg_template mt\n JOIN civicrm_option_value ov ON workflow_id = ov.id\n JOIN civicrm_option_group og ON ov.option_group_id = og.id\n WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1"; $testDao = CRM_Core_DAO::executeQuery($query); $testDao->fetch(); $mailContent['subject'] = $testDao->subject . $mailContent['subject']; $mailContent['text'] = $testDao->text . $mailContent['text']; $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']); $testDao->free(); } // replace tokens in the three elements (in subject as if it was the text body) $domain = CRM_Core_BAO_Domain::getDomain(); $hookTokens = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->subject = $mailContent['subject']; $mailing->body_text = $mailContent['text']; $mailing->body_html = $mailContent['html']; $tokens = $mailing->getTokens(); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $contactID = CRM_Utils_Array::value('contactId', $params); if ($contactID) { $contactParams = array('contact_id' => $contactID); $returnProperties = array(); if (isset($tokens['subject']['contact'])) { foreach ($tokens['subject']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['text']['contact'])) { foreach ($tokens['text']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['html']['contact'])) { foreach ($tokens['html']['contact'] as $name) { $returnProperties[$name] = 1; } } // @todo CRM-17253 don't resolve contact details if there are no tokens // effectively comment out this next (performance-expensive) line // but unfortunately testing is a bit think on the ground to that needs to // be added. list($contact) = CRM_Utils_Token::getTokenDetails($contactParams, $returnProperties, FALSE, FALSE, NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contact[$contactID]; } $mailContent['subject'] = CRM_Utils_Token::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['text'], TRUE); $mailContent['text'] = CRM_Utils_Token::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE); $mailContent['html'] = CRM_Utils_Token::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE); if ($contactID) { $mailContent['subject'] = CRM_Utils_Token::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['text'], FALSE, TRUE); $mailContent['text'] = CRM_Utils_Token::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE); $mailContent['html'] = CRM_Utils_Token::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE); $contactArray = array($contactID => $contact); CRM_Utils_Hook::tokenValues($contactArray, array($contactID), NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contactArray[$contactID]; $mailContent['subject'] = CRM_Utils_Token::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE); $mailContent['text'] = CRM_Utils_Token::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE); $mailContent['html'] = CRM_Utils_Token::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE); } // strip whitespace from ends and turn into a single line $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}"; // parse the three elements with Smarty $smarty = CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}"); } // send the template, honouring the target user’s preferences (if any) $sent = FALSE; // create the params array $params['subject'] = $mailContent['subject']; $params['text'] = $mailContent['text']; $params['html'] = $mailContent['html']; if ($params['toEmail']) { $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $params['text'] = NULL; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $params['html'] = NULL; } $config = CRM_Core_Config::singleton(); if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) { $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']); if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']); } $pdf_filename = ''; if ($config->doNotAttachPDFReceipt && $params['PDFFilename'] && $params['html']) { if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']); if (isset($params['tplParams']['email_comment'])) { $params['html'] = $params['tplParams']['email_comment']; $params['text'] = strip_tags($params['tplParams']['email_comment']); } } $sent = CRM_Utils_Mail::send($params); if ($pdf_filename) { unlink($pdf_filename); } } return array($sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']); }
/** * Get the uf_id given a contact_id. * * @param int $contactID * ID of the contact for which related uf_id is required. * * @return int * uf_id of the given contact_id on success, null otherwise */ public static function getUFId($contactID) { if (!isset($contactID)) { return NULL; } $domain = CRM_Core_BAO_Domain::getDomain(); $ufmatch = new CRM_Core_DAO_UFMatch(); $ufmatch->contact_id = $contactID; $ufmatch->domain_id = $domain->id; if ($ufmatch->find(TRUE)) { return $ufmatch->uf_id; } return NULL; }
/** * global validation rules for the form * * @param array $fields posted values of the form * * @return array list of errors to be posted back to the form * @static * @access public */ static function formRule($fields) { $errors = array(); // Validate include/exclude groups, mailings // Start if (isset($fields['includeGroups']) && isset($fields['excludeGroups']) && is_array($fields['excludeGroups'])) { $checkGroups = array(); $checkGroups = in_array($fields['includeGroups'], $fields['excludeGroups']); if (!empty($checkGroups)) { $errors['excludeGroups'] = ts('Cannot have same groups in Include Group(s) and Exclude Group(s).'); } } if (isset($fields['includeMailings']) && is_array($fields['includeMailings']) && isset($fields['excludeMailings']) && is_array($fields['excludeMailings'])) { $checkMailings = array(); $checkMailings = array_intersect($fields['includeMailings'], $fields['excludeMailings']); if (!empty($checkMailings)) { $errors['excludeMailings'] = ts('Cannot have same mail in Include mailing(s) and Exclude mailing(s).'); } } if (!empty($fields['search_id']) && empty($fields['group_id'])) { $errors['group_id'] = ts('You must select a group to filter on'); } if (empty($fields['search_id']) && !empty($fields['group_id'])) { $errors['search_id'] = ts('You must select a search to filter'); } // End // Validate message template html/text // Start $errors = array(); $template = CRM_Core_Smarty::singleton(); if (isset($fields['html_message'])) { $htmlMessage = str_replace(array("\n", "\r"), ' ', $fields['html_message']); $htmlMessage = str_replace("'", "\\'", $htmlMessage); $template->assign('htmlContent', $htmlMessage); } $domain = CRM_Core_BAO_Domain::getDomain(); $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 ($fields["{$part}_id"]) { //echo "found<p>"; $component = new CRM_Mailing_BAO_Component(); $component->id = $fields["{$part}_id"]; $component->find(TRUE); ${$part}['textFile'] = $component->body_text; ${$part}['htmlFile'] = $component->body_html; $component->free(); } else { ${$part}['htmlFile'] = ${$part}['textFile'] = ''; } } if (!CRM_Utils_Array::value('text_message', $fields) && !CRM_Utils_Array::value('html_message', $fields)) { $errors['html_message'] = ts('Please provide either a Text or HTML formatted message - or both.'); } foreach (array('text', 'html') as $file) { $str = $fields[$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 */ $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 . '_message'] = 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>'; } } // End return empty($errors) ? TRUE : $errors; }
/** * Send an email from the specified template based on an array of params * * @param array $params a string-keyed array of function params, see function body for details * * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ static function sendTemplate($params) { $defaults = array('groupName' => null, 'valueName' => null, 'contactId' => null, 'tplParams' => array(), 'from' => null, 'toName' => null, 'toEmail' => null, 'cc' => null, 'bcc' => null, 'replyTo' => null, 'attachments' => null, 'isTest' => false); $params = array_merge($defaults, $params); if (!$params['groupName'] or !$params['valueName']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value missing.")); } // fetch the three elements from the db based on option_group and option_value names $query = 'SELECT msg_subject subject, msg_text text, msg_html html FROM civicrm_msg_template mt JOIN civicrm_option_value ov ON workflow_id = ov.id JOIN civicrm_option_group og ON ov.option_group_id = og.id WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String')); $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } $subject = $dao->subject; $text = $dao->text; $html = $dao->html; // add the test banner (if requested) if ($params['isTest']) { $query = "SELECT msg_subject subject, msg_text text, msg_html html\n FROM civicrm_msg_template mt\n JOIN civicrm_option_value ov ON workflow_id = ov.id\n JOIN civicrm_option_group og ON ov.option_group_id = og.id\n WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1"; $testDao = CRM_Core_DAO::executeQuery($query); $testDao->fetch(); $subject = $testDao->subject . $subject; $text = $testDao->text . $text; $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html); } // replace tokens in the three elements require_once 'CRM/Utils/Token.php'; require_once 'CRM/Core/BAO/Domain.php'; require_once 'api/v2/Contact.php'; require_once 'CRM/Mailing/BAO/Mailing.php'; $domain = CRM_Core_BAO_Domain::getDomain(); if ($params['contactId']) { $contactParams = array('contact_id' => $params['contactId']); $contact =& civicrm_contact_get($contactParams); } // replace tokens in subject as if it was the text body foreach (array('subject' => 'text', 'text' => 'text', 'html' => 'html') as $type => $tokenType) { if (!${$type}) { continue; } // skip all of the below if the given part is missing $bodyType = "body_{$tokenType}"; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->{$bodyType} = ${$type}; $tokens = $mailing->getTokens(); ${$type} = CRM_Utils_Token::replaceDomainTokens(${$type}, $domain, true, $tokens[$tokenType]); if ($params['contactId']) { ${$type} = CRM_Utils_Token::replaceContactTokens(${$type}, $contact, false, $tokens[$tokenType]); } } // strip whitespace from ends and turn into a single line $subject = "{strip}{$subject}{/strip}"; // parse the three elements with Smarty require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); $smarty =& CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } // send the template, honouring the target user’s preferences (if any) $sent = false; if ($params['toEmail']) { $contactParams = array('email' => $params['toEmail']); $contact =& civicrm_contact_get($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $text = null; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $html = null; } require_once 'CRM/Utils/Mail.php'; $sent = CRM_Utils_Mail::send($params['from'], $params['toName'], $params['toEmail'], $subject, $text, $params['cc'], $params['bcc'], $params['replyTo'], $html, $params['attachments']); } return array($sent, $subject, $text, $html); }
/** * This function preserve the civicrm_domain.email_name and civicrm_domain.email_address * as a default option value into "from_email_address" option group * and drop these columns from civicrm_domain table. * @access public * * @return void */ function upgradeDomainFromEmail() { $query = "\nSELECT id\n FROM civicrm_option_group\n WHERE name = 'from_Email_address'"; $fmaGroup = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); $fmaGroupId = NULL; if ($fmaGroup->fetch()) { $fmaGroupId = $fmaGroup->id; } else { //insert 'from_mailing_address' option group. $query = "\nINSERT INTO civicrm_option_group ( name, description, is_reserved, is_active )\nVALUES ('from_email_address', 'From Email Address', 0, 1)"; CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); //get the group id. $query = "\nSELECT id\n FROM civicrm_option_group\n WHERE name = 'from_email_address'"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); if ($dao->fetch()) { $fmaGroupId = $dao->id; } } if ($fmaGroupId) { //get domain from email address and name as default value. $domain = CRM_Core_BAO_Domain::getDomain(); $domain->selectAdd(); $domain->selectAdd('email_name', 'email_address'); $domain->find(TRUE); $formEmailAddress = '"' . $domain->email_name . '"<' . $domain->email_address . '>'; //first check given domain email address exist in option //value, if yes make it as domain email address by making //it as default from email address.. //get the existing from email address. $optionValues = array(); $grpParams['name'] = 'from_email_address'; CRM_Core_OptionValue::getValues($grpParams, $optionValues); $maxVal = $maxWt = 1; $insertEmailAddress = TRUE; if (!empty($optionValues)) { //make existing is_default = 0 $query = "\nUPDATE civicrm_option_value\n SET is_default = 0\n WHERE option_group_id = %1"; $params = array(1 => array($fmaGroupId, 'Integer')); CRM_Core_DAO::executeQuery($query, $params); //if domain from name and email exist as name or label in option value //table need to preserve that name and label and take care that label //and name both remain unique in db. $labelValues = $nameValues = array(); foreach ($optionValues as $id => $value) { if ($value['label'] == $formEmailAddress) { $labelValues = $value; } elseif ($value['name'] == $formEmailAddress) { $nameValues = $value; } } //as we consider label so label should preserve. $updateValues = array(); if (!empty($labelValues)) { $updateValues = $labelValues; } //if matching name found need to preserve it. if (!empty($nameValues)) { //copy domain from email address as label. if (empty($updateValues)) { $updateValues = $nameValues; $updateValues['label'] = $formEmailAddress; } else { //since name is also imp so preserve it //as name for domain email address record. $updateValues['name'] = $nameValues['name']; //name is unique so drop name value record. //since we transfer this name to found label record. CRM_Core_BAO_OptionValue::del($nameValues['id']); } } if (!empty($updateValues)) { $insertEmailAddress = FALSE; //update label/name found record w/ manupulated values. $updateValues['is_active'] = $updateValues['is_default'] = 1; $optionValue = new CRM_Core_DAO_OptionValue(); $optionValue->copyValues($updateValues); $optionValue->save(); } //get the max value and wt. if ($insertEmailAddress) { $query = "\nSELECT max(ROUND(civicrm_option_value.value)) as maxVal,\n max(civicrm_option_value.weight) as maxWt\n FROM civicrm_option_value, civicrm_option_group\n WHERE civicrm_option_group.name = 'from_Email_address'\n AND civicrm_option_value.option_group_id = civicrm_option_group.id\nGROUP BY civicrm_option_group.id"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); if ($dao->fetch()) { $maxWt += $dao->maxWt; $maxVal += $dao->maxVal; } } } if ($insertEmailAddress) { //insert domain from email address and name. $query = "\nINSERT INTO `civicrm_option_value`\n (`option_group_id`, `label`, `value`, `name` , `grouping`, `filter`, `is_default`,\n `weight`, `description`, `is_optgroup`, `is_reserved`, `is_active`, `component_id`)\n VALUES ( %1, %2, %3, %2, NULL, 0, 1, %4, 'Default domain email address and from name.', 0, 0, 1, NULL)"; $params = array(1 => array($fmaGroupId, 'Integer'), 2 => array($formEmailAddress, 'String'), 3 => array($maxVal, 'Integer'), 4 => array($maxWt, 'Integer')); CRM_Core_DAO::executeQuery($query, $params); } //drop civicrm_domain.email_name and //civicrm_domain.email_address. $query = "\nALTER TABLE `civicrm_domain`\n DROP `email_name`,\n DROP `email_address`"; CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); } }
/** * * getTokenData receives a token from an email * and returns the appropriate data for the token */ private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) { $type = $token_a['type']; $token = $token_a['token']; $data = $token; $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE; if ($type == 'embedded_url') { $embed_data = array(); foreach ($token as $t) { $embed_data[] = $this->getTokenData($t, $html = FALSE, $contact, $verp, $urls, $event_queue_id); } $numSlices = count($embed_data); $url = ''; for ($i = 0; $i < $numSlices; $i++) { $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}"; } if (isset($token_a['embed_parts'][$numSlices])) { $url .= $token_a['embed_parts'][$numSlices]; } // add trailing quote since we've gobbled it up in a previous regex // function getPatterns, line 431 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) { $url .= "'"; } elseif (preg_match('/^href[ ]*=[ ]*\\"/', $url)) { $url .= '"'; } $data = $url; } elseif ($type == 'url') { if ($this->url_tracking) { $data = CRM_Mailing_BAO_TrackableURL::getTrackerURL($token, $this->id, $event_queue_id); if (!empty($html)) { $data = htmlentities($data, ENT_NOQUOTES); } } else { $data = $token; } } elseif ($type == 'contact') { $data = CRM_Utils_Token::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty); } elseif ($type == 'action') { $data = CRM_Utils_Token::getActionTokenReplacement($token, $verp, $urls, $html); } elseif ($type == 'domain') { $domain = CRM_Core_BAO_Domain::getDomain(); $data = CRM_Utils_Token::getDomainTokenReplacement($token, $domain, $html); } elseif ($type == 'mailing') { if ($token == 'name') { $data = $this->name; } elseif ($token == 'group') { $groups = $this->getGroupNames(); $data = implode(', ', $groups); } } else { $data = CRM_Utils_Array::value("{$type}.{$token}", $contact); } return $data; }
/** * Run dashboard * * @return void * @access public */ function run() { // Add dashboard js and css $resources = CRM_Core_Resources::singleton(); $resources->addScriptFile('civicrm', 'packages/jquery/plugins/jquery.dashboard.js', 0, 'html-header', FALSE); $resources->addStyleFile('civicrm', 'packages/jquery/css/dashboard.css'); $config = CRM_Core_Config::singleton(); // Add dashlet-specific js files // TODO: Need a much better way of managing on-the-fly js requirements. Require.js perhaps? // Checking if a specific dashlet is enabled is a pain and including the js here sucks anyway // So here's a compromise: if (in_array('CiviCase', $config->enableComponents)) { $resources->addScriptFile('civicrm', 'templates/CRM/Case/Form/ActivityChangeStatus.js'); } $resetCache = CRM_Utils_Request::retrieve('resetCache', 'Positive', CRM_Core_DAO::$_nullObject); CRM_Utils_System::setTitle(ts('CiviCRM Home')); $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); if ($resetCache) { CRM_Core_BAO_Dashboard::resetDashletCache($contactID); } // call hook to get html from other modules // ignored but needed to prevent warnings $contentPlacement = CRM_Utils_Hook::DASHBOARD_BELOW; $html = CRM_Utils_Hook::dashboard($contactID, $contentPlacement); if (is_array($html)) { $this->assign_by_ref('hookContent', $html); $this->assign('hookContentPlacement', $contentPlacement); } //check that default FROM email address, owner (domain) organization name and default mailbox are configured. $fromEmailOK = TRUE; $ownerOrgOK = TRUE; $defaultMailboxOK = TRUE; // Don't put up notices if user doesn't have administer CiviCRM permission if (CRM_Core_Permission::check('administer CiviCRM')) { $destination = CRM_Utils_System::url('civicrm/dashboard', 'reset=1', FALSE, NULL, FALSE); $destination = urlencode($destination); list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE); if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') { $fixEmailUrl = CRM_Utils_System::url("civicrm/admin/domain", "action=update&reset=1&civicrmDestination={$destination}"); $this->assign('fixEmailUrl', $fixEmailUrl); $fromEmailOK = FALSE; } $domain = CRM_Core_BAO_Domain::getDomain(); $domainName = $domain->name; if (!$domainName || $domainName == 'Default Domain Name') { $fixOrgUrl = CRM_Utils_System::url("civicrm/admin/domain", "action=update&reset=1&civicrmDestination={$destination}"); $this->assign('fixOrgUrl', $fixOrgUrl); $ownerOrgOK = FALSE; } if (in_array('CiviMail', $config->enableComponents) && CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") { $fixDefaultMailbox = CRM_Utils_System::url('civicrm/admin/mailSettings', "reset=1&civicrmDestination={$destination}"); $this->assign('fixDefaultMailbox', $fixDefaultMailbox); $defaultMailboxOK = FALSE; } } $this->assign('fromEmailOK', $fromEmailOK); $this->assign('ownerOrgOK', $ownerOrgOK); $this->assign('defaultMailboxOK', $defaultMailboxOK); $communityMessages = CRM_Core_CommunityMessages::create(); if ($communityMessages->isEnabled()) { $message = $communityMessages->pick(); if ($message) { $this->assign('communityMessages', $communityMessages->evalMarkup($message['markup'])); } } return parent::run(); }
/** * Create a new forward event, create a new contact if necessary */ static function &forward($job_id, $queue_id, $hash, $forward_email, $fromEmail = null, $comment = null) { $q =& CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash); $successfulForward = false; if (!$q) { return $successfulForward; } /* Find the email address/contact, if it exists */ $contact = CRM_Contact_BAO_Contact::getTableName(); $location = CRM_Core_BAO_Location::getTableName(); $email = CRM_Core_BAO_Email::getTableName(); $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName(); $job = CRM_Mailing_BAO_Job::getTableName(); $mailing = CRM_Mailing_BAO_Mailing::getTableName(); $forward = self::getTableName(); $domain =& CRM_Core_BAO_Domain::getDomain(); $dao =& new CRM_Core_Dao(); $dao->query("\n SELECT {$contact}.id as contact_id,\n {$email}.id as email_id,\n {$contact}.do_not_email as do_not_email,\n {$queueTable}.id as queue_id\n FROM ({$email}, {$job} as temp_job)\n INNER JOIN {$contact}\n ON {$email}.contact_id = {$contact}.id\n LEFT JOIN {$queueTable}\n ON {$email}.id = {$queueTable}.email_id\n LEFT JOIN {$job}\n ON {$queueTable}.job_id = {$job}.id\n AND temp_job.mailing_id = {$job}.mailing_id\n WHERE {$queueTable}.job_id = {$job_id}\n AND {$email}.email = '" . CRM_Utils_Type::escape($forward_email, 'String') . "'"); $dao->fetch(); require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); if (isset($dao->queue_id) || $dao->do_not_email == 1) { /* We already sent this mailing to $forward_email, or we should * never email this contact. Give up. */ return $successfulForward; } require_once 'api/v2/Contact.php'; $contact_params = array('email' => $forward_email); $count = civicrm_contact_search_count($contact_params); if ($count == 0) { require_once 'CRM/Core/BAO/LocationType.php'; /* If the contact does not exist, create one. */ $formatted = array('contact_type' => 'Individual'); $locationType = CRM_Core_BAO_LocationType::getDefault(); $value = array('email' => $forward_email, 'location_type_id' => $locationType->id); _civicrm_add_formatted_param($value, $formatted); require_once 'CRM/Import/Parser.php'; $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP; $formatted['fixAddress'] = true; $contact =& civicrm_contact_format_create($formatted); if (civicrm_error($contact, CRM_Core_Error)) { return $successfulForward; } $contact_id = $contact['id']; } $email =& new CRM_Core_DAO_Email(); $email->email = $forward_email; $email->find(true); $email_id = $email->id; if (!$contact_id) { $contact_id = $email->contact_id; } /* Create a new queue event */ $queue_params = array('email_id' => $email_id, 'contact_id' => $contact_id, 'job_id' => $job_id); $queue =& CRM_Mailing_Event_BAO_Queue::create($queue_params); $forward =& new CRM_Mailing_Event_BAO_Forward(); $forward->time_stamp = date('YmdHis'); $forward->event_queue_id = $queue_id; $forward->dest_queue_id = $queue->id; $forward->save(); $dao->reset(); $dao->query(" SELECT {$job}.mailing_id as mailing_id \n FROM {$job}\n WHERE {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer')); $dao->fetch(); $mailing_obj =& new CRM_Mailing_BAO_Mailing(); $mailing_obj->id = $dao->mailing_id; $mailing_obj->find(true); $config =& CRM_Core_Config::singleton(); $mailer =& $config->getMailer(); $recipient = null; $attachments = null; $message =& $mailing_obj->compose($job_id, $queue->id, $queue->hash, $queue->contact_id, $forward_email, $recipient, false, null, $attachments, true, $fromEmail); //append comment if added while forwarding. if (count($comment)) { $message->_txtbody = $comment['body_text'] . $message->_txtbody; if (CRM_Utils_Array::value('body_html', $comment)) { $message->_htmlbody = $comment['body_html'] . '<br />---------------Original message---------------------<br />' . $message->_htmlbody; } } $body = $message->get(); $headers = $message->headers(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); $result = null; if (is_object($mailer)) { $result = $mailer->send($recipient, $headers, $body); CRM_Core_Error::setCallback(); } $params = array('event_queue_id' => $queue->id, 'job_id' => $job_id, 'hash' => $queue->hash); if (is_a($result, PEAR_Error)) { /* Register the bounce event */ $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage())); CRM_Mailing_Event_BAO_Bounce::create($params); } else { $successfulForward = true; /* Register the delivery event */ CRM_Mailing_Event_BAO_Delivered::create($params); } $transaction->commit(); return $successfulForward; }
/** * Function to send Acknowledgment and create activity. * * @param object $form form object. * @param array $params (reference ) an assoc array of name/value pairs. * @access public * @return None. */ function sendAcknowledgment(&$form, $params) { //handle Acknowledgment. $allPayments = $payments = array(); //get All Payments status types. require_once 'CRM/Contribute/PseudoConstant.php'; $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name'); $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id'); //get all paymnets details. CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_Payment', 'pledge_id', $params['id'], $allPayments, $returnProperties); if (!empty($allPayments)) { foreach ($allPayments as $payID => $values) { $contributionValue = $contributionStatus = array(); if (isset($values['contribution_id'])) { $contributionParams = array('id' => $values['contribution_id']); $returnProperties = array('contribution_status_id', 'receive_date'); CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_Contribution', $contributionParams, $contributionStatus, $returnProperties); $contributionValue = array('status' => CRM_Utils_Array::value('contribution_status_id', $contributionStatus), 'receive_date' => CRM_Utils_Array::value('receive_date', $contributionStatus)); } $payments[$payID] = array_merge($contributionValue, array('amount' => CRM_Utils_Array::value('scheduled_amount', $values), 'due_date' => CRM_Utils_Array::value('scheduled_date', $values))); //get the first valid payment id. if (!$form->paymentId && ($paymentStatusTypes[$values['status_id']] == 'Pending' || $paymentStatusTypes[$values['status_id']] == 'Overdue')) { $form->paymentId = $values['id']; } } } //end //assign pledge fields value to template. $pledgeFields = array('create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit', 'installments', 'frequency_day', 'scheduled_amount'); foreach ($pledgeFields as $field) { if (CRM_Utils_Array::value($field, $params)) { $form->assign($field, $params[$field]); } } //assign all payments details. if ($payments) { $form->assign('payments', $payments); } //assign honor fields. $honor_block_is_active = false; //make sure we have values for it if (CRM_Utils_Array::value('honor_type_id', $params) && (!empty($params["honor_first_name"]) && !empty($params["honor_last_name"]) || !empty($params["honor_email"]))) { $honor_block_is_active = true; require_once "CRM/Core/PseudoConstant.php"; $prefix = CRM_Core_PseudoConstant::individualPrefix(); $honor = CRM_Core_PseudoConstant::honor(); $form->assign("honor_type", $honor[$params["honor_type_id"]]); $form->assign("honor_prefix", $prefix[$params["honor_prefix_id"]]); $form->assign("honor_first_name", $params["honor_first_name"]); $form->assign("honor_last_name", $params["honor_last_name"]); $form->assign("honor_email", $params["honor_email"]); } $form->assign('honor_block_is_active', $honor_block_is_active); //handle domain token values require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens()); require_once 'CRM/Utils/Token.php'; $domainValues = array(); foreach ($tokens['domain'] as $token) { $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain); } $form->assign('domain', $domainValues); //handle contact token values. require_once 'CRM/Contact/BAO/Contact.php'; require_once 'CRM/Mailing/BAO/Mailing.php'; $ids = array($params['contact_id']); $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::importableFields()), array('display_name', 'checksum', 'contact_id')); foreach ($fields as $key => $val) { $returnProperties[$val] = true; } $details = CRM_Mailing_BAO_Mailing::getDetails($ids, $returnProperties); $form->assign('contact', $details[0][$params['contact_id']]); //handle custom data. if (CRM_Utils_Array::value('hidden_custom', $params)) { require_once 'CRM/Core/BAO/CustomGroup.php'; $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Pledge', CRM_Core_DAO::$_nullObject, $params['id']); $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0)); $customGroup = array(); // retrieve custom data require_once "CRM/Core/BAO/UFGroup.php"; foreach ($groupTree as $groupID => $group) { $customFields = $customValues = array(); if ($groupID == 'info') { continue; } foreach ($group['fields'] as $k => $field) { $field['title'] = $field['label']; $customFields["custom_{$k}"] = $field; } //to build array of customgroup & customfields in it CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, false, $pledgeParams); $customGroup[$group['title']] = $customValues; } $form->assign('customGroup', $customGroup); } //handle acknowledgment email stuff. require_once 'CRM/Contact/BAO/Contact.php'; require_once 'CRM/Contact/BAO/Contact/Location.php'; list($pledgerDisplayName, $pledgerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']); //check for online pledge. $session = CRM_Core_Session::singleton(); if (CRM_Utils_Array::value('receipt_from_email', $params)) { $userName = CRM_Utils_Array::value('receipt_from_name', $params); $userEmail = CRM_Utils_Array::value('receipt_from_email', $params); } else { if ($userID = $session->get('userID')) { //check for loged in user. list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); } else { //set the domain values. $userName = CRM_Utils_Array::value('name', $domainValues); $userEmail = CRM_Utils_Array::value('email', $domainValues); } } $receiptFrom = "{$userName} <{$userEmail}>"; require_once 'CRM/Core/BAO/MessageTemplates.php'; list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_pledge', 'valueName' => 'pledge_acknowledge', 'contactId' => $params['contact_id'], 'from' => $receiptFrom, 'toName' => $pledgerDisplayName, 'toEmail' => $pledgerEmail)); //check if activity record exist for this pledge //Acknowledgment, if exist do not add activity. require_once "CRM/Activity/DAO/Activity.php"; $activityType = 'Pledge Acknowledgment'; $activity = new CRM_Activity_DAO_Activity(); $activity->source_record_id = $params['id']; $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'); $config = CRM_Core_Config::singleton(); $money = $config->defaultCurrencySymbol; $details = 'Total Amount ' . $money . $params['total_pledge_amount'] . ' To be paid in ' . $params['installments'] . ' installments of ' . $money . $params['scheduled_amount'] . ' every ' . $params['frequency_interval'] . ' ' . $params['frequency_unit'] . '(s)'; if (!$activity->find()) { $activityParams = array('subject' => $subject, 'source_contact_id' => $params['contact_id'], 'source_record_id' => $params['id'], 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']), 'is_test' => $params['is_test'], 'status_id' => 2, 'details' => $details); require_once 'api/v2/Activity.php'; if (is_a(civicrm_activity_create($activityParams), 'CRM_Core_Error')) { CRM_Core_Error::fatal("Failed creating Activity for acknowledgment"); } } }
/** * Send a reponse email informing the contact of the groups from which he * has been unsubscribed. * * @param string $queue_id The queue event ID * @param array $groups List of group IDs * @param bool $is_domain Is this domain-level? * @param int $job The job ID * @return void * @access public * @static */ public static function send_unsub_response($queue_id, $groups, $is_domain = false, $job) { $config =& CRM_Core_Config::singleton(); $domain =& CRM_Core_BAO_Domain::getDomain(); $jobTable = CRM_Mailing_BAO_Job::getTableName(); $mailingTable = CRM_Mailing_DAO_Mailing::getTableName(); $contacts = CRM_Contact_DAO_Contact::getTableName(); $email = CRM_Core_DAO_Email::getTableName(); $queue = CRM_Mailing_Event_BAO_Queue::getTableName(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $dao =& new CRM_Mailing_BAO_Mailing(); $dao->query(" SELECT * FROM {$mailingTable} \n INNER JOIN {$jobTable} ON\n {$jobTable}.mailing_id = {$mailingTable}.id \n WHERE {$jobTable}.id = {$job}"); $dao->fetch(); $component =& new CRM_Mailing_BAO_Component(); if ($is_domain) { $component->id = $dao->optout_id; } else { $component->id = $dao->unsubscribe_id; } $component->find(true); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $eq =& new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$contacts}.id as contact_id,\n {$email}.email as email,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); if ($groups) { foreach ($groups as $key => $value) { if (!$value) { unset($groups[$key]); } } } $message =& new Mail_Mime("\n"); list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email); $bao =& new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceUnsubscribeTokens($html, $domain, $groups, true, $eq->contact_id, $eq->hash); $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, true, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, null, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceUnsubscribeTokens($text, $domain, $groups, false, $eq->contact_id, $eq->hash); $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, false, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, null, $tokens['text']); $message->setTxtBody($text); } require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($eq->email, $h, $b); CRM_Core_Error::setCallback(); } }
/** * Send confirmation of cancellation to source participant * * return @ void */ public function sendCancellation() { $domainValues = array(); $domain = CRM_Core_BAO_Domain::getDomain(); $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens()); foreach ($tokens['domain'] as $token) { $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain); } $participantRoles = array(); $participantRoles = CRM_Event_PseudoConstant::participantRole(); $participantDetails = array(); $query = "SELECT * FROM civicrm_participant WHERE id = {$this->_from_participant_id}"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id); } $eventDetails = array(); $eventParams = array('id' => $this->_event_id); CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]); //get default participant role. $eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles); //get the location info $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event'); $eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE); //get contact details $contactIds[$this->_from_contact_id] = $this->_from_contact_id; list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant'); foreach ($currentContactDetails as $contactId => $contactValues) { $contactDetails[$this->_from_contact_id] = $contactValues; } //send a 'cancelled' email to user, and cc the event's cc_confirm email $mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_from_participant_id, $participantDetails[$this->_from_participant_id], $eventDetails[$this->_event_id], $contactDetails[$this->_from_contact_id], $domainValues, "Transferred", ""); $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name)); $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email)); CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success'); }
/** * Send an automated response. * * @param object $mailing * The mailing object. * @param int $queue_id * The queue ID. * @param string $replyto * Optional reply-to from the reply. * * @return void */ private static function autoRespond(&$mailing, $queue_id, $replyto) { $config = CRM_Core_Config::singleton(); $contacts = CRM_Contact_DAO_Contact::getTableName(); $email = CRM_Core_DAO_Email::getTableName(); $queue = CRM_Mailing_Event_DAO_Queue::getTableName(); $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$email}.email as email,\n {$queue}.job_id as job_id,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); $to = empty($replyto) ? $eq->email : $replyto; $component = new CRM_Mailing_BAO_Component(); $component->id = $mailing->reply_id; $component->find(TRUE); $message = new Mail_Mime("\n"); $domain = CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'To' => $to, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); /* TODO: do we need reply tokens? */ $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $mailing, NULL, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $mailing, NULL, $tokens['text']); $message->setTxtBody($text); } $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'a', $eq->job_id, queue_id, $eq->hash); $mailer = $config->getMailer(); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($to, $h, $b); unset($errorScope); } }
/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { require_once 'CRM/Mailing/Event/BAO/Subscribe.php'; $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return false; } require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $ce =& new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); require_once 'CRM/Contact/BAO/GroupContact.php'; CRM_Contact_BAO_GroupContact::updateGroupMembershipStatus($contact_id, $se->group_id, 'Email', $ce->id); $transaction->commit(); $config =& CRM_Core_Config::singleton(); require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); require_once 'CRM/Contact/BAO/Contact/Location.php'; list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); require_once 'CRM/Contact/DAO/Group.php'; $group =& new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(true); require_once 'CRM/Mailing/BAO/Component.php'; $component =& new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(true); require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } require_once 'CRM/Mailing/BAO/Mailing.php'; $bao =& new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, true); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, false); // we need to wrap Mail_mime because PEAR is apparently unable to fix // a six-year-old bug (PEAR bug #30) in Mail_mime::_encodeHeaders() // this fixes CRM-5466 require_once 'CRM/Utils/Mail/FixedMailMIME.php'; $message =& new CRM_Utils_Mail_FixedMailMIME("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); require_once 'CRM/Mailing/BAO/Mailing.php'; PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($email, $h, $b); CRM_Core_Error::setCallback(); } return $group->title; }
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)); }
/** * Get the domain object given a subscribe event. * * @param int $subscribe_id * ID of the subscribe event. * * @return object * $domain The domain owning the event */ public static function &getDomain($subscribe_id) { return CRM_Core_BAO_Domain::getDomain(); }
/** * Function takes participant ids and statuses * update status from $fromStatusId to $toStatusId * and send mail + create activities. * * @param array $participantIds * Participant ids. * @param int $toStatusId * Update status id. * @param int $fromStatusId * From status id. * @param bool $returnResult * @param bool $skipCascadeRule * * @return array|NULL */ public static function transitionParticipants($participantIds, $toStatusId, $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE) { if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) { return NULL; } //thumb rule is if we triggering primary participant need to triggered additional $allParticipantIds = $primaryANDAdditonalIds = array(); foreach ($participantIds as $id) { $allParticipantIds[] = $id; if (self::isPrimaryParticipant($id)) { //filter additional as per status transition rules, CRM-5403 if ($skipCascadeRule) { $additionalIds = self::getAdditionalParticipantIds($id); } else { $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId); } if (!empty($additionalIds)) { $allParticipantIds = array_merge($allParticipantIds, $additionalIds); $primaryANDAdditonalIds[$id] = $additionalIds; } } } //get the unique participant ids, $allParticipantIds = array_unique($allParticipantIds); //pull required participants, contacts, events data, if not in hand static $eventDetails = array(); static $domainValues = array(); static $contactDetails = array(); $contactIds = $eventIds = $participantDetails = array(); $statusTypes = CRM_Event_PseudoConstant::participantStatus(); $participantRoles = CRM_Event_PseudoConstant::participantRole(); $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'"); //first thing is pull all necessory data from db. $participantIdClause = '(' . implode(',', $allParticipantIds) . ')'; //get all participants data. $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id); if (!array_key_exists($dao->contact_id, $contactDetails)) { $contactIds[$dao->contact_id] = $dao->contact_id; } if (!array_key_exists($dao->event_id, $eventDetails)) { $eventIds[$dao->event_id] = $dao->event_id; } } //get the domain values. if (empty($domainValues)) { // making all tokens available to templates. $domain = CRM_Core_BAO_Domain::getDomain(); $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens()); foreach ($tokens['domain'] as $token) { $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain); } } //get all required contacts detail. if (!empty($contactIds)) { // get the contact details. list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant'); foreach ($currentContactDetails as $contactId => $contactValues) { $contactDetails[$contactId] = $contactValues; } } //get all required events detail. if (!empty($eventIds)) { foreach ($eventIds as $eventId) { //retrieve event information $eventParams = array('id' => $eventId); CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]); //get default participant role. $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles); //get the location info $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event'); $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE); } } //now we are ready w/ all required data. //take a decision as per statuses. $emailType = NULL; $toStatus = $statusTypes[$toStatusId]; $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes); switch ($toStatus) { case 'Pending from waitlist': case 'Pending from approval': switch ($fromStatus) { case 'On waitlist': case 'Awaiting approval': $emailType = 'Confirm'; break; } break; case 'Expired': //no matter from where u come send expired mail. $emailType = $toStatus; break; case 'Cancelled': //no matter from where u come send cancel mail. $emailType = $toStatus; break; } //as we process additional w/ primary, there might be case if user //select primary as well as additionals, so avoid double processing. $processedParticipantIds = array(); $mailedParticipants = array(); //send mails and update status. foreach ($participantDetails as $participantId => $participantValues) { $updateParticipantIds = array(); if (in_array($participantId, $processedParticipantIds)) { continue; } //check is it primary and has additional. if (array_key_exists($participantId, $primaryANDAdditonalIds)) { foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) { if ($emailType) { $mail = self::sendTransitionParticipantMail($additonalId, $participantDetails[$additonalId], $eventDetails[$participantDetails[$additonalId]['event_id']], $contactDetails[$participantDetails[$additonalId]['contact_id']], $domainValues, $emailType); //get the mail participant ids if ($mail) { $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name']; } } $updateParticipantIds[] = $additonalId; $processedParticipantIds[] = $additonalId; } } //now send email appropriate mail to primary. if ($emailType) { $mail = self::sendTransitionParticipantMail($participantId, $participantValues, $eventDetails[$participantValues['event_id']], $contactDetails[$participantValues['contact_id']], $domainValues, $emailType); //get the mail participant ids if ($mail) { $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name']; } } //now update status of group/one at once. $updateParticipantIds[] = $participantId; //update the register date only when we, //move participant to pending class, CRM-6496 $updateRegisterDate = FALSE; if (array_key_exists($toStatusId, $pendingStatuses)) { $updateRegisterDate = TRUE; } self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate); $processedParticipantIds[] = $participantId; } //return result for cron. if ($returnResult) { $results = array('mailedParticipants' => $mailedParticipants, 'updatedParticipantIds' => $processedParticipantIds); return $results; } }
/** * Check that domain email and org name are set * @return array */ public function checkDomainNameEmail() { $messages = array(); list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE); $domain = CRM_Core_BAO_Domain::getDomain(); $domainName = $domain->name; $fixEmailUrl = CRM_Utils_System::url("civicrm/admin/domain", "action=update&reset=1"); if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') { if (!$domainName || $domainName == 'Default Domain Name') { $msg = ts("Please enter your organization's <a href=\"%1\">name, primary address, and default FROM Email Address</a> (for system-generated emails).", array(1 => $fixEmailUrl)); } else { $msg = ts('Please enter a <a href="%1">default FROM Email Address</a> (for system-generated emails).', array(1 => $fixEmailUrl)); } } elseif (!$domainName || $domainName == 'Default Domain Name') { $msg = ts("Please enter your organization's <a href=\"%1\">name and primary address</a>.", array(1 => $fixEmailUrl)); } if (!empty($msg)) { $messages[] = new CRM_Utils_Check_Message(__FUNCTION__, $msg, ts('Complete Setup'), \Psr\Log\LogLevel::WARNING, 'fa-check-square-o'); } return $messages; }