/**
 * 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);
}
 public static function formRule($params)
 {
     $currentVer = CRM_Core_BAO_Domain::version(TRUE);
     $errors = array();
     if (version_compare($currentVer, '4.4') < 0) {
         $errors['version_error'] = " You need to upgrade to version 4.4 or above to work with extension Mailchimp";
     }
     return empty($errors) ? TRUE : $errors;
 }
 public function preProcess()
 {
     $version = CRM_Core_BAO_Domain::version();
     if (version_compare($version, '4.5', '<')) {
         $this->use_old_contact_ref_fields = true;
     }
     parent::preProcess();
     // TODO: Change the autogenerated stub
 }
Example #4
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;
 }
 private function invoke($fnSuffix, $numParams, &$arg1 = null, &$arg2 = null, &$arg3 = null, &$arg4 = null, &$arg5 = null)
 {
     $hook = CRM_Utils_Hook::singleton();
     $civiVersion = CRM_Core_BAO_Domain::version();
     if (version_compare('4.4', $civiVersion, '<=')) {
         //in CiviCRM 4.4 the invoke function has 5 arguments maximum
         return $hook->invoke($numParams, $arg1, $arg2, $arg3, $arg4, $arg5, $fnSuffix);
     }
     //in CiviCRM 4.5 and later the invoke function has 6 arguments
     return $hook->invoke($numParams, $arg1, $arg2, $arg3, $arg4, $arg5, null, $fnSuffix);
 }
Example #6
0
 /**
  * Sets up the fixture, for example, opens a network connection.
  *
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     parent::setUp();
     $this->useTransaction(TRUE);
     // taken from form code - couldn't find good method to use
     $params['entity_id'] = 1;
     $params['entity_table'] = CRM_Core_BAO_Domain::getTableName();
     $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
     $domContact = $this->callAPISuccess('contact', 'create', array('contact_type' => 'Organization', 'organization_name' => 'new org', 'api.phone.create' => array('location_type_id' => $defaultLocationType->id, 'phone_type_id' => 1, 'phone' => '456-456'), 'api.address.create' => array('location_type_id' => $defaultLocationType->id, 'street_address' => '45 Penny Lane'), 'api.email.create' => array('location_type_id' => $defaultLocationType->id, 'email' => '*****@*****.**')));
     $this->callAPISuccess('domain', 'create', array('id' => 1, 'contact_id' => $domContact['id']));
     $this->params = array('name' => 'A-team domain', 'description' => 'domain of chaos', 'domain_version' => '4.2', 'contact_id' => $domContact['id']);
 }
 /**
  * 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();
 }
Example #8
0
/**
 * Create a new domain
 *
 * @param array $params
 * @return array
 */
