Esempio n. 1
0
/**
 * Get CiviCRM domain details
 * {@getfields domain_create}
 * @example DomainGet.php
 */
function civicrm_api3_domain_get($params)
{
    $params['version'] = CRM_Utils_Array::value('domain_version', $params);
    unset($params['version']);
    $bao = new CRM_Core_BAO_Domain();
    if (CRM_Utils_Array::value('current_domain', $params)) {
        $domainBAO = CRM_Core_Config::domainID();
        $params['id'] = $domainBAO;
    }
    _civicrm_api3_dao_set_filter($bao, $params, true, 'domain');
    $domains = _civicrm_api3_dao_to_array($bao, $params, true, 'domain');
    foreach ($domains as $domain) {
        if (!empty($domain['contact_id'])) {
            $values = array();
            $locparams = array('contact_id' => $domain['contact_id']);
            $values['location'] = CRM_Core_BAO_Location::getValues($locparams, 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');
            if (!empty($values['location']['email'])) {
                $domain['domain_email'] = CRM_Utils_Array::value('email', $values['location']['email'][1]);
            }
            if (!empty($values['location']['phone'])) {
                $domain['domain_phone'] = array('phone_type' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', CRM_Utils_Array::value('phone_type_id', $values['location']['phone'][1])), 'phone' => CRM_Utils_Array::value('phone', $values['location']['phone'][1]));
            }
            if (!empty($values['location']['address'])) {
                foreach ($address_array as $value) {
                    $domain['domain_address'][$value] = CRM_Utils_Array::value($value, $values['location']['address'][1]);
                }
            }
            list($domain['from_name'], $domain['from_email']) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
            $domains[$domain['id']] = array_merge($domains[$domain['id']], $domain);
        }
    }
    return civicrm_api3_create_success($domains, $params, 'domain', 'get', $bao);
}
Esempio n. 2
0
 /**
  * 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();
 }
Esempio n. 4
0
/**
 * 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;
}
Esempio n. 5
0
 /**
 * takes an associative array and sends a thank you or email verification email
 *
 * @param array $params (reference ) an assoc array of name/value pairs
 *
 * @param $sendEmailMode
 *
 * @throws Exception
 * @return void
   @access public
 * @static
 */
 public static function sendEmail($params, $sendEmailMode)
 {
     /* sendEmailMode
      * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
      *   connected user via login/pwd - thank you
      *    or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
      *   or login using fb connect - thank you + click to add msg to fb wall
      *
      * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
      *  send a confirmation request email
      */
     // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
     $petitionGroupName = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'petition_contacts', NULL, 'Petition Contacts');
     $dao = new CRM_Contact_DAO_Group();
     $dao->title = $petitionGroupName;
     if (!$dao->find(TRUE)) {
         $dao->is_active = 1;
         $dao->visibility = 'User and User Admin Only';
         $dao->save();
     }
     $group_id = $dao->id;
     // get petition info
     $petitionParams['id'] = $params['sid'];
     $petitionInfo = array();
     CRM_Campaign_BAO_Survey::retrieve($petitionParams, $petitionInfo);
     if (empty($petitionInfo)) {
         CRM_Core_Error::fatal('Petition doesn\'t exist.');
     }
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $toName = CRM_Contact_BAO_Contact::displayName($params['contactId']);
     $replyTo = "do-not-reply@{$emailDomain}";
     // set additional general message template params (custom tokens to use in email msg templates)
     // tokens then available in msg template as {$petition.title}, etc
     $petitionTokens['title'] = $petitionInfo['title'];
     $petitionTokens['petitionId'] = $params['sid'];
     $tplParams['petition'] = $petitionTokens;
     switch ($sendEmailMode) {
         case CRM_Campaign_Form_Petition_Signature::EMAIL_THANK:
             // add this contact to the CIVICRM_PETITION_CONTACTS group
             // Cannot pass parameter 1 by reference
             $p = array($params['contactId']);
             CRM_Contact_BAO_GroupContact::addContactsToGroup($p, $group_id, 'API');
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_sign', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title']));
             }
             break;
         case CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM:
             // create mailing event subscription record for this contact
             // this will allow using a hash key to confirm email address by sending a url link
             $se = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $params['email-Primary'], $params['contactId'], 'profile');
             //    require_once 'CRM/Core/BAO/Domain.php';
             //    $domain = CRM_Core_BAO_Domain::getDomain();
             $config = CRM_Core_Config::singleton();
             $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
             $replyTo = implode($config->verpSeparator, array($localpart . 'c', $se->contact_id, $se->id, $se->hash)) . "@{$emailDomain}";
             $confirmUrl = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE);
             $confirmUrlPlainText = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE, NULL, FALSE);
             // set email specific message template params and assign to tplParams
             $petitionTokens['confirmUrl'] = $confirmUrl;
             $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
             $tplParams['petition'] = $petitionTokens;
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_confirmation_needed', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'], 'confirmUrl' => $confirmUrl));
             }
             break;
     }
 }
    /**
     * @param $mappingID
     * @param $now
     *
     * @throws CRM_Core_Exception
     */
    static function sendMailings($mappingID, $now)
    {
        $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
        $fromEmailAddress = "{$domainValues['0']} <{$domainValues['1']}>";
        $mapping = new CRM_Core_DAO_ActionMapping();
        $mapping->id = $mappingID;
        $mapping->find(TRUE);
        $actionSchedule = new CRM_Core_DAO_ActionSchedule();
        $actionSchedule->mapping_id = $mappingID;
        $actionSchedule->is_active = 1;
        $actionSchedule->find(FALSE);
        $tokenFields = array();
        $session = CRM_Core_Session::singleton();
        while ($actionSchedule->fetch()) {
            $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
            if ($actionSchedule->from_email) {
                $fromEmailAddress = "{$actionSchedule->from_name} <{$actionSchedule->from_email}>";
            }
            if ($actionSchedule->record_activity) {
                if ($mapping->entity == 'civicrm_membership') {
                    $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
                } else {
                    $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
                }
                $activityStatusID = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
            }
            if ($mapping->entity == 'civicrm_activity') {
                $tokenEntity = 'activity';
                $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
                $extraSelect = ', ov.label as activity_type, e.id as activity_id';
                $extraJoin = "\nINNER JOIN civicrm_option_group og ON og.name = 'activity_type'\nINNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
                $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = "\nLEFT JOIN civicrm_option_group og ON og.name = 'activity_type'\nLEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
                }
            }
            if ($mapping->entity == 'civicrm_participant') {
                $tokenEntity = 'event';
                $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone', 'balance');
                $extraSelect = ', ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone ';
                $extraJoin = "\nINNER JOIN civicrm_event ev ON e.event_id = ev.id\nINNER JOIN civicrm_option_group og ON og.name = 'event_type'\nINNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT  JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT  JOIN civicrm_address address ON address.id = lb.address_id\nLEFT  JOIN civicrm_email email ON email.id = lb.email_id\nLEFT  JOIN civicrm_phone phone ON phone.id = lb.phone_id\n";
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = "\nLEFT JOIN civicrm_event ev ON e.event_id = ev.id\nLEFT JOIN civicrm_option_group og ON og.name = 'event_type'\nLEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT JOIN civicrm_address address ON address.id = lb.address_id\nLEFT JOIN civicrm_email email ON email.id = lb.email_id\nLEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id\n";
                }
            }
            if ($mapping->entity == 'civicrm_membership') {
                $tokenEntity = 'membership';
                $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
                $extraSelect = ', mt.minimum_fee as fee, e.id as id , e.join_date, e.start_date, e.end_date, ms.name as status, mt.name as type';
                $extraJoin = '
 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = '
 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
                }
            }
            if ($mapping->entity == 'civicrm_contact') {
                $tokenEntity = 'contact';
                //TODO: get full list somewhere!
                $tokenFields = array('birth_date', 'last_name');
                //TODO: is there anything to add here?
            }
            $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
            if ($actionSchedule->limit_to == 0) {
                $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
                $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
            }
            $entityJoinClause .= $extraOn;
            $query = "\nSELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.*, e.id as entityID, e.* {$extraSelect}\nFROM  civicrm_action_log reminder\n{$entityJoinClause}\n{$extraJoin}\nWHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL\n{$extraWhere}";
            $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
            while ($dao->fetch()) {
                $entityTokenParams = array();
                foreach ($tokenFields as $field) {
                    if ($field == 'location') {
                        $loc = array();
                        $stateProvince = CRM_Core_PseudoConstant::stateProvince();
                        $loc['street_address'] = $dao->street_address;
                        $loc['city'] = $dao->city;
                        $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince);
                        $loc['postal_code'] = $dao->postal_code;
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
                    } elseif ($field == 'info_url') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                    } elseif ($field == 'registration_url') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                    } elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->{$field});
                    } elseif ($field == 'balance') {
                        $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event');
                        $balancePay = CRM_Utils_Array::value('balance', $info);
                        $balancePay = CRM_Utils_Money::format($balancePay);
                        $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
                    } elseif ($field == 'fee_amount') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money::format($dao->{$field});
                    } else {
                        $entityTokenParams["{$tokenEntity}." . $field] = $dao->{$field};
                    }
                }
                $isError = 0;
                $errorMsg = $toEmail = $toPhoneNumber = '';
                if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
                    $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
                    $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters);
                    //to get primary mobile ph,if not get a first mobile phONE
                    if (!empty($toPhoneNumbers)) {
                        $toPhoneNumberDetails = reset($toPhoneNumbers);
                        $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
                        //contact allows to send sms
                        $toDoNotSms = 0;
                    }
                }
                if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
                    $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID);
                }
                if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) {
                    $to['email'] = $toEmail;
                    $to['phone'] = $toPhoneNumber;
                    $result = CRM_Core_BAO_ActionSchedule::sendReminder($dao->contactID, $to, $actionSchedule->id, $fromEmailAddress, $entityTokenParams);
                    if (!$result || is_a($result, 'PEAR_Error')) {
                        // we could not send an email, for now we ignore, CRM-3406
                        $isError = 1;
                    }
                } else {
                    $isError = 1;
                    $errorMsg = "Couldn\\'t find recipient\\'s email address.";
                }
                // update action log record
                $logParams = array('id' => $dao->reminderID, 'is_error' => $isError, 'message' => $errorMsg ? $errorMsg : "null", 'action_date_time' => $now);
                CRM_Core_BAO_ActionLog::create($logParams);
                // insert activity log record if needed
                if ($actionSchedule->record_activity) {
                    $activityParams = array('subject' => $actionSchedule->title, 'details' => $actionSchedule->body_html, 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $dao->contactID, 'target_contact_id' => $dao->contactID, 'activity_date_time' => date('YmdHis'), 'status_id' => $activityStatusID, 'activity_type_id' => $activityTypeID, 'source_record_id' => $dao->entityID);
                    $activity = CRM_Activity_BAO_Activity::create($activityParams);
                }
            }
            $dao->free();
        }
    }
Esempio n. 7
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  * @return None 
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues();
     $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active');
     foreach ($checkBoxes as $key) {
         if (!isset($params[$key])) {
             $params[$key] = 0;
         }
     }
     $session =& CRM_Core_Session::singleton();
     $contactID = isset($this->_contactID) ? $this->_contactID : $session->get('userID');
     if (!$contactID) {
         $contactID = $this->get('contactID');
     }
     $params['contact_id'] = $contactID;
     $params['contribution_page_id'] = $this->get('contribution_page_id') ? $this->get('contribution_page_id') : $this->_contriPageId;
     $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
     $approval_needed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PCPBlock', $params['contribution_page_id'], 'is_approval_needed', 'entity_id');
     $approvalMessage = null;
     if ($this->get('action') & CRM_Core_Action::ADD) {
         $params['status_id'] = $approval_needed ? 1 : 2;
         $approvalMessage = $approval_needed ? ts('but requires administrator review before you can begin your fundraising efforts. You will receive an email confirmation shortly which includes a link to return to your fundraising page.') : ts('and is ready to use.');
     }
     $params['id'] = $this->_pageId;
     require_once 'CRM/Contribute/BAO/PCP.php';
     $pcp = CRM_Contribute_BAO_PCP::add($params, false);
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_pcp', $pcp->id);
     $pageStatus = isset($this->_pageId) ? ts('updated') : ts('created');
     $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PCP', $pcp->id, 'status_id');
     //send notification of PCP create/update.
     $pcpParams = array('entity_table' => 'civicrm_contribution_page', 'entity_id' => $pcp->contribution_page_id);
     $notifyParams = array();
     $notifyStatus = "";
     CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_PCPBlock', $pcpParams, $notifyParams, array('notify_email'));
     if ($emails = CRM_Utils_Array::value('notify_email', $notifyParams)) {
         $this->assign('pcpTitle', $pcp->title);
         if ($this->_pageId) {
             $this->assign('mode', 'Update');
         } else {
             $this->assign('mode', 'Add');
         }
         require_once 'CRM/Core/OptionGroup.php';
         $pcpStatus = CRM_Core_OptionGroup::getLabel('pcp_status', $statusId);
         $this->assign('pcpStatus', $pcpStatus);
         $this->assign('pcpId', $pcp->id);
         $supporterUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid={$pcp->contact_id}", true, null, true, true);
         $this->assign('supporterUrl', $supporterUrl);
         $supporterName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $pcp->contact_id, 'display_name');
         $this->assign('supporterName', $supporterName);
         $contribPageUrl = CRM_Utils_System::url("civicrm/contribute/transact", "reset=1&id={$pcp->contribution_page_id}", true, null, true, true);
         $this->assign('contribPageUrl', $contribPageUrl);
         $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $pcp->contribution_page_id, 'title');
         $this->assign('contribPageTitle', $contribPageTitle);
         $managePCPUrl = CRM_Utils_System::url("civicrm/admin/pcp", "reset=1", true, null, true, true);
         $this->assign('managePCPUrl', $managePCPUrl);
         //get the default domain email address.
         require_once 'CRM/Core/BAO/Domain.php';
         list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
         if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') {
             CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in Administer CiviCRM &raquo; Configure &raquo; Domain Information. The email address used may need to be a valid mail account with your email service provider.'));
         }
         //if more than one email present for PCP notification ,
         //first email take it as To and other as CC and First email
         //address should be sent in users email receipt for
         //support purpose.
         $emailArray = explode(',', $emails);
         $to = $emailArray[0];
         unset($emailArray[0]);
         $cc = implode(',', $emailArray);
         require_once 'CRM/Core/BAO/MessageTemplates.php';
         list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_notify', 'contactId' => $contactID, 'from' => "{$domainEmailName} <{$domainEmailAddress}>", 'toEmail' => $to, 'cc' => $cc));
         if ($sent) {
             $notifyStatus = ts('A notification email has been sent to the site administrator.');
         }
     }
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_pcp', $pcp->id);
     // send email notification to supporter, if initial setup / add mode.
     if (!$this->_pageId) {
         CRM_Contribute_BAO_PCP::sendStatusUpdate($pcp->id, $statusId, true);
         if ($approvalMessage && CRM_Utils_Array::value('status_id', $params) == 1) {
             $notifyStatus .= ts(' You will receive a second email as soon as the review process is complete.');
         }
     }
     //check if pcp created by anonymous user
     $anonymousPCP = 0;
     if (!$session->get('userID')) {
         $anonymousPCP = 1;
     }
     CRM_Core_Session::setStatus(ts("Your Personal Campaign Page has been %1 %2 %3", array(1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus)));
     if (!$this->_pageId) {
         $session->pushUserContext(CRM_Utils_System::url('civicrm/contribute/pcp/info', "reset=1&id={$pcp->id}&ap={$anonymousPCP}"));
     }
 }
 /**
  * called after the user submits the form.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->exportValues();
     if ($this->_selfService && $this->_donorEmail) {
         // for self service force notify
         $params['is_notify'] = 1;
     }
     // if this is an update of an existing recurring contribution, pass the ID
     $params['id'] = $this->_subscriptionDetails->recur_id;
     $message = '';
     $params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
     $updateSubscription = TRUE;
     if ($this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
         $updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
     }
     if (is_a($updateSubscription, 'CRM_Core_Error')) {
         CRM_Core_Error::displaySessionError($updateSubscription);
         $status = ts('Could not update the Recurring contribution details');
         $msgTitle = ts('Update Error');
         $msgType = 'error';
     } elseif ($updateSubscription) {
         // save the changes
         $result = CRM_Contribute_BAO_ContributionRecur::add($params);
         $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.', array(1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency), 2 => $this->_subscriptionDetails->frequency_interval, 3 => $this->_subscriptionDetails->frequency_unit, 4 => $params['installments']));
         $msgTitle = ts('Update Success');
         $msgType = 'success';
         $contactID = $this->_subscriptionDetails->contact_id;
         if ($this->_subscriptionDetails->amount != $params['amount']) {
             $message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.", array(1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency), 2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency))) . ' ';
         }
         if ($this->_subscriptionDetails->installments != $params['installments']) {
             $message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", array(1 => $this->_subscriptionDetails->installments, 2 => $params['installments'])) . ' ';
         }
         $activityParams = array('source_contact_id' => $contactID, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Update Recurring Contribution', 'name'), 'subject' => ts('Recurring Contribution Updated'), 'details' => $message, 'activity_date_time' => date('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'));
         $session = CRM_Core_Session::singleton();
         $cid = $session->get('userID');
         if ($cid) {
             $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
             $activityParams['source_contact_id'] = $cid;
         }
         CRM_Activity_BAO_Activity::create($activityParams);
         if (!empty($params['is_notify'])) {
             // send notification
             if ($this->_subscriptionDetails->contribution_page_id) {
                 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $this->_subscriptionDetails->contribution_page_id, $value, array('title', 'receipt_from_name', 'receipt_from_email'));
                 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
             } else {
                 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
                 $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>";
             }
             list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $tplParams = array('recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval, 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit, 'amount' => CRM_Utils_Money::format($params['amount']), 'installments' => $params['installments']);
             $tplParams['contact'] = array('display_name' => $donorDisplayName);
             $tplParams['receipt_from_email'] = $receiptFrom;
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_recurring_edit', 'contactId' => $contactID, 'tplParams' => $tplParams, 'isTest' => $this->_subscriptionDetails->is_test, 'PDFFilename' => 'receipt.pdf', 'from' => $receiptFrom, 'toName' => $donorDisplayName, 'toEmail' => $donorEmail);
             list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
         }
     }
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     if ($userID && $status) {
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     } elseif (!$userID) {
         if ($status) {
             CRM_Utils_System::setUFMessage($status);
         }
         // keep result as 1, since we not displaying anything on the redirected page anyway
         return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus', "reset=1&task=update&result=1"));
     }
 }
 /**
  * Send an alert email.
  *
  * @param $p_eWAY_tran_num
  * @param $p_trxn_out
  * @param $p_trxn_back
  * @param $p_request
  * @param $p_response
  */
 public function send_alert_email($p_eWAY_tran_num, $p_trxn_out, $p_trxn_back, $p_request, $p_response)
 {
     // Initialization call is required to use CiviCRM APIs.
     civicrm_initialize(TRUE);
     list($fromName, $fromEmail) = CRM_Core_BAO_Domain::getNameAndEmail();
     $from = "{$fromName} <{$fromEmail}>";
     $toName = 'Support at eWAY';
     $toEmail = '*****@*****.**';
     $subject = "ALERT: Unique Trxn Number Failure : eWAY Transaction # = [" . $p_eWAY_tran_num . "]";
     $message = "\nTRXN sent out with request   = '{$p_trxn_out}'.\nTRXN sent back with response = '{$p_trxn_back}'.\n\nThis is a ['{$this->_mode}'] transaction.\n\n\nRequest XML =\n---------------------------------------------------------------------------\n{$p_request}\n---------------------------------------------------------------------------\n\n\nResponse XML =\n---------------------------------------------------------------------------\n{$p_response}\n---------------------------------------------------------------------------\n\n\nRegards\n\nThe CiviCRM eWAY Payment Processor Module\n";
     $params = array();
     $params['groupName'] = 'eWay Email Sender';
     $params['from'] = $from;
     $params['toName'] = $toName;
     $params['toEmail'] = $toEmail;
     $params['subject'] = $subject;
     $params['text'] = $message;
     CRM_Utils_Mail::send($params);
 }