function civicrm_domain_create($params)
{
    require_once 'CRM/Core/BAO/Domain.php';
    if (!is_array($params)) {
        return civicrm_create_error('Params need to be of type array!');
    }
    if (empty($params)) {
        return civicrm_create_error('Params cannot be empty!');
    }
    $domain = CRM_Core_BAO_Domain::create($params);
    $domain_array = array();
    _civicrm_object_to_array($domain, $domain_array);
    return $domain_array;
}
Example #9
0
 /**
  * takes an associative array and creates a contact object
  *
  * the function extract all the params it needs to initialize the create a
  * contact object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array  $params         (reference ) an assoc array of name/value pairs
  * @param array  $ids            the array that holds all the db ids
  * @param array  $locationId     
  *
  * @return object   CRM_Core_BAO_Location object on success, null otherwise
  * @access public
  * @static
  */
 function add(&$params, &$ids, $locationId)
 {
     if (!CRM_Core_BAO_Location::dataExists($params, $locationId, $ids)) {
         return null;
     }
     $location =& new CRM_Core_BAO_Location();
     if (!isset($params['contact_id'])) {
         require_once 'CRM/Core/BAO/Domain.php';
         $location->entity_table = CRM_Core_BAO_Domain::getTableName();
         $location->entity_id = $params['domain_id'];
     } else {
         $location->entity_table = CRM_Contact_BAO_Contact::getTableName();
         $location->entity_id = $params['contact_id'];
     }
     $location->location_type_id = CRM_Utils_Array::value('location_type_id', $params['location'][$locationId]);
     $location->name = CRM_Utils_Array::value('name', $params['location'][$locationId]);
     $location->is_primary = CRM_Utils_Array::value('is_primary', $params['location'][$locationId], false);
     // check if there exists another location has is_primary set, and if so reset that
     // if no location has is_primary, make this one is_primart
     if ($location->is_primary) {
         // reset all other locations with the same entity table entity id
         $sql = "UPDATE " . CRM_Core_BAO_Location::getTableName() . "\n SET is_primary = 0 WHERE \n entity_table = '{$location->entity_table}' AND\n entity_id    = '{$location->entity_id}' ";
         CRM_Core_DAO::executeQuery($sql);
     } else {
         // make sure there is at once location with is_primary set
         $sql = "SELECT count( " . CRM_Core_BAO_Location::getTableName() . ".id )\n FROM " . CRM_Core_BAO_Location::getTableName() . " WHERE\n entity_table = '{$location->entity_table}' AND\n entity_id    = '{$location->entity_id}'    AND\n is_primary   = 1";
         $count = CRM_Core_DAO::singleValueQuery($sql);
         if ($count == 0) {
             $location->is_primary = true;
         }
     }
     $location->id = CRM_Utils_Array::value('id', $ids['location'][$locationId]);
     $location->save();
     $params['location'][$locationId]['id'] = $location->id;
     $address_object = CRM_Core_BAO_Address::add($params, $ids, $locationId);
     $location->address = $address_object;
     // set this to true if this has been made the primary IM.
     // the rule is the first entered value is the primary object
     $isPrimaryPhone = $isPrimaryEmail = $isPrimaryIM = true;
     $location->phone = array();
     $location->email = array();
     $location->im = array();
     for ($i = 1; $i <= CRM_CONTACT_FORM_LOCATION_BLOCKS; $i++) {
         $location->phone[$i] = CRM_Core_BAO_Phone::add($params, $ids, $locationId, $i, $isPrimaryPhone);
         $location->email[$i] = CRM_Core_BAO_Email::add($params, $ids, $locationId, $i, $isPrimaryEmail);
         $location->im[$i] = CRM_Core_BAO_IM::add($params, $ids, $locationId, $i, $isPrimaryIM);
     }
     return $location;
 }
 /**
  * Apply the various CRM_Utils_Token helpers.
  *
  * @param TokenRenderEvent $e
  */
 public function onRender(TokenRenderEvent $e)
 {
     $isHtml = $e->message['format'] == 'text/html';
     $useSmarty = !empty($e->context['smarty']);
     $e->string = \CRM_Utils_Token::replaceDomainTokens($e->string, \CRM_Core_BAO_Domain::getDomain(), $isHtml, $e->message['tokens'], $useSmarty);
     if (!empty($e->context['contact'])) {
         $e->string = \CRM_Utils_Token::replaceContactTokens($e->string, $e->context['contact'], $isHtml, $e->message['tokens'], FALSE, $useSmarty);
         // FIXME: This may depend on $contact being merged with hook values.
         $e->string = \CRM_Utils_Token::replaceHookTokens($e->string, $e->context['contact'], $e->context['hookTokenCategories'], $isHtml, $useSmarty);
         \CRM_Utils_Token::replaceGreetingTokens($e->string, NULL, $e->context['contact']['contact_id'], NULL, $useSmarty);
     }
     if ($useSmarty) {
         $smarty = \CRM_Core_Smarty::singleton();
         $e->string = $smarty->fetch("string:" . $e->string);
     }
 }