Esempio n. 10
0
 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));
 }
Esempio n. 11
0
 /**
  * Function used to send notification mail to pcp owner.
  *
  * This is used by contribution and also event PCPs.
  *
  * @param object $contribution
  * @param object $contributionSoft
  *   Contribution object.
  */
 public static function pcpNotifyOwner($contribution, $contributionSoft)
 {
     $params = array('id' => $contributionSoft->pcp_id);
     CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
     $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
     if ($ownerNotifyID != CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'no_notifications', 'name') && ($ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name') && CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id, 'is_notify') || $ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
         $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$contributionSoft->pcp_id}", TRUE, NULL, FALSE, TRUE);
         // set email in the template here
         if (CRM_Core_BAO_LocationType::getBilling()) {
             list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id, FALSE, CRM_Core_BAO_LocationType::getBilling());
         }
         // get primary location email if no email exist( for billing location).
         if (!$email) {
             list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id);
         }
         list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft->contact_id);
         $tplParams = array('page_title' => $pcpInfo['title'], 'receive_date' => $contribution->receive_date, 'total_amount' => $contributionSoft->amount, 'donors_display_name' => $donorName, 'donors_email' => $email, 'pcpInfoURL' => $pcpInfoURL, 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll, 'currency' => $contributionSoft->currency);
         $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
         $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_owner_notify', 'contactId' => $contributionSoft->contact_id, 'toEmail' => $ownerEmail, 'toName' => $ownerName, 'from' => "{$domainValues['0']} <{$domainValues['1']}>", 'tplParams' => $tplParams, 'PDFFilename' => 'receipt.pdf');
         CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
     }
 }
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active', 'is_notify');
     foreach ($checkBoxes as $key) {
         if (!isset($params[$key])) {
             $params[$key] = 0;
         }
     }
     $session = CRM_Core_Session::singleton();
     $contactID = isset($this->_contactID) ? $this->_contactID : $session->get('userID');
     if (!$contactID) {
         $contactID = $this->get('contactID');
     }
     $params['title'] = $params['pcp_title'];
     $params['intro_text'] = $params['pcp_intro_text'];
     $params['contact_id'] = $contactID;
     $params['page_id'] = $this->get('component_page_id') ? $this->get('component_page_id') : $this->_contriPageId;
     $params['page_type'] = $this->_component;
     // since we are allowing html input from the user
     // we also need to purify it, so lets clean it up
     $htmlFields = array('intro_text', 'page_text', 'title');
     foreach ($htmlFields as $field) {
         if (!empty($params[$field])) {
             $params[$field] = CRM_Utils_String::purifyHTML($params[$field]);
         }
     }
     $entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($params['page_type']);
     $pcpBlock = new CRM_PCP_DAO_PCPBlock();
     $pcpBlock->entity_table = $entity_table;
     $pcpBlock->entity_id = $params['page_id'];
     $pcpBlock->find(TRUE);
     $params['pcp_block_id'] = $pcpBlock->id;
     $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
     $approval_needed = $pcpBlock->is_approval_needed;
     $approvalMessage = NULL;
     if ($this->get('action') & CRM_Core_Action::ADD) {
         $params['status_id'] = $approval_needed ? 1 : 2;
         $approvalMessage = $approval_needed ? ts('but requires administrator review before you can begin promoting your campaign. You will receive an email confirmation shortly which includes a link to return to this page.') : ts('and is ready to use.');
     }
     $params['id'] = $this->_pageId;
     $pcp = CRM_PCP_BAO_PCP::add($params, FALSE);
     //create page in wordpress
     create_wp_campaign($pcp->title, $pcp->contact_id, $pcp->id);
     CRM_Core_Error::debug_log_message("Calling create_wp_campaign.... Params title: {$pcp->title}, contact_id: {$pcp->contact_id}, pcp_id: {$pcp->id} ");
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_pcp', $pcp->id);
     $pageStatus = isset($this->_pageId) ? ts('updated') : ts('created');
     $statusId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp->id, 'status_id');
     //send notification of PCP create/update.
     $pcpParams = array('entity_table' => $entity_table, 'entity_id' => $pcp->page_id);
     $notifyParams = array();
     $notifyStatus = "";
     CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, array('notify_email'));
     if ($emails = $pcpBlock->notify_email) {
         $this->assign('pcpTitle', $pcp->title);
         if ($this->_pageId) {
             $this->assign('mode', 'Update');
         } else {
             $this->assign('mode', 'Add');
         }
         $pcpStatus = CRM_Core_OptionGroup::getLabel('pcp_status', $statusId);
         $this->assign('pcpStatus', $pcpStatus);
         $this->assign('pcpId', $pcp->id);
         $supporterUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$pcp->contact_id}", TRUE, NULL, FALSE, FALSE);
         $this->assign('supporterUrl', $supporterUrl);
         $supporterName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $pcp->contact_id, 'display_name');
         $this->assign('supporterName', $supporterName);
         if ($this->_component == 'contribute') {
             $pageUrl = CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE);
             $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $pcpBlock->entity_id, 'title');
         } elseif ($this->_component == 'event') {
             $pageUrl = CRM_Utils_System::url('civicrm/event', "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE);
             $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $pcpBlock->entity_id, 'title');
         }
         $this->assign('contribPageUrl', $pageUrl);
         $this->assign('contribPageTitle', $contribPageTitle);
         $managePCPUrl = CRM_Utils_System::url('civicrm/admin/pcp', "reset=1", TRUE, NULL, FALSE, FALSE);
         $this->assign('managePCPUrl', $managePCPUrl);
         //get the default domain email address.
         list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
         if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') {
             $fixUrl = CRM_Utils_System::url('civicrm/admin/domain', 'action=update&reset=1');
             CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl)));
         }
         //if more than one email present for PCP notification ,
         //first email take it as To and other as CC and First email
         //address should be sent in users email receipt for
         //support purpose.
         $emailArray = explode(',', $emails);
         $to = $emailArray[0];
         unset($emailArray[0]);
         $cc = implode(',', $emailArray);
         list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_notify', 'contactId' => $contactID, 'from' => "{$domainEmailName} <{$domainEmailAddress}>", 'toEmail' => $to, 'cc' => $cc));
         if ($sent) {
             $notifyStatus = ts('A notification email has been sent to the site administrator.');
         }
     }
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_pcp', $pcp->id);
     // send email notification to supporter, if initial setup / add mode.
     if (!$this->_pageId) {
         CRM_PCP_BAO_PCP::sendStatusUpdate($pcp->id, $statusId, TRUE, $this->_component);
         if ($approvalMessage && CRM_Utils_Array::value('status_id', $params) == 1) {
             $notifyStatus .= ts(' You will receive a second email as soon as the review process is complete.');
         }
     }
     //check if pcp created by anonymous user
     $anonymousPCP = 0;
     if (!$session->get('userID')) {
         $anonymousPCP = 1;
     }
     CRM_Core_Session::setStatus(ts("Your Personal Campaign Page has been %1 %2 %3", array(1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus)), '', 'info');
     if (!$this->_pageId) {
         $session->pushUserContext(CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcp->id}&ap={$anonymousPCP}"));
     } elseif ($this->_context == 'dashboard') {
         $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/pcp', 'reset=1'));
     }
 }
Esempio n. 13
0
 /**
  * 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 processMandrillCalls($reponse)
 {
     $events = array('open', 'click', 'hard_bounce', 'soft_bounce', 'spam', 'reject');
     $bounceType = array();
     //MTE-17
     $config = CRM_Core_Config::singleton();
     if (property_exists($config, 'civiVersion')) {
         $civiVersion = $config->civiVersion;
     } else {
         $civiVersion = CRM_Core_BAO_Domain::version();
     }
     if (version_compare('4.4alpha1', $civiVersion) > 0) {
         $jobCLassName = 'CRM_Mailing_DAO_Job';
     } else {
         $jobCLassName = 'CRM_Mailing_DAO_MailingJob';
     }
     foreach ($reponse as $value) {
         //changes done to check if email exists in response array
         if (in_array($value['event'], $events) && CRM_Utils_Array::value('email', $value['msg'])) {
             $metaData = CRM_Utils_Array::value('metadata', $value['msg']) ? CRM_Utils_Array::value('CiviCRM_Mandrill_id', $value['msg']['metadata']) : NULL;
             $header = self::extractHeader($metaData);
             $mail = self::getMailing($header, $jobCLassName);
             $contacts = array();
             if ($mail->find(TRUE)) {
                 if ($value['event'] == 'click' && $mail->url_tracking === FALSE || $value['event'] == 'open' && $mail->open_tracking === FALSE) {
                     continue;
                 }
                 $emails = self::retrieveEmailContactId($value['msg']['email']);
                 if (!CRM_Utils_Array::value('contact_id', $emails['email'])) {
                     continue;
                 }
                 $value['mailing_id'] = $mail->id;
                 // IF no activity id in header then create new activity
                 if (empty($header[0])) {
                     self::createActivity($value, NULL, $header);
                 }
                 if (empty($header[2])) {
                     $params = array('job_id' => CRM_Core_DAO::getFieldValue($jobCLassName, $mail->id, 'id', 'mailing_id'), 'contact_id' => $emails['email']['contact_id'], 'email_id' => $emails['email']['id']);
                     $eventQueue = CRM_Mailing_Event_BAO_Queue::create($params);
                     $eventQueueID = $eventQueue->id;
                     $hash = $eventQueue->hash;
                     $jobId = $params['job_id'];
                 } else {
                     $eventQueueID = $header[3];
                     $hash = explode('@', $header[4]);
                     $hash = $hash[0];
                     $jobId = $header[2];
                 }
                 if ($eventQueueID) {
                     $mandrillActivtyParams = array('mailing_queue_id' => $eventQueueID, 'activity_id' => $header[0]);
                     CRM_Mte_BAO_MandrillActivity::create($mandrillActivtyParams);
                 }
                 $msgBody = '';
                 if (!empty($header[0])) {
                     $msgBody = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $header[0], 'details');
                 }
                 $value['mail_body'] = $msgBody;
                 $bType = ucfirst(preg_replace('/_\\w+/', '', $value['event']));
                 $assignedContacts = array();
                 switch ($value['event']) {
                     case 'open':
                         $oe = new CRM_Mailing_Event_BAO_Opened();
                         $oe->event_queue_id = $eventQueueID;
                         $oe->time_stamp = date('YmdHis', $value['ts']);
                         $oe->save();
                         break;
                     case 'click':
                         if (CRM_Utils_Array::value(1, $header) == 'b') {
                             break;
                         }
                         $tracker = new CRM_Mailing_BAO_TrackableURL();
                         $tracker->url = $value['url'];
                         $tracker->mailing_id = $mail->id;
                         if (!$tracker->find(TRUE)) {
                             $tracker->save();
                         }
                         $open = new CRM_Mailing_Event_BAO_TrackableURLOpen();
                         $open->event_queue_id = $eventQueueID;
                         $open->trackable_url_id = $tracker->id;
                         $open->time_stamp = date('YmdHis', $value['ts']);
                         $open->save();
                         break;
                     case 'hard_bounce':
                     case 'soft_bounce':
                     case 'spam':
                     case 'reject':
                         if (empty($bounceType)) {
                             CRM_Core_PseudoConstant::populate($bounceType, 'CRM_Mailing_DAO_BounceType', TRUE, 'id', NULL, NULL, NULL, 'name');
                         }
                         //Delete queue in delivered since this email is not successfull
                         $delivered = new CRM_Mailing_Event_BAO_Delivered();
                         $delivered->event_queue_id = $eventQueueID;
                         if ($delivered->find(TRUE)) {
                             $delivered->delete();
                         }
                         $bounceParams = array('time_stamp' => date('YmdHis', $value['ts']), 'event_queue_id' => $eventQueueID, 'bounce_type_id' => $bounceType["Mandrill {$bType}"], 'job_id' => $jobId, 'hash' => $hash);
                         $bounceParams['bounce_reason'] = CRM_Utils_Array::value('bounce_description', $value['msg']);
                         if (empty($bounceParams['bounce_reason'])) {
                             $bounceParams['bounce_reason'] = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_BounceType', $bounceType["Mandrill {$bType}"], 'description');
                         }
                         CRM_Mailing_Event_BAO_Bounce::create($bounceParams);
                         if (substr($value['event'], -7) == '_bounce') {
                             $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mandrill_smtp_settings');
                             if (CRM_Utils_Array::value('group_id', $mailingBackend)) {
                                 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
                                 $mailBody = ts('The following email failed to be delivered due to a') . " {$bType} Bounce :</br>\nTo: {$value['msg']['email']} </br>\nFrom: {$value['msg']['sender']} </br>\nSubject: {$value['msg']['subject']}</br>\nMessage Body: {$msgBody}";
                                 $mailParams = array('groupName' => 'Mandrill bounce notification', 'from' => '"' . $domainEmailName . '" <' . $domainEmailAddress . '>', 'subject' => ts('Mandrill Bounce Notification'), 'text' => $mailBody, 'html' => $mailBody);
                                 $query = "SELECT ce.email, cc.sort_name, cgc.contact_id FROM civicrm_contact cc\nINNER JOIN civicrm_group_contact cgc ON cgc.contact_id = cc.id\nINNER JOIN civicrm_email ce ON ce.contact_id = cc.id\nWHERE cc.is_deleted = 0 AND cc.is_deceased = 0 AND cgc.group_id = {$mailingBackend['group_id']} AND ce.is_primary = 1 AND ce.email <> %1";
                                 $queryParam = array(1 => array($value['msg']['email'], 'String'));
                                 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
                                 while ($dao->fetch()) {
                                     $mailParams['toName'] = $dao->sort_name;
                                     $mailParams['toEmail'] = $dao->email;
                                     CRM_Utils_Mail::send($mailParams);
                                     $value['assignee_contact_id'][] = $dao->contact_id;
                                 }
                             }
                         }
                         $bType = 'Bounce';
                         break;
                 }
                 // create activity for click and open event
                 if ($value['event'] == 'open' || $value['event'] == 'click' || $bType == 'Bounce') {
                     self::createActivity($value, $bType, $header);
                 }
             }
         }
     }
 }
Esempio n. 15
0
 /**
  * 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();
 }
Esempio n. 16
0
 /**
  * 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);
     }
 }
Esempio n. 17
0
 /**
  * Process membership records.
  *
  * @param array $params
  *   Associated array of submitted values.
  *
  *
  * @return bool
  */
 private function processMembership(&$params)
 {
     $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate');
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     // get the price set associated with offline membership
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
     $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             foreach ($dateTypes as $dateField => $dateVariable) {
                 ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]);
                 $fDate[$dateField] = CRM_Utils_Array::value($dateField, $value);
             }
             $calcDates = array();
             $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate);
             foreach ($calcDates as $memType => $calcDate) {
                 foreach ($dates as $d) {
                     //first give priority to form values then calDates.
                     $date = CRM_Utils_Array::value($d, $value);
                     if (!$date) {
                         $date = CRM_Utils_Array::value($d, $calcDate);
                     }
                     $value[$d] = CRM_Utils_Date::processDate($date);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             if (!empty($value['membership_status'])) {
                 $value['status_id'] = $value['membership_status'];
                 unset($value['membership_status']);
             }
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $key, 'Membership', $membershipTypeId);
             if (!empty($value['financial_type'])) {
                 $value['financial_type_id'] = $value['financial_type'];
             }
             if (!empty($value['payment_instrument'])) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             // handle soft credit
             if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
                 //CRM-15350: if soft-credit-type profile field is disabled or removed then
                 //we choose Gift as default value as per Gift Membership rule
                 if (!empty($params['soft_credit_type'][$key])) {
                     $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
                 } else {
                     $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'Gift', 'name');
                 }
             }
             if (!empty($value['receive_date'])) {
                 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             unset($value['financial_type']);
             unset($value['payment_instrument']);
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // make entry in line item for contribution
             $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]);
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (!empty($editedResults)) {
                 unset($this->_priceSet['fields']);
                 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
                 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
                 $fid = $editedResults['id'];
                 $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']);
                 $editedResults = array();
                 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
                 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
                 if (!empty($value['total_amount'])) {
                     $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
                 }
                 $fieldID = key($this->_priceSet['fields']);
                 $value['price_' . $fieldID] = $editedResults['id'];
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
                 //CRM-11529 for backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                     foreach ($lineItem[$priceSetId] as &$values) {
                         $values['financial_type_id'] = $value['financial_type_id'];
                     }
                 }
                 $value['lineItems'] = $lineItem;
                 $value['processPriceSet'] = TRUE;
             }
             // end of contribution related section
             unset($value['membership_type']);
             unset($value['membership_start_date']);
             unset($value['membership_end_date']);
             $value['is_renew'] = FALSE;
             if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
                 // The following parameter setting may be obsolete.
                 $this->_params = $params;
                 $value['is_renew'] = TRUE;
                 $isPayLater = CRM_Utils_Array::value('is_pay_later', $params);
                 $campaignId = NULL;
                 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
                     $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
                     if (!array_key_exists('campaign_id', $this->_params)) {
                         $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
                     }
                 }
                 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
                     //CRM-18000 - ignore $dateType if its not explicitly passed
                     if (!empty($fDate[$dateType]) || !empty($fDate['membership_' . $dateType])) {
                         $formDates[$dateType] = CRM_Utils_Array::value($dateType, $value);
                     }
                 }
                 $membershipSource = CRM_Utils_Array::value('source', $value);
                 list($membership) = CRM_Member_BAO_Membership::renewMembership($value['contact_id'], $value['membership_type_id'], FALSE, NULL, NULL, $value['custom'], 1, NULL, FALSE, NULL, $membershipSource, $isPayLater, $campaignId, $formDates);
                 // make contribution entry
                 $contrbutionParams = array_merge($value, array('membership_id' => $membership->id));
                 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
                 // This form should set the correct params & not call this fn directly.
                 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
             } else {
                 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'), 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($membership->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['membership_id'] = $membership->id;
                 $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
                 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
             }
         }
     }
     return TRUE;
 }