Example #11
0
 /**
  * Singleton function used to manage this object.
  *
  * @param bool $loadFromDB
  *   whether to load from the database.
  * @param bool $force
  *   whether to force a reconstruction.
  *
  * @return CRM_Core_Config
  */
 public static function &singleton($loadFromDB = TRUE, $force = FALSE)
 {
     if (self::$_singleton === NULL || $force) {
         $GLOBALS['civicrm_default_error_scope'] = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'handle'));
         $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'simpleHandler'));
         if (defined('E_DEPRECATED')) {
             error_reporting(error_reporting() & ~E_DEPRECATED);
         }
         self::$_singleton = new CRM_Core_Config();
         \Civi\Core\Container::boot($loadFromDB);
         if ($loadFromDB && self::$_singleton->dsn) {
             $domain = \CRM_Core_BAO_Domain::getDomain();
             \CRM_Core_BAO_ConfigSetting::applyLocale(\Civi::settings($domain->id), $domain->locales);
             unset($errorScope);
             CRM_Utils_Hook::config(self::$_singleton);
             self::$_singleton->authenticate();
             // Extreme backward compat: $config binds to active domain at moment of setup.
             self::$_singleton->getSettings();
             Civi::service('settings_manager')->useDefaults();
         }
     }
     return self::$_singleton;
 }
 static function register($extension)
 {
     if ($domain_id = CRM_Core_Config::domainID()) {
         // Gather information from domain settings
         $params = array('id' => $domain_id);
         CRM_Core_BAO_Domain::retrieve($params, $domain);
         unset($params['id']);
         $locParams = $params + array('entity_id' => $domain_id, 'entity_table' => 'civicrm_domain');
         $defaults = CRM_Core_BAO_Location::getValues($locParams);
         foreach (array('address', 'phone', 'email') as $info) {
             $domain[$info] = reset(CRM_Utils_Array::value($info, $defaults));
         }
         // Create registration parameters
         $registration = array('extension' => $extension, 'organization_name' => $domain['name'], 'description' => $domain['description']);
         foreach (array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'state_province_id', 'country_id') as $field) {
             $registration[$field] = CRM_Utils_Array::value($field, $domain['address']);
         }
         $registration['phone'] = $domain['phone']['phone'];
         $registration['email'] = $domain['email']['email'];
         return self::_rest_helper('http://my.cividesk.com/register.php', $registration, 'POST');
     }
     return false;
 }