Esempio n. 18
0
 /**
  * Process that send notification e-mails
  *
  * @param int $contactID
  *   Contact id.
  * @param array $values
  *   Associative array of name/value pair.
  */
 public static function commonSendMail($contactID, &$values)
 {
     if (!$contactID || !$values) {
         return;
     }
     $template = CRM_Core_Smarty::singleton();
     $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
     self::profileDisplay($values['id'], $values['values'], $template);
     $emailList = explode(',', $values['email']);
     $contactLink = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contactID}", TRUE, NULL, FALSE, FALSE, TRUE);
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') {
         $fixUrl = CRM_Utils_System::url('civicrm/admin/domain', 'action=update&reset=1');
         CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl)));
     }
     foreach ($emailList as $emailTo) {
         // FIXME: take the below out of the foreach loop
         CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_uf', 'valueName' => 'uf_notify', 'contactId' => $contactID, 'tplParams' => array('displayName' => $displayName, 'currentDate' => date('r'), 'contactLink' => $contactLink), 'from' => "{$domainEmailName} <{$domainEmailAddress}>", 'toEmail' => $emailTo));
     }
 }
Esempio n. 19
0
 /**
  * Build From Email as the combination of all the email ids of the logged in user,
  * the domain email id and the email id configured for the event
  * 
  * @param int $eventId   the id of the event
  * 
  * @return array         an array of email ids
  * @access public
  * @static
  */
 static function getFromEmailIds($eventId = null)
 {
     static $emails;
     $session = CRM_Core_Session::singleton();
     $contactID = $session->get('userID');
     $cacheKey = 'd';
     if ($eventId) {
         $cacheKey .= '_eid_' . $eventId;
     }
     if ($contactID) {
         $cacheKey .= '_cid_' . $contactID;
     }
     $fromEmailValues = $fromEmailIds = $eventEmail = $contactEmails = array();
     if (isset($emails[$cacheKey])) {
         return $emails[$cacheKey];
     }
     if ($eventId) {
         // add the email id configured for the event
         $params = array('id' => $eventId);
         $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
         CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
         if (CRM_Utils_Array::value('confirm_from_name', $eventEmail) && CRM_Utils_Array::value('confirm_from_email', $eventEmail)) {
             $fromEmailValues[] = $fromEmailIds[] = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
         }
     }
     // add the domain email id
     require_once 'CRM/Core/BAO/Domain.php';
     $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
     $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
     if (!in_array($domainEmail, $fromEmailIds)) {
         $fromEmailValues[] = $fromEmailIds[] = $domainEmail;
     }
     require_once 'CRM/Core/BAO/Email.php';
     // add logged in user's active email ids
     if ($contactID) {
         $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
         $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
         foreach ($contactEmails as $emailId => $emailVal) {
             $email = trim($emailVal['email']);
             if (!$email || $emailVal['on_hold']) {
                 continue;
             }
             $fromEmail = "{$fromDisplayName} <{$email}>";
             if (!in_array($fromEmail, $fromEmailIds)) {
                 $fromEmailValues[$emailId] = $fromEmailIds[] = $fromEmail;
                 $fromEmailValues[$emailId] .= $emailVal['locationType'];
                 if (CRM_Utils_Array::value('is_primary', $emailVal)) {
                     $fromEmailValues[$emailId] .= ' ' . ts('(preferred)');
                 }
             }
         }
     }
     foreach ($fromEmailValues as $key => $value) {
         $emailValues[] = htmlspecialchars($value);
     }
     $emails[$cacheKey] = array('name' => $fromEmailIds, 'label' => $emailValues, 'cc' => CRM_Utils_Array::value('cc_confirm', $eventEmail), 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventEmail));
     return $emails[$cacheKey];
 }
Esempio n. 20
0
 /**
  * Ask a contact for subscription confirmation (opt-in)
  *
  * @param string $email
  *   The email address.
  *
  * @return void
  */
 public function send_confirm_request($email)
 {
     $config = CRM_Core_Config::singleton();
     $domain = CRM_Core_BAO_Domain::getDomain();
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $confirm = implode($config->verpSeparator, array($localpart . 'c', $this->contact_id, $this->id, $this->hash)) . "@{$emailDomain}";
     $group = new CRM_Contact_BAO_Group();
     $group->id = $this->group_id;
     $group->find(TRUE);
     $component = new CRM_Mailing_BAO_Component();
     $component->is_default = 1;
     $component->is_active = 1;
     $component->component_type = 'Subscribe';
     $component->find(TRUE);
     $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'To' => $email, 'Reply-To' => $confirm, 'Return-Path' => "do-not-reply@{$emailDomain}");
     $url = CRM_Utils_System::url('civicrm/mailing/confirm', "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}", TRUE);
     $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::replaceSubscribeTokens($html, $group->title, $url, TRUE);
     $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
     $text = CRM_Utils_Token::replaceSubscribeTokens($text, $group->title, $url, FALSE);
     // render the &amp; entities in text mode, so that the links work
     $text = str_replace('&amp;', '&', $text);
     $message = new Mail_mime("\n");
     $message->setHTMLBody($html);
     $message->setTxtBody($text);
     $b = CRM_Utils_Mail::setMimeParams($message);
     $h = $message->headers($headers);
     CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 's', $this->contact_id, $this->id, $this->hash);
     $mailer = \Civi::service('pear_mail');
     if (is_object($mailer)) {
         $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
         $mailer->send($email, $h, $b);
         unset($errorScope);
     }
 }
Esempio n. 21
0
 /**
  * Complete an order.
  *
  * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
  *
  * Currently overloaded to complete a transaction & repeat a transaction - fix!
  *
  * Moving it out of the BaseIPN class is just the first step.
  *
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param CRM_Core_Transaction $transaction
  * @param int $recur
  * @param CRM_Contribute_BAO_Contribution $contribution
  * @param bool $isRecurring
  *   Duplication of param needs review. Only used by AuthorizeNetIPN
  * @param int $isFirstOrLastRecurringPayment
  *   Deprecated param only used by AuthorizeNetIPN.
  */
 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment)
 {
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     // The previous details are used when calculating line items so keep it before any code that 'does something'
     if (!empty($contribution->id)) {
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date');
     $contributionParams = array_merge(array('contribution_status_id' => 'Completed'), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)));
     $participant = CRM_Utils_Array::value('participant', $objects);
     $memberships = CRM_Utils_Array::value('membership', $objects);
     $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
     if (!empty($recurContrib->id)) {
         $contributionParams['contribution_recur_id'] = $recurContrib->id;
     }
     self::repeatTransaction($contribution, $input, $contributionParams);
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contributionParams['contribution_page_id'] = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         if (!empty($values['is_email_receipt'])) {
             $contributionParams['receipt_date'] = $changeDate;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id);
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membershipParams['id']}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = CRM_Core_DAO::executeQuery($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membershipParams['membership_type_id'] = $dao->membership_type_id;
                         }
                     }
                     $dao->free();
                     $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID);
                     $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']);
                         $dates['join_date'] = $currentMembership['join_date'];
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams);
                     $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
                     //we might be renewing membership,
                     //so make status override false.
                     $membershipParams['is_override'] = FALSE;
                     civicrm_api3('Membership', 'create', $membershipParams);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams);
                 }
             }
         }
     } else {
         if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
             $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id));
             $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
             if ($eventDetail['is_email_confirm']) {
                 // @todo this should be set by the function that sends the mail after sending.
                 $contributionParams['receipt_date'] = $changeDate;
             }
             $participantParams['id'] = $participant->id;
             $participantParams['status_id'] = 'Registered';
             civicrm_api3('Participant', 'create', $participantParams);
         }
     }
     $contributionParams['id'] = $contribution->id;
     civicrm_api3('Contribution', 'create', $contributionParams);
     // Add new soft credit against current $contribution.
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
     }
     $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending']) {
         $input['payment_processor'] = $paymentProcessorId;
     }
     $input['contribution_status_id'] = $contributionStatuses['Completed'];
     $input['total_amount'] = $input['amount'];
     $input['contribution'] = $contribution;
     $input['financial_type_id'] = $contribution->financial_type_id;
     if (!empty($contribution->_relatedObjects['participant'])) {
         $input['contribution_mode'] = 'participant';
         $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
         $input['skipLineItem'] = 1;
     } elseif (!empty($contribution->_relatedObjects['membership'])) {
         $input['skipLineItem'] = TRUE;
         $input['contribution_mode'] = 'membership';
     }
     //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
     // and subsequent payments. In this case the line items are created at
     // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
     // and since the contribution is saved prior to this line there is always a contribution-id,
     // however there is never a prevContribution (which appears to mean original contribution not previous
     // contribution - or preUpdateContributionObject most accurately)
     // so, this is always called & only appears to succeed when prevContribution exists - which appears
     // to mean "are we updating an exisitng pending contribution"
     //I was able to make the unit test complete as fataling here doesn't prevent
     // the contribution being created - but activities would not be created or emails sent
     CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (!empty($ids['related_contact'])) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
     if ($isRecurring) {
         CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment);
     }
 }
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['contribution_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format), 'reminder_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('reminder_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $memberships[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $addLineItems = FALSE;
     if (empty($contribution->id)) {
         $addLineItems = TRUE;
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     $contribution->save();
     //add lineitems for recurring payments
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
         $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
         }
     }
     if ($contribution->trxn_id) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id);
         $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
     }
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
Esempio n. 23
0
 /**
  * Takes an associative array and creates a friend object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return void
  */
 public static function create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     $mailParams = array();
     //create contact corresponding to each friend
     foreach ($params['friend'] as $key => $details) {
         if ($details["first_name"]) {
             $contactParams[$key] = array('first_name' => $details["first_name"], 'last_name' => $details["last_name"], 'contact_source' => ts('Tell a Friend') . ": {$params['title']}", 'email-Primary' => $details["email"]);
             $displayName = $details["first_name"] . " " . $details["last_name"];
             $mailParams['email'][$displayName] = $details["email"];
         }
     }
     $frndParams = array();
     $frndParams['entity_id'] = $params['entity_id'];
     $frndParams['entity_table'] = $params['entity_table'];
     self::getValues($frndParams);
     $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'Tell a Friend', 'value', 'name');
     //create activity
     $activityParams = array('source_contact_id' => $params['source_contact_id'], 'source_record_id' => NULL, 'activity_type_id' => $activityTypeId, 'title' => $params['title'], 'activity_date_time' => date("YmdHis"), 'subject' => ts('Tell a Friend') . ": {$params['title']}", 'details' => $params['suggested_message'], 'status_id' => 2, 'is_test' => $params['is_test'], 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params));
     //activity creation
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
     //friend contacts creation
     foreach ($contactParams as $key => $value) {
         //create contact only if it does not exits in db
         $value['email'] = $value['email-Primary'];
         $value['check_permission'] = FALSE;
         $contact = CRM_Core_BAO_UFGroup::findContact($value, NULL, 'Individual');
         if (!$contact) {
             $contact = self::add($value);
         }
         // attempt to save activity targets
         $targetParams = array('activity_id' => $activity->id, 'contact_id' => $contact, 'record_type_id' => $targetID);
         // See if it already exists
         $activityContact = new CRM_Activity_DAO_ActivityContact();
         $activityContact->activity_id = $activity->id;
         $activityContact->contact_id = $contact;
         $activityContact->find(TRUE);
         if (empty($activityContact->id)) {
             $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
         }
     }
     $transaction->commit();
     //process sending of mails
     $mailParams['title'] = CRM_Utils_Array::value('title', $params);
     $mailParams['general_link'] = CRM_Utils_Array::value('general_link', $frndParams);
     $mailParams['message'] = CRM_Utils_Array::value('suggested_message', $params);
     // get domain
     $domainDetails = CRM_Core_BAO_Domain::getNameAndEmail();
     list($username, $mailParams['domain']) = explode('@', $domainDetails[1]);
     $default = array();
     $findProperties = array('id' => $params['entity_id']);
     if ($params['entity_table'] == 'civicrm_contribution_page') {
         $returnProperties = array('receipt_from_email', 'is_email_receipt');
         CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $findProperties, $default, $returnProperties);
         //if is_email_receipt is set then take receipt_from_email
         //as from_email
         if (!empty($default['is_email_receipt']) && !empty($default['receipt_from_email'])) {
             $mailParams['email_from'] = $default['receipt_from_email'];
         }
         $urlPath = 'civicrm/contribute/transact';
         $mailParams['module'] = 'contribute';
     } elseif ($params['entity_table'] == 'civicrm_event') {
         $returnProperties = array('confirm_from_email', 'is_email_confirm');
         CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $findProperties, $default, $returnProperties);
         $mailParams['email_from'] = $domainDetails['1'];
         //if is_email_confirm is set then take confirm_from_email
         //as from_email
         if (!empty($default['is_email_confirm']) && !empty($default['confirm_from_email'])) {
             $mailParams['email_from'] = $default['confirm_from_email'];
         }
         $urlPath = 'civicrm/event/info';
         $mailParams['module'] = 'event';
     } elseif ($params['entity_table'] == 'civicrm_pcp') {
         $mailParams['email_from'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $params['source_contact_id'], 'email', 'contact_id');
         $urlPath = 'civicrm/pcp/info';
         $mailParams['module'] = 'contribute';
     }
     $mailParams['page_url'] = CRM_Utils_System::url($urlPath, "reset=1&id={$params['entity_id']}", TRUE, NULL, FALSE, TRUE);
     //send mail
     self::sendMail($params['source_contact_id'], $mailParams);
 }