Example #13
0
 /**
  * Function takes participant ids and statuses
  * update status from $fromStatusId to $toStatusId
  * and send mail + create activities.
  *
  * @param array $participantIds
  *   Participant ids.
  * @param int $toStatusId
  *   Update status id.
  * @param int $fromStatusId
  *   From status id.
  * @param bool $returnResult
  * @param bool $skipCascadeRule
  *
  * @return array|NULL
  */
 public static function transitionParticipants($participantIds, $toStatusId, $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE)
 {
     if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
         return NULL;
     }
     //thumb rule is if we triggering  primary participant need to triggered additional
     $allParticipantIds = $primaryANDAdditonalIds = array();
     foreach ($participantIds as $id) {
         $allParticipantIds[] = $id;
         if (self::isPrimaryParticipant($id)) {
             //filter additional as per status transition rules, CRM-5403
             if ($skipCascadeRule) {
                 $additionalIds = self::getAdditionalParticipantIds($id);
             } else {
                 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
             }
             if (!empty($additionalIds)) {
                 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
                 $primaryANDAdditonalIds[$id] = $additionalIds;
             }
         }
     }
     //get the unique participant ids,
     $allParticipantIds = array_unique($allParticipantIds);
     //pull required participants, contacts, events  data, if not in hand
     static $eventDetails = array();
     static $domainValues = array();
     static $contactDetails = array();
     $contactIds = $eventIds = $participantDetails = array();
     $statusTypes = CRM_Event_PseudoConstant::participantStatus();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
     //first thing is pull all necessory data from db.
     $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
     //get all participants data.
     $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id);
         if (!array_key_exists($dao->contact_id, $contactDetails)) {
             $contactIds[$dao->contact_id] = $dao->contact_id;
         }
         if (!array_key_exists($dao->event_id, $eventDetails)) {
             $eventIds[$dao->event_id] = $dao->event_id;
         }
     }
     //get the domain values.
     if (empty($domainValues)) {
         // making all tokens available to templates.
         $domain = CRM_Core_BAO_Domain::getDomain();
         $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens());
         foreach ($tokens['domain'] as $token) {
             $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
         }
     }
     //get all required contacts detail.
     if (!empty($contactIds)) {
         // get the contact details.
         list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
         foreach ($currentContactDetails as $contactId => $contactValues) {
             $contactDetails[$contactId] = $contactValues;
         }
     }
     //get all required events detail.
     if (!empty($eventIds)) {
         foreach ($eventIds as $eventId) {
             //retrieve event information
             $eventParams = array('id' => $eventId);
             CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
             //get default participant role.
             $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
             //get the location info
             $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
             $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
         }
     }
     //now we are ready w/ all required data.
     //take a decision as per statuses.
     $emailType = NULL;
     $toStatus = $statusTypes[$toStatusId];
     $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes);
     switch ($toStatus) {
         case 'Pending from waitlist':
         case 'Pending from approval':
             switch ($fromStatus) {
                 case 'On waitlist':
                 case 'Awaiting approval':
                     $emailType = 'Confirm';
                     break;
             }
             break;
         case 'Expired':
             //no matter from where u come send expired mail.
             $emailType = $toStatus;
             break;
         case 'Cancelled':
             //no matter from where u come send cancel mail.
             $emailType = $toStatus;
             break;
     }
     //as we process additional w/ primary, there might be case if user
     //select primary as well as additionals, so avoid double processing.
     $processedParticipantIds = array();
     $mailedParticipants = array();
     //send mails and update status.
     foreach ($participantDetails as $participantId => $participantValues) {
         $updateParticipantIds = array();
         if (in_array($participantId, $processedParticipantIds)) {
             continue;
         }
         //check is it primary and has additional.
         if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
             foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
                 if ($emailType) {
                     $mail = self::sendTransitionParticipantMail($additonalId, $participantDetails[$additonalId], $eventDetails[$participantDetails[$additonalId]['event_id']], $contactDetails[$participantDetails[$additonalId]['contact_id']], $domainValues, $emailType);
                     //get the mail participant ids
                     if ($mail) {
                         $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
                     }
                 }
                 $updateParticipantIds[] = $additonalId;
                 $processedParticipantIds[] = $additonalId;
             }
         }
         //now send email appropriate mail to primary.
         if ($emailType) {
             $mail = self::sendTransitionParticipantMail($participantId, $participantValues, $eventDetails[$participantValues['event_id']], $contactDetails[$participantValues['contact_id']], $domainValues, $emailType);
             //get the mail participant ids
             if ($mail) {
                 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
             }
         }
         //now update status of group/one at once.
         $updateParticipantIds[] = $participantId;
         //update the register date only when we,
         //move participant to pending class, CRM-6496
         $updateRegisterDate = FALSE;
         if (array_key_exists($toStatusId, $pendingStatuses)) {
             $updateRegisterDate = TRUE;
         }
         self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
         $processedParticipantIds[] = $participantId;
     }
     //return result for cron.
     if ($returnResult) {
         $results = array('mailedParticipants' => $mailedParticipants, 'updatedParticipantIds' => $processedParticipantIds);
         return $results;
     }
 }
 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");
 }
Example #15
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;
 }
Example #16
0
 /**
  * Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
  *
  * @return bool
  */
 public static function isUpgradeFromPreFourOneAlpha1()
 {
     if (CRM_Core_Config::isUpgradeMode()) {
         $currentVer = CRM_Core_BAO_Domain::version();
         if (version_compare($currentVer, '4.1.alpha1') < 0) {
             return TRUE;
         }
     }
     return FALSE;
 }
Example #17
0
 /**
  * Get a domain object given a queue event
  * 
  * @param int $queue_id     The ID of the queue event
  * @return object $domain   The domain owning the event
  * @access public
  * @static
  */
 function &getDomain($queue_id)
 {
     $dao =& new CRM_Core_Dao();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $dao->query("SELECT         {$mailing}.domain_id as domain_id\n                        FROM        {$mailing}\n                        INNER JOIN  {$job} \n                                ON  {$job}.mailing_id = {$mailing}.id\n                        INNER JOIN  {$queue}\n                                ON  {$queue}.job_id = {$job}.id\n                        WHERE       {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer'));
     $dao->fetch();
     if (empty($dao->domain_id)) {
         return null;
     }
     require_once 'CRM/Core/BAO/Domain.php';
     return CRM_Core_BAO_Domain::getDomainById($dao->domain_id);
 }
    /**
     * @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();
        }
    }
 /**
  * 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);
 }
Example #20
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);
     }
 }
Example #21
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));
 }
Example #22
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];
 }
Example #23
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);
     }
 }
Example #24
0
 /**
  * Cancel this participant and finish, send cancellation email. At this point no
  * auto-cancellation of payment is handled, so payment needs to be manually cancelled
  *
  * return @void
  */
 public function cancelParticipant($params)
 {
     //set participant record status to Cancelled, refund payment if possible
     // send email to participant and admin, and log Activity
     $value = array();
     $value['id'] = $this->_participant_id;
     $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
     $value['status_id'] = $cancelledId;
     CRM_Event_BAO_Participant::create($value);
     $domainValues = array();
     $domain = CRM_Core_BAO_Domain::getDomain();
     $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens());
     foreach ($tokens['domain'] as $token) {
         $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
     }
     $participantRoles = array();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $participantDetails = array();
     $query = "SELECT * FROM civicrm_participant WHERE id = {$this->_participant_id}";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id);
     }
     $eventDetails = array();
     $eventParams = array('id' => $this->_event_id);
     CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
     //get default participant role.
     $eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
     //get the location info
     $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
     $eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
     //get contact details
     $contactIds[$this->_contact_id] = $this->_contact_id;
     list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
     foreach ($currentContactDetails as $contactId => $contactValues) {
         $contactDetails[$this->_contact_id] = $contactValues;
     }
     //send a 'cancelled' email to user, and cc the event's cc_confirm email
     $mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_participant_id, $participantDetails[$this->_participant_id], $eventDetails[$this->_event_id], $contactDetails[$this->_contact_id], $domainValues, "Cancelled", "");
     $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
     $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true");
     CRM_Utils_System::redirect($url);
 }