Esempio n. 24
0
File: PCP.php Progetto: kidaa30/yes
 /**
  * Send notfication email to supporter
  * 1. when their PCP status is changed by site admin.
  * 2. when supporter initially creates a Personal Campaign Page ($isInitial set to true).
  *
  * @param int $pcpId
  *   Campaign page id.
  * @param int $newStatus
  *   Pcp status id.
  * @param bool|int $isInitial is it the first time, campaign page has been created by the user
  *
  * @param string $component
  *
  * @throws Exception
  * @return null
  */
 public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE, $component = 'contribute')
 {
     $pcpStatusName = CRM_Core_OptionGroup::values("pcp_status", FALSE, FALSE, FALSE, NULL, 'name');
     $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
     $config = CRM_Core_Config::singleton();
     if (!isset($pcpStatus[$newStatus])) {
         return FALSE;
     }
     require_once 'Mail/mime.php';
     //set loginUrl
     $loginURL = $config->userSystem->getLoginURL();
     // used in subject templates
     $contribPageTitle = self::getPcpPageTitle($pcpId, $component);
     $tplParams = array('loginUrl' => $loginURL, 'contribPageTitle' => $contribPageTitle, 'pcpId' => $pcpId);
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') {
         $fixUrl = CRM_Utils_System::url("civicrm/admin/domain", 'action=update&reset=1');
         CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl)));
     }
     $receiptFrom = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
     // get recipient (supporter) name and email
     $params = array('id' => $pcpId);
     CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
     list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($pcpInfo['contact_id']);
     // get pcp block info
     list($blockId, $eid) = self::getPcpBlockEntityId($pcpId, $component);
     $params = array('id' => $blockId);
     CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlockInfo);
     // assign urls required in email template
     if ($pcpStatusName[$newStatus] == 'Approved') {
         $tplParams['isTellFriendEnabled'] = $pcpBlockInfo['is_tellfriend_enabled'];
         if ($pcpBlockInfo['is_tellfriend_enabled']) {
             $pcpTellFriendURL = CRM_Utils_System::url('civicrm/friend', "reset=1&eid={$pcpId}&blockId={$blockId}&pcomponent=pcp", TRUE, NULL, FALSE, TRUE);
             $tplParams['pcpTellFriendURL'] = $pcpTellFriendURL;
         }
     }
     $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcpId}", TRUE, NULL, FALSE, TRUE);
     $tplParams['pcpInfoURL'] = $pcpInfoURL;
     $tplParams['contribPageTitle'] = $contribPageTitle;
     if ($emails = CRM_Utils_Array::value('notify_email', $pcpBlockInfo)) {
         $emailArray = explode(',', $emails);
         $tplParams['pcpNotifyEmailAddress'] = $emailArray[0];
     }
     // get appropriate message based on status
     $tplParams['pcpStatus'] = $pcpStatus[$newStatus];
     $tplName = $isInitial ? 'pcp_supporter_notify' : 'pcp_status_change';
     list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => $tplName, 'contactId' => $pcpInfo['contact_id'], 'tplParams' => $tplParams, 'from' => $receiptFrom, 'toName' => $name, 'toEmail' => $address));
     return $sent;
 }
Esempio n. 25
0
 static function mailReport($fileContent, $instanceID = NULL, $outputMode = 'html', $attachments = array())
 {
     if (!$instanceID) {
         return FALSE;
     }
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $params = array('id' => $instanceID);
     $instanceInfo = array();
     CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance', $params, $instanceInfo);
     $params = array();
     $params['groupName'] = 'Report Email Sender';
     $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
     //$domainEmailName;
     $params['toName'] = "";
     $params['toEmail'] = CRM_Utils_Array::value('email_to', $instanceInfo);
     $params['cc'] = CRM_Utils_Array::value('email_cc', $instanceInfo);
     $params['subject'] = CRM_Utils_Array::value('email_subject', $instanceInfo);
     if (empty($instanceInfo['attachments'])) {
         $instanceInfo['attachments'] = array();
     }
     $params['attachments'] = array_merge(CRM_Utils_Array::value('attachments', $instanceInfo), $attachments);
     $params['text'] = '';
     $params['html'] = $fileContent;
     return CRM_Utils_Mail::send($params);
 }
 /**
  * Send the emails for Recurring Contribution Notication.
  *
  * @param string $type
  *   TxnType.
  * @param int $contactID
  *   Contact id for contributor.
  * @param int $pageID
  *   Contribution page id.
  * @param object $recur
  *   Object of recurring contribution table.
  * @param bool|object $autoRenewMembership is it a auto renew membership.
  *
  * @return void
  */
 public static function recurringNotify($type, $contactID, $pageID, $recur, $autoRenewMembership = FALSE)
 {
     $value = array();
     if ($pageID) {
         CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $pageID, $value, array('title', 'is_email_receipt', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt'));
     }
     $isEmailReceipt = CRM_Utils_Array::value('is_email_receipt', $value[$pageID]);
     $isOfflineRecur = FALSE;
     if (!$pageID && $recur->id) {
         $isOfflineRecur = TRUE;
     }
     if ($isEmailReceipt || $isOfflineRecur) {
         if ($pageID) {
             $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$pageID]) . '" <' . $value[$pageID]['receipt_from_email'] . '>';
             $receiptFromName = $value[$pageID]['receipt_from_name'];
             $receiptFromEmail = $value[$pageID]['receipt_from_email'];
         } else {
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>";
             $receiptFromName = $domainValues[0];
             $receiptFromEmail = $domainValues[1];
         }
         list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE);
         $templatesParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_recurring_notify', 'contactId' => $contactID, 'tplParams' => array('recur_frequency_interval' => $recur->frequency_interval, 'recur_frequency_unit' => $recur->frequency_unit, 'recur_installments' => $recur->installments, 'recur_start_date' => $recur->start_date, 'recur_end_date' => $recur->end_date, 'recur_amount' => $recur->amount, 'recur_txnType' => $type, 'displayName' => $displayName, 'receipt_from_name' => $receiptFromName, 'receipt_from_email' => $receiptFromEmail, 'auto_renew_membership' => $autoRenewMembership), 'from' => $receiptFrom, 'toName' => $displayName, 'toEmail' => $email);
         //CRM-13811
         if ($pageID) {
             $templatesParams['cc'] = CRM_Utils_Array::value('cc_receipt', $value[$pageID]);
             $templatesParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $value[$pageID]);
         }
         if ($recur->id) {
             // in some cases its just recurringNotify() thats called for the first time and these urls don't get set.
             // like in PaypalPro, & therefore we set it here additionally.
             $template = CRM_Core_Smarty::singleton();
             $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
             $url = $paymentProcessor->subscriptionURL($recur->id, 'recur');
             $template->assign('cancelSubscriptionUrl', $url);
             $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'billing');
             $template->assign('updateSubscriptionBillingUrl', $url);
             $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'update');
             $template->assign('updateSubscriptionUrl', $url);
         }
         list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams);
         if ($sent) {
             CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.');
         } else {
             CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.');
         }
     }
 }