Example #25
0
 /**
  * Validation.
  *
  * @param array $params
  *   (ref.) an assoc array of name/value pairs.
  *
  * @param $files
  * @param $self
  *
  * @return bool|array
  *   mixed true or array of errors
  */
 public static function formRule($params, $files, $self)
 {
     if (!empty($_POST['_qf_Import_refresh'])) {
         return TRUE;
     }
     $errors = array();
     $template = CRM_Core_Smarty::singleton();
     if (isset($params['html_message'])) {
         $htmlMessage = str_replace(array("\n", "\r"), ' ', $params['html_message']);
         $htmlMessage = str_replace("'", "\\'", $htmlMessage);
         $template->assign('htmlContent', $htmlMessage);
     }
     $domain = CRM_Core_BAO_Domain::getDomain();
     $mailing = new CRM_Mailing_BAO_Mailing();
     $mailing->id = $self->_mailingID;
     $mailing->find(TRUE);
     $session = CRM_Core_Session::singleton();
     $values = array('contact_id' => $session->get('userID'), 'version' => 3);
     require_once 'api/api.php';
     $contact = civicrm_api('contact', 'get', $values);
     //CRM-4524
     $contact = reset($contact['values']);
     $verp = array_flip(array('optOut', 'reply', 'unsubscribe', 'resubscribe', 'owner'));
     foreach ($verp as $key => $value) {
         $verp[$key]++;
     }
     $urls = array_flip(array('forward', 'optOutUrl', 'unsubscribeUrl', 'resubscribeUrl'));
     foreach ($urls as $key => $value) {
         $urls[$key]++;
     }
     // set $header and $footer
     foreach (array('header', 'footer') as $part) {
         ${$part} = array();
         if ($params["{$part}_id"]) {
             //echo "found<p>";
             $component = new CRM_Mailing_BAO_Component();
             $component->id = $params["{$part}_id"];
             $component->find(TRUE);
             ${$part}['textFile'] = $component->body_text;
             ${$part}['htmlFile'] = $component->body_html;
             $component->free();
         } else {
             ${$part}['htmlFile'] = ${$part}['textFile'] = '';
         }
     }
     $skipTextFile = $self->get('skipTextFile');
     $skipHtmlFile = $self->get('skipHtmlFile');
     if (!$params['upload_type']) {
         if ((!isset($files['textFile']) || !file_exists($files['textFile']['tmp_name'])) && (!isset($files['htmlFile']) || !file_exists($files['htmlFile']['tmp_name']))) {
             if (!($skipTextFile || $skipHtmlFile)) {
                 $errors['textFile'] = ts('Please provide either a Text or HTML formatted message - or both.');
             }
         }
     } else {
         if (empty($params['text_message']) && empty($params['html_message'])) {
             $errors['html_message'] = ts('Please provide either a Text or HTML formatted message - or both.');
         }
         if (!empty($params['saveTemplate']) && empty($params['saveTemplateName'])) {
             $errors['saveTemplateName'] = ts('Please provide a Template Name.');
         }
     }
     foreach (array('text', 'html') as $file) {
         if (!$params['upload_type'] && !file_exists(CRM_Utils_Array::value('tmp_name', $files[$file . 'File']))) {
             continue;
         }
         if ($params['upload_type'] && !$params[$file . '_message']) {
             continue;
         }
         if (!$params['upload_type']) {
             $str = file_get_contents($files[$file . 'File']['tmp_name']);
             $name = $files[$file . 'File']['name'];
         } else {
             $str = $params[$file . '_message'];
             $str = $file == 'html' ? str_replace('%7B', '{', str_replace('%7D', '}', $str)) : $str;
             $name = $file . ' message';
         }
         /* append header/footer */
         $str = $header[$file . 'File'] . $str . $footer[$file . 'File'];
         $dataErrors = array();
         /* First look for missing tokens */
         if (!CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'disable_mandatory_tokens_check')) {
             $err = CRM_Utils_Token::requiredTokens($str);
             if ($err !== TRUE) {
                 foreach ($err as $token => $desc) {
                     $dataErrors[] = '<li>' . ts('This message is missing a required token - {%1}: %2', array(1 => $token, 2 => $desc)) . '</li>';
                 }
             }
         }
         /* Do a full token replacement on a dummy verp, the current
          * contact and domain, and the first organization. */
         // here we make a dummy mailing object so that we
         // can retrieve the tokens that we need to replace
         // so that we do get an invalid token error
         // this is qute hacky and I hope that there might
         // be a suggestion from someone on how to
         // make it a bit more elegant
         $dummy_mail = new CRM_Mailing_BAO_Mailing();
         $mess = "body_{$file}";
         $dummy_mail->{$mess} = $str;
         $tokens = $dummy_mail->getTokens();
         $str = CRM_Utils_Token::replaceSubscribeInviteTokens($str);
         $str = CRM_Utils_Token::replaceDomainTokens($str, $domain, NULL, $tokens[$file]);
         $str = CRM_Utils_Token::replaceMailingTokens($str, $mailing, NULL, $tokens[$file]);
         $str = CRM_Utils_Token::replaceOrgTokens($str, $org);
         $str = CRM_Utils_Token::replaceActionTokens($str, $verp, $urls, NULL, $tokens[$file]);
         $str = CRM_Utils_Token::replaceContactTokens($str, $contact, NULL, $tokens[$file]);
         $unmatched = CRM_Utils_Token::unmatchedTokens($str);
         if (!empty($unmatched) && 0) {
             foreach ($unmatched as $token) {
                 $dataErrors[] = '<li>' . ts('Invalid token code') . ' {' . $token . '}</li>';
             }
         }
         if (!empty($dataErrors)) {
             $errors[$file . 'File'] = ts('The following errors were detected in %1:', array(1 => $name)) . ' <ul>' . implode('', $dataErrors) . '</ul><br /><a href="' . CRM_Utils_System::docURL2('Sample CiviMail Messages', TRUE, NULL, NULL, NULL, "wiki") . '" target="_blank">' . ts('More information on required tokens...') . '</a>';
         }
     }
     $templateName = CRM_Core_BAO_MessageTemplate::getMessageTemplates();
     if (!empty($params['saveTemplate']) && in_array(CRM_Utils_Array::value('saveTemplateName', $params), $templateName)) {
         $errors['saveTemplate'] = ts('Duplicate Template Name.');
     }
     return empty($errors) ? TRUE : $errors;
 }
Example #26
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;
     }
 }
Example #27
0
File: PCP.php Project: 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;
 }
Example #28
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);
 }
 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");
 }
Example #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();
     }
 }