Esempio n. 27
0
 /**
  * process membership records
  *
  * @param array $params associated array of submitted values
  *
  * @access public
  *
  * @return bool
  */
 private function processMembership(&$params)
 {
     $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate');
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     // get the price set associated with offline memebership
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
     $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             foreach ($dateTypes as $dateField => $dateVariable) {
                 ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]);
             }
             $calcDates = array();
             $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate);
             foreach ($calcDates as $memType => $calcDate) {
                 foreach ($dates as $d) {
                     //first give priority to form values then calDates.
                     $date = CRM_Utils_Array::value($d, $value);
                     if (!$date) {
                         $date = CRM_Utils_Array::value($d, $calcDate);
                     }
                     $value[$d] = CRM_Utils_Date::processDate($date);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             if (!empty($value['membership_status'])) {
                 $value['status_id'] = $value['membership_status'];
                 unset($value['membership_status']);
             }
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membershipTypeId);
             if (!empty($value['financial_type'])) {
                 $value['financial_type_id'] = $value['financial_type'];
             }
             if (!empty($value['payment_instrument'])) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             // handle soft credit
             if (is_array(CRM_Utils_Array::value('soft_credit_contact_id', $params)) && !empty($params['soft_credit_contact_id'][$key]) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
             }
             if (!empty($value['receive_date'])) {
                 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             unset($value['financial_type']);
             unset($value['payment_instrument']);
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // make entry in line item for contribution
             $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]);
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (!empty($editedResults)) {
                 unset($this->_priceSet['fields']);
                 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
                 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
                 $fid = $editedResults['id'];
                 $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']);
                 $editedResults = array();
                 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
                 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
                 if (!empty($value['total_amount'])) {
                     $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
                 }
                 $fieldID = key($this->_priceSet['fields']);
                 $value['price_' . $fieldID] = $editedResults['id'];
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
                 //CRM-11529 for backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                     foreach ($lineItem[$priceSetId] as &$values) {
                         $values['financial_type_id'] = $value['financial_type_id'];
                     }
                 }
                 $value['lineItems'] = $lineItem;
                 $value['processPriceSet'] = TRUE;
             }
             // end of contribution related section
             unset($value['membership_type']);
             unset($value['membership_start_date']);
             unset($value['membership_end_date']);
             $value['is_renew'] = false;
             if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
                 $this->_params = $params;
                 $value['is_renew'] = true;
                 $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($value['contact_id'], $value['membership_type_id'], FALSE, $this, NULL, NULL, $value['custom']);
                 // make contribution entry
                 CRM_Member_BAO_Membership::recordMembershipContribution(array_merge($value, array('membership_id' => $membership->id)));
             } else {
                 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $value['contribution_id'], 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($membership->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['membership_id'] = $membership->id;
                 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
             }
         }
     }
     return TRUE;
 }
Esempio n. 28
0
/**
 * Calls IPN complete transaction for completing or repeating a transaction.
 *
 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
 * when separating them in the api layer.
 *
 * @param array $params
 * @param CRM_Contribute_BAO_Contribution $contribution
 * @param array $input
 *
 * @param array $ids
 *
 * @param CRM_Contribute_BAO_Contribution $firstContribution
 *
 * @return mixed
 */
function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL)
{
    $objects = $contribution->_relatedObjects;
    $objects['contribution'] =& $contribution;
    if ($firstContribution) {
        $objects['first_contribution'] = $firstContribution;
    }
    $input['component'] = $contribution->_component;
    $input['is_test'] = $contribution->is_test;
    $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
    if (isset($params['is_email_receipt'])) {
        $input['is_email_receipt'] = $params['is_email_receipt'];
    }
    if (!empty($params['trxn_date'])) {
        $input['trxn_date'] = $params['trxn_date'];
    }
    if (empty($contribution->contribution_page_id)) {
        static $domainFromName;
        static $domainFromEmail;
        if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
            list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
        }
        $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
        $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
    }
    $transaction = new CRM_Core_Transaction();
    CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id), $contribution, FALSE, FALSE);
    return $params;
}
Esempio n. 29
0
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     $source = NULL;
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             $membershipsUpdate = array();
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $membershipsUpdate[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
             //update the memberships object with updated membershipTypeId data
             //if membershipTypeId has changed after membership update
             if (!empty($membershipsUpdate)) {
                 $memberships = $memberships + $membershipsUpdate;
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
         //and cases involving status updation through ipn
         $values['totalAmount'] = $input['amount'];
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
             $participant->status_id = 1;
         }
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     // This complete transaction function is being overloaded to create new contributions too.
     // here we record if it is a new contribution.
     // @todo separate the 2 more appropriately.
     $isNewContribution = FALSE;
     if (empty($contribution->id)) {
         $isNewContribution = TRUE;
         if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
             $contribution->total_amount = $input['amount'];
             // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
             // so we have to handle net_amount in this (naughty) code.
             if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
                 $contribution->fee_amount = $input['fee_amount'];
             }
             $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
         }
         if (!empty($input['campaign_id'])) {
             $contribution->campaign_id = $input['campaign_id'];
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     // @todo this section should call the api  in order to have hooks called &
     // because all this 'messiness' setting variables could be avoided
     // by letting the api resolve pseudoconstants & copy set values and format dates.
     $contribution->contribution_status_id = $contributionStatuses['Completed'];
     $contribution->is_test = $input['is_test'];
     // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
     if (isset($input['net_amount'])) {
         $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     }
     if (isset($input['net_amount'])) {
         $contribution->net_amount = $input['net_amount'];
     }
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     if (!empty($contribution->id)) {
         $contributionId['id'] = $contribution->id;
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $contribution->save();
     //add line items for recurring payments
     if (!empty($contribution->contribution_recur_id)) {
         if ($isNewContribution) {
             $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
         } else {
             // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
             $input['line_item'] = array();
         }
         if (!empty($memberships) && $primaryContributionID != $contribution->id) {
             foreach ($memberships as $membership) {
                 try {
                     $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id);
                     if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) {
                         civicrm_api3('membership_payment', 'create', $membershipPayment);
                     }
                 } catch (CiviCRM_API3_Exception $e) {
                     echo $e->getMessage();
                     // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
                     // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
                 }
             }
         }
     }
     //copy initial contribution custom fields for recurring contributions
     if ($recurContrib && $recurContrib->id) {
         $this->copyCustomValues($recurContrib->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
     // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
     // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
     // it would be good if someone added some comments or refactored this
     if ($contribution->id) {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
             $input['payment_processor'] = $paymentProcessorId;
         }
         $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
         $input['total_amount'] = $input['amount'];
         $input['contribution'] = $contribution;
         $input['financial_type_id'] = $contribution->financial_type_id;
         if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) {
             $input['contribution_mode'] = 'participant';
             $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
             $input['skipLineItem'] = 1;
         }
         //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
         // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
         // and since the contribution is saved prior to this line there is always a contribution-id,
         // however there is never a prevContribution (which appears to mean original contribution not previous
         // contribution - or preUpdateContributionObject most accurately)
         // so, this is always called & only appears to succeed when prevContribution exists - which appears
         // to mean "are we updating an exisitng pending contribution"
         //I was able to make the unit test complete as fataling here doesn't prevent
         // the contribution being created - but activities would not be created or emails sent
         CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
 }
Esempio n. 30
0
 /**
  * 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();
     }
 }