static function relatedContactInfo($contactId)
 {
     $return = array();
     if (empty($contactId)) {
         return $return;
     }
     $phone = CRM_Core_BAO_Phone::allPhones($contactId, TRUE, NULL, array('is_primary' => 1));
     $contactSubType = CRM_Contact_BAO_Contact::getContactSubType($contactId);
     $contactType = CRM_Contact_BAO_ContactType::getLabel($contactSubType[0]);
     $gid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'PCP_Supporter_Profile', 'id', 'name');
     $updateURL = CRM_Utils_System::url('civicrm/profile/edit', "reset=1&gid={$gid}&cid={$contactId}");
     // $updateURL      =CRM_Utils_System::url('civicrm/pcp/support', "action=browse&component=event&id={$params['pcpId']}");
     $return = array('name' => CRM_Contact_BAO_Contact::displayName($contactId), 'type' => $contactType, 'email' => CRM_Contact_BAO_Contact::getPrimaryEmail($contactId), 'phone' => !empty($phone) && isset($phone[1]['phone']) ? $phone[1]['phone'] : NULL, 'action' => "<a href={$updateURL}>Update Contact Information</a>");
     return $return;
 }
Example #2
0
 /**
  * @param $token
  * @param $mailing
  * @param bool $escapeSmarty
  *
  * @return string
  */
 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE)
 {
     $value = '';
     switch ($token) {
         // CRM-7663
         case 'id':
             $value = $mailing ? $mailing->id : 'undefined';
             break;
         case 'name':
             $value = $mailing ? $mailing->name : 'Mailing Name';
             break;
         case 'group':
             $groups = $mailing ? $mailing->getGroupNames() : array('Mailing Groups');
             $value = implode(', ', $groups);
             break;
         case 'subject':
             $value = $mailing->subject;
             break;
         case 'viewUrl':
             $mailingKey = $mailing->id;
             if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
                 $mailingKey = $hash;
             }
             $value = CRM_Utils_System::url('civicrm/mailing/view', "reset=1&id={$mailingKey}", TRUE, NULL, FALSE, TRUE);
             break;
         case 'editUrl':
         case 'scheduleUrl':
             // Note: editUrl and scheduleUrl used to be different, but now there's
             // one screen which can adapt based on permissions (in workflow mode).
             $value = CRM_Utils_System::url('civicrm/mailing/send', "reset=1&mid={$mailing->id}&continue=true", TRUE, NULL, FALSE, TRUE);
             break;
         case 'html':
             $page = new CRM_Mailing_Page_View();
             $value = $page->run($mailing->id, NULL, FALSE, TRUE);
             break;
         case 'approvalStatus':
             $value = CRM_Core_PseudoConstant::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id);
             break;
         case 'approvalNote':
             $value = $mailing->approval_note;
             break;
         case 'approveUrl':
             $value = CRM_Utils_System::url('civicrm/mailing/approve', "reset=1&mid={$mailing->id}", TRUE, NULL, FALSE, TRUE);
             break;
         case 'creator':
             $value = CRM_Contact_BAO_Contact::displayName($mailing->created_id);
             break;
         case 'creatorEmail':
             $value = CRM_Contact_BAO_Contact::getPrimaryEmail($mailing->created_id);
             break;
         default:
             $value = "{mailing.{$token}}";
             break;
     }
     if ($escapeSmarty) {
         $value = self::tokenEscapeSmarty($value);
     }
     return $value;
 }
Example #3
0
 /**
  * Test case for getPrimaryEmail.
  */
 public function testGetPrimaryEmail()
 {
     //get the contact params
     $params = $this->contactParams();
     $params['email'][2] = $params['email'][1];
     $params['email'][2]['email'] = '*****@*****.**';
     unset($params['email'][1]['is_primary']);
     //create contact
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contactId = $contact->id;
     //get the primary email.
     $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
     //Now check the primary email
     $this->assertEquals($email, CRM_Utils_Array::value('email', $params['email'][2]), 'Check Primary Email');
     //cleanup DB by deleting the contact
     $this->contactDelete($contactId);
     $this->quickCleanup(array('civicrm_contact'));
 }
    /**
     * @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();
        }
    }
 public function updateConstructedNames()
 {
     require_once 'CRM/Utils/Address.php';
     require_once 'CRM/Core/BAO/Preferences.php';
     require_once 'CRM/Core/DAO.php';
     require_once 'CRM/Core/PseudoConstant.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     //handle individuals using settings in the system
     $query = "SELECT * FROM civicrm_contact WHERE contact_type = 'Individual';";
     $dao = CRM_Core_DAO::executeQuery($query);
     $prefixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
     $suffixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id');
     $tokens = array();
     CRM_Utils_Hook::tokens($tokens);
     $tokenFields = array();
     foreach ($tokens as $category => $catTokens) {
         foreach ($catTokens as $token) {
             $tokenFields[] = $token;
         }
     }
     //determine sort name construction
     $sortFormat = CRM_Core_BAO_Preferences::value('sort_name_format');
     $sortFormat = str_replace('contact.', '', $sortFormat);
     //determine display name construction
     $displayFormat = CRM_Core_BAO_Preferences::value('display_name_format');
     $displayFormat = str_replace('contact.', '', $displayFormat);
     while ($dao->fetch()) {
         $contactID = $dao->id;
         $params = array('first_name' => $dao->first_name, 'middle_name' => $dao->middle_name, 'last_name' => $dao->last_name, 'prefix_id' => $dao->prefix_id, 'suffix_id' => $dao->suffix_id);
         $params['individual_prefix'] = $prefixes[$dao->prefix_id];
         $params['individual_suffix'] = $suffixes[$dao->suffix_id];
         $sortName = CRM_Utils_Address::format($params, $sortFormat, FALSE, FALSE, TRUE, $tokenFields);
         $sortName = trim(CRM_Core_DAO::escapeString($sortName));
         $displayName = CRM_Utils_Address::format($params, $displayFormat, FALSE, FALSE, TRUE, $tokenFields);
         $displayName = trim(CRM_Core_DAO::escapeString($displayName));
         //check for email
         if (empty($sortName) || empty($displayName)) {
             $email = NULL;
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contactID);
             if (empty($email)) {
                 $email = $contactID;
             }
             if (empty($sortName)) {
                 $sortName = $email;
             }
             if (empty($displayName)) {
                 $displayName = $email;
             }
         }
         //update record
         $updateQuery = "UPDATE civicrm_contact SET display_name = '{$displayName}', sort_name = '{$sortName}' WHERE id = {$contactID};";
         CRM_Core_DAO::executeQuery($updateQuery);
     }
     //end indiv
     echo "\n Individuals recached... ";
     //set organizations
     $query = "UPDATE civicrm_contact\n\t\t          SET display_name = organization_name,\n\t\t\t\t      sort_name = organization_name\n\t\t\t      WHERE contact_type = 'Organization';";
     $dao = CRM_Core_DAO::executeQuery($query);
     echo "\n Organizations recached... ";
     //set households
     $query = "UPDATE civicrm_contact\n\t\t          SET display_name = household_name,\n\t\t\t\t      sort_name = household_name\n\t\t\t      WHERE contact_type = 'Household';";
     $dao = CRM_Core_DAO::executeQuery($query);
     echo "\n Households recached... ";
 }
 /**
  * Process the PDf and email with activity and attachment.
  * on click of Print Invoices
  *
  * @param array $contribIDs
  *   Contribution Id.
  * @param array $params
  *   Associated array of submitted values.
  * @param array $contactIds
  *   Contact Id.
  * @param CRM_Core_Form $form
  *   Form object.
  */
 public static function printPDF($contribIDs, &$params, $contactIds, &$form)
 {
     // get all the details needed to generate a invoice
     $messageInvoice = array();
     $invoiceTemplate = CRM_Core_Smarty::singleton();
     $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
     // gives the status id when contribution status is 'Refunded'
     $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
     // getting data from admin page
     $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     foreach ($invoiceElements['details'] as $contribID => $detail) {
         $input = $ids = $objects = array();
         if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
             continue;
         }
         $input['component'] = $detail['component'];
         $ids['contact'] = $detail['contact'];
         $ids['contribution'] = $contribID;
         $ids['contributionRecur'] = NULL;
         $ids['contributionPage'] = NULL;
         $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
         $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
         $ids['event'] = CRM_Utils_Array::value('event', $detail);
         if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
             CRM_Core_Error::fatal();
         }
         $contribution =& $objects['contribution'];
         $input['amount'] = $contribution->total_amount;
         $input['invoice_id'] = $contribution->invoice_id;
         $input['receive_date'] = $contribution->receive_date;
         $input['contribution_status_id'] = $contribution->contribution_status_id;
         $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
         $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
         $addressParams = array('contact_id' => $contribution->contact_id);
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
         // to get billing address if present
         $billingAddress = array();
         foreach ($addressDetails as $key => $address) {
             if (isset($address['is_billing']) && $address['is_billing'] == 1 && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
                 break;
             } elseif ($address['is_billing'] == 0 && $address['is_primary'] == 1 || isset($address['is_billing']) && $address['is_billing'] == 1 && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
             }
         }
         if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
             $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
         } else {
             $stateProvinceAbbreviation = '';
         }
         if ($contribution->contribution_status_id == $refundedStatusId) {
             $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
         }
         $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
         //to obtain due date for PDF invoice
         $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
         $invoiceDate = date("F j, Y");
         $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
         if ($input['component'] == 'contribute') {
             $eid = $contribID;
             $etable = 'contribution';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
         } else {
             $eid = $contribution->_relatedObjects['participant']->id;
             $etable = 'participant';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable);
         }
         //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
         $amountDue = $input['amount'] - $input['amount'];
         // retreiving the subtotal and sum of same tax_rate
         $dataArray = array();
         $subTotal = 0;
         foreach ($lineItem as $entity_id => $taxRate) {
             if (isset($dataArray[(string) $taxRate['tax_rate']])) {
                 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
             } else {
                 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
             }
             $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
         }
         // to email the invoice
         $mailDetails = array();
         $values = array();
         if ($contribution->_component == 'event') {
             $daoName = 'CRM_Event_DAO_Event';
             $pageId = $contribution->_relatedObjects['event']->id;
             $mailElements = array('title', 'confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
         } elseif ($contribution->_component == 'contribute') {
             $daoName = 'CRM_Contribute_DAO_ContributionPage';
             $pageId = $contribution->contribution_page_id;
             $mailElements = array('title', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
         }
         $source = $contribution->source;
         $config = CRM_Core_Config::singleton();
         if (!isset($params['forPage'])) {
             $config->doNotAttachPDFReceipt = 1;
         }
         // get organization address
         $domain = CRM_Core_BAO_Domain::getDomain();
         $locParams = array('contact_id' => $domain->id);
         $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
         if (isset($locationDefaults['address'][1]['state_province_id'])) {
             $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
         } else {
             $stateProvinceAbbreviationDomain = '';
         }
         if (isset($locationDefaults['address'][1]['country_id'])) {
             $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
         } else {
             $countryDomain = '';
         }
         // parameters to be assign for template
         $tplParams = array('title' => $title, 'component' => $input['component'], 'id' => $contribution->id, 'source' => $source, 'invoice_id' => $invoiceId, 'resourceBase' => $config->userFrameworkResourceURL, 'defaultCurrency' => $config->defaultCurrency, 'amount' => $contribution->total_amount, 'amountDue' => $amountDue, 'invoice_date' => $invoiceDate, 'dueDate' => $dueDate, 'notes' => CRM_Utils_Array::value('notes', $prefixValue), 'display_name' => $contribution->_relatedObjects['contact']->display_name, 'lineItem' => $lineItem, 'dataArray' => $dataArray, 'refundedStatusId' => $refundedStatusId, 'contribution_status_id' => $contribution->contribution_status_id, 'subTotal' => $subTotal, 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'stateProvinceAbbreviation' => $stateProvinceAbbreviation, 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'is_pay_later' => $contribution->is_pay_later, 'organization_name' => $contribution->_relatedObjects['contact']->organization_name, 'domain_organization' => $domain->name, 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_state' => $stateProvinceAbbreviationDomain, 'domain_country' => $countryDomain, 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])), 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])));
         if (isset($creditNoteId)) {
             $tplParams['creditnote_id'] = $creditNoteId;
         }
         $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_invoice_receipt', 'contactId' => $contribution->contact_id, 'tplParams' => $tplParams, 'PDFFilename' => 'Invoice.pdf');
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         //CRM-16319 - we dont store in userID in case the user is doing multiple
         //transactions etc
         if (empty($contactID)) {
             $contactID = $session->get('transaction.userID');
         }
         $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
         $emails = array();
         $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
         foreach ($contactEmails as $emailId => $item) {
             $email = $item['email'];
             if ($email) {
                 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
             }
         }
         $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
         // from email address
         if (isset($params['from_email_address'])) {
             $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
         }
         // condition to check for download PDF Invoice or email Invoice
         if ($invoiceElements['createPdf']) {
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if (isset($params['forPage'])) {
                 return $html;
             } else {
                 $mail = array('subject' => $subject, 'body' => $message, 'html' => $html);
                 if ($mail['html']) {
                     $messageInvoice[] = $mail['html'];
                 } else {
                     $messageInvoice[] = nl2br($mail['body']);
                 }
             }
         } elseif ($contribution->_component == 'contribute') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         } elseif ($contribution->_component == 'event') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         }
         CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
         if ($contribution->contribution_status_id == $refundedStatusId) {
             CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
         }
         $invoiceTemplate->clearTemplateVars();
     }
     if ($invoiceElements['createPdf']) {
         if (isset($params['forPage'])) {
             return $html;
         } else {
             CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array('margin_top' => 10, 'margin_left' => 65, 'metric' => 'px'));
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contactIds, $fileName, $params);
             CRM_Utils_System::civiExit();
         }
     } else {
         if ($invoiceElements['suppressedEmails']) {
             $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails']));
             $msgTitle = ts('Email Error');
             $msgType = 'error';
         } else {
             $status = ts('Your mail has been sent.');
             $msgTitle = ts('Sent');
             $msgType = 'success';
         }
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     }
 }
Example #7
0
 /**
  * Update the uf_name in the user object.
  *
  * @param int $contactId
  *   Id of the contact to update.
  */
 public static function updateUFName($contactId)
 {
     if (!$contactId) {
         return;
     }
     $config = CRM_Core_Config::singleton();
     $ufName = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
     if (!$ufName) {
         return;
     }
     $update = FALSE;
     // 1.do check for contact Id.
     $ufmatch = new CRM_Core_DAO_UFMatch();
     $ufmatch->contact_id = $contactId;
     $ufmatch->domain_id = CRM_Core_Config::domainID();
     if (!$ufmatch->find(TRUE)) {
         return;
     }
     if ($ufmatch->uf_name != $ufName) {
         $update = TRUE;
     }
     // CRM-6928
     // 2.do check for duplicate ufName.
     $ufDupeName = new CRM_Core_DAO_UFMatch();
     $ufDupeName->uf_name = $ufName;
     $ufDupeName->domain_id = CRM_Core_Config::domainID();
     if ($ufDupeName->find(TRUE) && $ufDupeName->contact_id != $contactId) {
         $update = FALSE;
     }
     if (!$update) {
         return;
     }
     // save the updated ufmatch object
     $ufmatch->uf_name = $ufName;
     $ufmatch->save();
     $config->userSystem->updateCMSName($ufmatch->uf_id, $ufName);
 }
Example #8
0
 /**
  * Function is used to format the individual contact values.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param CRM $contact
  *   Contact object.
  *
  * @return CRM_Contact_BAO_Contact
  */
 public static function format(&$params, &$contact)
 {
     if (!self::dataExists($params)) {
         return NULL;
     }
     // "null" value for example is passed by dedupe merge in order to empty.
     // Display name computation shouldn't consider such values.
     foreach (array('first_name', 'middle_name', 'last_name', 'nick_name', 'formal_title') as $displayField) {
         if (CRM_Utils_Array::value($displayField, $params) == "null") {
             $params[$displayField] = '';
         }
     }
     $sortName = $displayName = '';
     $firstName = CRM_Utils_Array::value('first_name', $params, '');
     $middleName = CRM_Utils_Array::value('middle_name', $params, '');
     $lastName = CRM_Utils_Array::value('last_name', $params, '');
     $nickName = CRM_Utils_Array::value('nick_name', $params, '');
     $prefix_id = CRM_Utils_Array::value('prefix_id', $params, '');
     $suffix_id = CRM_Utils_Array::value('suffix_id', $params, '');
     $formalTitle = CRM_Utils_Array::value('formal_title', $params, '');
     // get prefix and suffix names
     $prefix = $suffix = NULL;
     if ($prefix_id) {
         $params['individual_prefix'] = $prefix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'prefix_id', $prefix_id);
     }
     if ($suffix_id) {
         $params['individual_suffix'] = $suffix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'suffix_id', $suffix_id);
     }
     $params['is_deceased'] = CRM_Utils_Array::value('is_deceased', $params, FALSE);
     $individual = NULL;
     if ($contact->id) {
         $individual = new CRM_Contact_BAO_Contact();
         $individual->id = $contact->id;
         if ($individual->find(TRUE)) {
             //lets allow to update single name field though preserveDBName
             //but if db having null value and params contain value, CRM-4330.
             $useDBNames = array();
             foreach (array('last', 'middle', 'first', 'nick') as $name) {
                 $dbName = "{$name}_name";
                 $value = $individual->{$dbName};
                 // the db has name values
                 if ($value && !empty($params['preserveDBName'])) {
                     $useDBNames[] = $name;
                 }
             }
             foreach (array('prefix', 'suffix') as $name) {
                 $dbName = "{$name}_id";
                 $value = $individual->{$dbName};
                 if ($value && !empty($params['preserveDBName'])) {
                     $useDBNames[] = $name;
                 }
             }
             if ($individual->formal_title && !empty($params['preserveDBName'])) {
                 $useDBNames[] = 'formal_title';
             }
             // CRM-4430
             //1. preserve db name if want
             //2. lets get value from param if exists.
             //3. if not in params, lets get from db.
             foreach (array('last', 'middle', 'first', 'nick') as $name) {
                 $phpName = "{$name}Name";
                 $dbName = "{$name}_name";
                 $value = $individual->{$dbName};
                 if (in_array($name, $useDBNames)) {
                     $params[$dbName] = $value;
                     $contact->{$dbName} = $value;
                     ${$phpName} = $value;
                 } elseif (array_key_exists($dbName, $params)) {
                     ${$phpName} = $params[$dbName];
                 } elseif ($value) {
                     ${$phpName} = $value;
                 }
             }
             foreach (array('prefix', 'suffix') as $name) {
                 $dbName = "{$name}_id";
                 $value = $individual->{$dbName};
                 if (in_array($name, $useDBNames)) {
                     $params[$dbName] = $value;
                     $contact->{$dbName} = $value;
                     if ($value) {
                         ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value);
                     } else {
                         ${$name} = NULL;
                     }
                 } elseif (array_key_exists($dbName, $params)) {
                     // CRM-5278
                     if (!empty($params[$dbName])) {
                         ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $params[$dbName]);
                     }
                 } elseif ($value) {
                     ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value);
                 }
             }
             if (in_array('formal_title', $useDBNames)) {
                 $params['formal_title'] = $individual->formal_title;
                 $contact->formal_title = $individual->formal_title;
                 $formalTitle = $individual->formal_title;
             } elseif (array_key_exists('formal_title', $params)) {
                 $formalTitle = $params['formal_title'];
             } elseif ($individual->formal_title) {
                 $formalTitle = $individual->formal_title;
             }
         }
     }
     //first trim before further processing.
     foreach (array('lastName', 'firstName', 'middleName') as $fld) {
         ${$fld} = trim(${$fld});
     }
     if ($lastName || $firstName || $middleName) {
         // make sure we have values for all the name fields.
         $formatted = $params;
         $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'nick_name' => $nickName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id, 'formal_title' => $formalTitle);
         // make sure we have all the name fields.
         foreach ($nameParams as $name => $value) {
             if (empty($formatted[$name]) && $value) {
                 $formatted[$name] = $value;
             }
         }
         $tokens = array();
         CRM_Utils_Hook::tokens($tokens);
         $tokenFields = array();
         foreach ($tokens as $catTokens) {
             foreach ($catTokens as $token => $label) {
                 $tokenFields[] = $token;
             }
         }
         //build the sort name.
         $format = Civi::settings()->get('sort_name_format');
         $sortName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields);
         $sortName = trim($sortName);
         //build the display name.
         $format = Civi::settings()->get('display_name_format');
         $displayName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields);
         $displayName = trim($displayName);
     }
     //start further check for email.
     if (empty($sortName) || empty($displayName)) {
         $email = NULL;
         if (!empty($params['email']) && is_array($params['email'])) {
             foreach ($params['email'] as $emailBlock) {
                 if (isset($emailBlock['is_primary'])) {
                     $email = $emailBlock['email'];
                     break;
                 }
             }
         }
         $uniqId = CRM_Utils_Array::value('user_unique_id', $params);
         if (!$email && $contact->id) {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contact->id);
         }
     }
     //now set the names.
     $names = array('displayName' => 'display_name', 'sortName' => 'sort_name');
     foreach ($names as $value => $name) {
         if (empty(${$value})) {
             if ($email) {
                 ${$value} = $email;
             } elseif ($uniqId) {
                 ${$value} = $uniqId;
             } elseif (!empty($params[$name])) {
                 ${$value} = $params[$name];
             } elseif ($displayName) {
                 ${$value} = $displayName;
             }
         }
         //finally if we could not pass anything lets keep db.
         if (!empty(${$value})) {
             $contact->{$name} = ${$value};
         }
     }
     $format = CRM_Utils_Date::getDateFormat('birth');
     if ($date = CRM_Utils_Array::value('birth_date', $params)) {
         if (in_array($format, array('dd-mm', 'mm/dd'))) {
             $separator = '/';
             if ($format == 'dd-mm') {
                 $separator = '-';
             }
             $date = $date . $separator . '1902';
         } elseif (in_array($format, array('yy-mm'))) {
             $date = $date . '-01';
         } elseif (in_array($format, array('M yy'))) {
             $date = $date . '-01';
         } elseif (in_array($format, array('yy'))) {
             $date = $date . '-01-01';
         }
         $contact->birth_date = CRM_Utils_Date::processDate($date);
     } elseif ($contact->birth_date) {
         $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
     }
     if ($date = CRM_Utils_Array::value('deceased_date', $params)) {
         if (in_array($format, array('dd-mm', 'mm/dd'))) {
             $separator = '/';
             if ($format == 'dd-mm') {
                 $separator = '-';
             }
             $date = $date . $separator . '1902';
         } elseif (in_array($format, array('yy-mm'))) {
             $date = $date . '-01';
         } elseif (in_array($format, array('M yy'))) {
             $date = $date . '-01';
         } elseif (in_array($format, array('yy'))) {
             $date = $date . '-01-01';
         }
         $contact->deceased_date = CRM_Utils_Date::processDate($date);
     } elseif ($contact->deceased_date) {
         $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
     }
     if ($middle_name = CRM_Utils_Array::value('middle_name', $params)) {
         $contact->middle_name = $middle_name;
     }
     return $contact;
 }
 /**
  * @param \Civi\Token\TokenRow $tokenRow
  * @param CRM_Core_DAO_ActionSchedule $schedule
  * @param int $toContactID
  * @return array
  *   List of error messages.
  */
 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID)
 {
     $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($toContactID);
     if (!$toEmail) {
         return array("email_missing" => "Couldn't find recipient's email address.");
     }
     $body_text = $tokenRow->render('body_text');
     $body_html = $tokenRow->render('body_html');
     if (!$schedule->body_text) {
         $body_text = CRM_Utils_String::htmlToText($body_html);
     }
     // set up the parameters for CRM_Utils_Mail::send
     $mailParams = array('groupName' => 'Scheduled Reminder Sender', 'from' => self::pickFromEmail($schedule), 'toName' => $tokenRow->context['contact']['display_name'], 'toEmail' => $toEmail, 'subject' => $tokenRow->render('subject'), 'entity' => 'action_schedule', 'entity_id' => $schedule->id);
     if (!$body_html || $tokenRow->context['contact']['preferred_mail_format'] == 'Text' || $tokenRow->context['contact']['preferred_mail_format'] == 'Both') {
         // render the &amp; entities in text mode, so that the links work
         $mailParams['text'] = str_replace('&amp;', '&', $body_text);
     }
     if ($body_html && ($tokenRow->context['contact']['preferred_mail_format'] == 'HTML' || $tokenRow->context['contact']['preferred_mail_format'] == 'Both')) {
         $mailParams['html'] = $body_html;
     }
     $result = CRM_Utils_Mail::send($mailParams);
     if (!$result || is_a($result, 'PEAR_Error')) {
         return array('email_fail' => 'Failed to send message');
     }
     return array();
 }
function giftmemberships_civicrm_postProcess($formName, &$form)
{
    if ($formName == "CRM_Price_Form_Field" && ($form->_submitValues['gift-check'] == 1 || $form->_submitValues['redeem-check'] == 1)) {
        $priceSetId = $form->get('sid');
        $label = $form->_submitValues['label'];
        /* Get price fields belonging to price set */
        try {
            $result = civicrm_api3('PriceField', 'get', array('sequential' => 1, 'price_set_id' => $priceSetId));
            foreach ($result['values'] as $value) {
                if ($value['label'] == $label) {
                    /*** Update Name in Pricefield table ***/
                    $priceFieldId = $value['id'];
                    if ($form->_submitValues['gift-check'] == 1) {
                        $name = '_gift_membership';
                    } elseif ($form->_submitValues['redeem-check'] == 1) {
                        $name = '_redeem_membership';
                    }
                    $update = civicrm_api3('PriceField', 'create', array('sequential' => 1, 'price_set_id' => $priceSetId, 'id' => $priceFieldId, 'name' => $name));
                    /*** Save membership_type in gift_membership_price_fields table ***/
                    if ($update['is_error'] != 1 && $form->_submitValues['gift-check'] == 1) {
                        $memType = $form->_submitValues['membershipselect'];
                        $sql = "SELECT pfid FROM civicrm_gift_membership_price_fields WHERE pfid = {$priceFieldId};";
                        $dao = CRM_Core_DAO::executeQuery($sql);
                        if ($dao->fetch()) {
                            $giftPFID = $dao->pfid;
                        }
                        if ($giftPFID) {
                            $sql = "UPDATE civicrm_gift_membership_price_fields SET membership_type_id={$memType} WHERE pfid={$giftPFID};";
                        } else {
                            $sql = "INSERT INTO civicrm_gift_membership_price_fields (pfid, membership_type_id) VALUES ({$priceFieldId}, {$memType});";
                        }
                        $dao = CRM_Core_DAO::executeQuery($sql);
                    }
                }
            }
        } catch (CiviCRM_API3_Exeception $e) {
            $error = $e->getMessage();
        }
    }
    if ($formName == "CRM_Contribute_Form_Contribution_Confirm") {
        $submitValues = $form->_params;
        $contributionId = $form->_contributionID;
        $giverId = $form->_contactID;
        foreach ($submitValues as $key => $value) {
            if (strpos($key, '_gift-codes') !== false) {
                $giftcodes = true;
                $price = explode("_", $key);
                $pfid = $price[0];
                $sql = "SELECT membership_type_id FROM civicrm_gift_membership_price_fields WHERE pfid = {$pfid};";
                $dao = CRM_Core_DAO::executeQuery($sql);
                if ($dao->fetch()) {
                    $membershipType = $dao->membership_type_id;
                }
                if (strpos($value, '::')) {
                    $codes = explode('::', $value);
                    foreach ($codes as $code) {
                        $sql = "INSERT INTO civicrm_gift_membership_codes (membership_id, code, membership_type, contribution_id, giver_id) VALUES (NULL, '{$code}', '{$membershipType}', '{$contributionId}','{$giverId}' );";
                        $dao = CRM_Core_DAO::executeQuery($sql);
                    }
                } else {
                    if ($value != "") {
                        $sql = "INSERT INTO civicrm_gift_membership_codes (membership_id, code, membership_type, contribution_id, giver_id) VALUES (NULL, '{$value}', '{$membershipType}', '{$contributionId}', '{$giverId}');";
                        $dao = CRM_Core_DAO::executeQuery($sql);
                    }
                }
            }
            if (strpos($key, '_redeem-code') !== false) {
                //Create Membership using api
                $contact_id = $form->_contactID;
                $price = explode("_", $key);
                $pfid = $price[0];
                $priceName = "price_" . $pfid;
                $code = $submitValues[$priceName];
                $sql = "SELECT * FROM civicrm_gift_membership_codes WHERE code = '{$code}'";
                $dao = CRM_Core_DAO::executeQuery($sql);
                if ($dao->fetch()) {
                    $memType = $dao->membership_type;
                    $giver = $dao->giver_id;
                    $displayName = CRM_Contact_BAO_Contact::displayName($giver);
                    $source = "Gift Membership from " . $displayName;
                    $result = civicrm_api3('Membership', 'create', array('sequential' => 1, 'membership_type_id' => $memType, 'contact_id' => $contact_id, 'source' => $source));
                    if ($result['is_error'] != 1) {
                        $memId = $result['id'];
                        $sql = "UPDATE civicrm_gift_membership_codes SET membership_id='{$memId}' WHERE code='{$code}';";
                        $dao = CRM_Core_DAO::executeQuery($sql);
                    }
                }
            }
        }
        //end foreach
        /**** Send Email With Codes ****/
        if (isset($giftcodes) && $giftcodes == true) {
            /*** Make beginning of Code Table ***/
            $codeTable = "<h3>Gift Membership Codes</h3><table width='500px' style='border:1px solid #999;margin:1em 0em 1em;border-collapse:collapse'><thead><tr><th style='text-align:left;padding:4px;border-bottom:1px solid #999;background-color:#eee'>Membership</th><th style='text-align:left;padding:4px;border-bottom:1px solid #999;background-color:#eee'>Code</th></tr></thead><tbody>";
            $sql = "SELECT * FROM civicrm_gift_membership_codes WHERE contribution_id = '{$contributionId}'";
            $dao = CRM_Core_DAO::executeQuery($sql);
            /*** Add row for each code with corresponding membership purchased ***/
            while ($dao->fetch()) {
                $code = $dao->code;
                $memType = $dao->membership_type;
                $result = civicrm_api3('MembershipType', 'getsingle', array('sequential' => 1, 'id' => $memType));
                $memName = $result['name'] . " Membership";
                $codeTable .= "<tr><td>{$memName}</td><td>{$code}</td></tr>";
            }
            $codeTable .= "</tbody></table>";
            /*** get organization id of site ***/
            $sql = "SELECT contact_id FROM civicrm_domain WHERE id = 1";
            $dao = CRM_Core_DAO::executeQuery($sql);
            if ($dao->fetch()) {
                $orgEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contact_id);
            }
            /*** Prepare Params and Send Email ***/
            $email = CRM_Contact_BAO_Contact::getPrimaryEmail($giverId);
            $contactName = CRM_Contact_BAO_Contact::displayName($giverId);
            $mailParams = array();
            $mailParams['from'] = $orgEmail;
            $mailParams['toName'] = $contactName;
            $mailParams['subject'] = 'Gift Membership codes';
            $mailParams['toEmail'] = $email;
            $mailParams['html'] = $codeTable;
            $mailed = CRM_Utils_Mail::send($mailParams);
        }
    }
}
Example #11
0
 /**
  * update the uf_name in the user object
  *
  * @param int    $contactId id of the contact to update
  *
  * @return void
  * @access public
  * @static
  */
 static function updateUFName($contactId)
 {
     $config =& CRM_Core_Config::singleton();
     if ($config->userFramework == 'Standalone') {
         $ufName = CRM_Contact_BAO_Contact::getPrimaryOpenId($contactId);
     } else {
         $ufName = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
     }
     if (!$ufName) {
         return;
     }
     $ufmatch =& new CRM_Core_DAO_UFMatch();
     $ufmatch->contact_id = $contactId;
     $ufmatch->domain_id = CRM_Core_Config::domainID();
     if (!$ufmatch->find(true) || $ufmatch->uf_name == $ufName) {
         // if object does not exist or the OpenID has not changed
         return;
     }
     // save the updated ufmatch object
     $ufmatch->uf_name = $ufName;
     $ufmatch->save();
     require_once 'CRM/Core/BAO/CMSUser.php';
     CRM_Core_BAO_CMSUser::updateUFName($ufmatch->uf_id, $ufName);
 }
Example #12
0
 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = false)
 {
     $value = '';
     switch ($token) {
         case 'name':
             $value = $mailing ? $mailing->name : 'Mailing Name';
             break;
         case 'group':
             $groups = $mailing ? $mailing->getGroupNames() : array('Mailing Groups');
             $value = implode(', ', $groups);
             break;
         case 'subject':
             $value = $mailing->subject;
             break;
         case 'viewUrl':
             $value = CRM_Utils_System::url('civicrm/mailing/view', "reset=1&id={$mailing->id}", true, null, false, true);
             break;
         case 'editUrl':
             $value = CRM_Utils_System::url('civicrm/mailing/send', "reset=1&mid={$mailing->id}&continue=true", true, null, false, true);
             break;
         case 'scheduleUrl':
             $value = CRM_Utils_System::url('civicrm/mailing/schedule', "reset=1&mid={$mailing->id}", true, null, false, true);
             break;
         case 'html':
             require_once 'CRM/Mailing/Page/View.php';
             $page = new CRM_Mailing_Page_View();
             $value = $page->run($mailing->id, false);
             break;
         case 'approvalStatus':
             require_once 'CRM/Mailing/PseudoConstant.php';
             $mailApprovalStatus = CRM_Mailing_PseudoConstant::approvalStatus();
             $value = $mailApprovalStatus[$mailing->approval_status_id];
             break;
         case 'approvalNote':
             $value = $mailing->approval_note;
             break;
         case 'approveUrl':
             $value = CRM_Utils_System::url('civicrm/mailing/approve', "reset=1&mid={$mailing->id}", true, null, false, true);
             break;
         case 'creator':
             $value = CRM_Contact_BAO_Contact::displayName($mailing->created_id);
             break;
         case 'creatorEmail':
             $value = CRM_Contact_BAO_Contact::getPrimaryEmail($mailing->created_id);
             break;
         default:
             $value = "{mailing.{$token}}";
             break;
     }
     if ($escapeSmarty) {
         $value = self::tokenEscapeSmarty($value);
     }
     return $value;
 }
Example #13
0
 /**
  * test case for getPrimaryEmail( ) 
  * 
  */
 function testGetPrimaryEmail()
 {
     //get the contact params
     $params = $this->contactParams();
     $params['email'][2] = $params['email'][1];
     $params['email'][2]['email'] = '*****@*****.**';
     unset($params['email'][1]['is_primary']);
     //create contact
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contactId = $contact->id;
     //get the primary email.
     $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
     //Now check the primary email
     $this->assertEquals($email, CRM_Utils_Array::value('email', $params['email'][2]), 'Check Primary Email');
     //cleanup DB by deleting the contact
     Contact::delete($contactId);
 }
Example #14
0
 /**
  * Function is used to format the individual contact values
  *
  * @param array  $params (reference ) an assoc array of name/value pairs
  * @param array  $contact  contact object
  *
  * @return object CRM_Contact_BAO_Contact object
  * @access public
  * @static
  */
 static function format(&$params, &$contact)
 {
     if (!self::dataExists($params)) {
         return;
     }
     $sortName = $displayName = "";
     $firstName = CRM_Utils_Array::value('first_name', $params, '');
     $middleName = CRM_Utils_Array::value('middle_name', $params, '');
     $lastName = CRM_Utils_Array::value('last_name', $params, '');
     $prefix_id = CRM_Utils_Array::value('prefix_id', $params, '');
     $suffix_id = CRM_Utils_Array::value('suffix_id', $params, '');
     // get prefix and suffix names
     $prefixes = CRM_Core_PseudoConstant::individualPrefix();
     $suffixes = CRM_Core_PseudoConstant::individualSuffix();
     $prefix = $suffix = null;
     if ($prefix_id) {
         $prefix = $prefixes[$prefix_id];
         $params['individual_prefix'] = $prefix;
     }
     if ($suffix_id) {
         $suffix = $suffixes[$suffix_id];
         $params['individual_suffix'] = $suffix;
     }
     $params['is_deceased'] = CRM_Utils_Array::value('is_deceased', $params, false);
     $individual = null;
     if ($contact->id) {
         $individual = new CRM_Contact_BAO_Contact();
         $individual->id = $contact->id;
         if ($individual->find(true)) {
             //lets allow to update single name field though preserveDBName
             //but if db having null value and params contain value, CRM-4330.
             $useDBNames = array();
             foreach (array('last', 'middle', 'first') as $name) {
                 $dbName = "{$name}_name";
                 $value = $individual->{$dbName};
                 // the db has name values
                 if ($value && CRM_Utils_Array::value('preserveDBName', $params)) {
                     $useDBNames[] = $name;
                 }
             }
             foreach (array('prefix', 'suffix') as $name) {
                 $dbName = "{$name}_id";
                 $value = $individual->{$dbName};
                 if ($value && CRM_Utils_Array::value('preserveDBName', $params)) {
                     $useDBNames[] = $name;
                 }
             }
             // CRM-4430
             //1. preserve db name if want
             //2. lets get value from param if exists.
             //3. if not in params, lets get from db.
             foreach (array('last', 'middle', 'first') as $name) {
                 $phpName = "{$name}Name";
                 $dbName = "{$name}_name";
                 $value = $individual->{$dbName};
                 if (in_array($name, $useDBNames)) {
                     $params[$dbName] = $value;
                     $contact->{$dbName} = $value;
                     ${$phpName} = $value;
                 } else {
                     if (array_key_exists($dbName, $params)) {
                         ${$phpName} = $params[$dbName];
                     } else {
                         if ($value) {
                             ${$phpName} = $value;
                         }
                     }
                 }
             }
             foreach (array('prefix', 'suffix') as $name) {
                 $phpName = $name;
                 $dbName = "{$name}_id";
                 $vals = "{$name}es";
                 $value = $individual->{$dbName};
                 if (in_array($name, $useDBNames)) {
                     $params[$dbName] = $value;
                     $contact->{$dbName} = $value;
                     if ($value) {
                         $temp = ${$vals};
                         ${$phpName} = $temp[$value];
                     } else {
                         ${$phpName} = null;
                     }
                 } else {
                     if (array_key_exists($dbName, $params)) {
                         $temp = ${$vals};
                         // CRM-5278
                         if (!empty($params[$dbName])) {
                             ${$phpName} = CRM_Utils_Array::value($params[$dbName], $temp);
                         }
                     } else {
                         if ($value) {
                             $temp = ${$vals};
                             ${$phpName} = $temp[$value];
                         }
                     }
                 }
             }
         }
     }
     //first trim before further processing.
     foreach (array('lastName', 'firstName', 'middleName') as $fld) {
         ${$fld} = trim(${$fld});
     }
     if ($lastName || $firstName || $middleName) {
         // make sure we have values for all the name fields.
         $formatted = $params;
         $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id);
         // make sure we have all the name fields.
         foreach ($nameParams as $name => $value) {
             if (!CRM_Utils_Array::value($name, $formatted) && $value) {
                 $formatted[$name] = $value;
             }
         }
         // make sure we have values for all the name fields.
         $formatted = $params;
         $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id);
         // make sure we have all the name fields.
         foreach ($nameParams as $name => $value) {
             if (!CRM_Utils_Array::value($name, $formatted) && $value) {
                 $formatted[$name] = $value;
             }
         }
         $tokens = array();
         CRM_Utils_Hook::tokens($tokens);
         $tokenFields = array();
         foreach ($tokens as $category => $catTokens) {
             foreach ($catTokens as $token) {
                 $tokenFields[] = $token;
             }
         }
         require_once 'CRM/Utils/Address.php';
         require_once 'CRM/Core/BAO/Preferences.php';
         //build the sort name.
         $format = CRM_Core_BAO_Preferences::value('sort_name_format');
         $format = str_replace('contact.', '', $format);
         $sortName = CRM_Utils_Address::format($formatted, $format, false, false, true, $tokenFields);
         $sortName = trim($sortName);
         //build the display name.
         $format = CRM_Core_BAO_Preferences::value('display_name_format');
         $format = str_replace('contact.', '', $format);
         $displayName = CRM_Utils_Address::format($formatted, $format, false, false, true, $tokenFields);
         $displayName = trim($displayName);
     }
     //start further check for email.
     if (empty($sortName) || empty($displayName)) {
         $email = null;
         if (CRM_Utils_Array::value('email', $params) && is_array($params['email'])) {
             foreach ($params['email'] as $emailBlock) {
                 if (isset($emailBlock['is_primary'])) {
                     $email = $emailBlock['email'];
                     break;
                 }
             }
         }
         $uniqId = CRM_Utils_Array::value('user_unique_id', $params);
         if (!$email && $contact->id) {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contact->id);
         }
     }
     //now set the names.
     $names = array('sortName' => 'sort_name', 'displayName' => 'display_name');
     foreach ($names as $value => $name) {
         if (empty(${$value})) {
             if ($email) {
                 ${$value} = $email;
             } else {
                 if ($uniqId) {
                     ${$value} = $uniqId;
                 }
             }
         }
         //finally if we could not pass anything lets keep db.
         if (!empty(${$value})) {
             $contact->{$name} = ${$value};
         }
     }
     $format = CRM_Utils_Date::getDateFormat('birth');
     if ($date = CRM_Utils_Array::value('birth_date', $params)) {
         if (in_array($format, array('dd-mm', 'mm/dd'))) {
             $separator = '/';
             if ($format == 'dd-mm') {
                 $separator = '-';
             }
             $date = $date . $separator . '1902';
         } else {
             if (in_array($format, array('yy-mm'))) {
                 $date = $date . '-01';
             } else {
                 if (in_array($format, array('M yy'))) {
                     $date = '01 ' . $date;
                 } else {
                     if (in_array($format, array('yy'))) {
                         $date = $date . '-01-01';
                     }
                 }
             }
         }
         $contact->birth_date = CRM_Utils_Date::processDate($date);
     } else {
         if ($contact->birth_date) {
             $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
         }
     }
     if ($date = CRM_Utils_Array::value('deceased_date', $params)) {
         if (in_array($format, array('dd-mm', 'mm/dd'))) {
             $separator = '/';
             if ($format == 'dd-mm') {
                 $separator = '-';
             }
             $date = $date . $separator . '1902';
         } else {
             if (in_array($format, array('yy-mm'))) {
                 $date = $date . '-01';
             } else {
                 if (in_array($format, array('M yy'))) {
                     $date = '01 ' . $date;
                 } else {
                     if (in_array($format, array('yy'))) {
                         $date = $date . '-01-01';
                     }
                 }
             }
         }
         $contact->deceased_date = CRM_Utils_Date::processDate($date);
     } else {
         if ($contact->deceased_date) {
             $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
         }
     }
     if ($middle_name = CRM_Utils_Array::value('middle_name', $params)) {
         $contact->middle_name = $middle_name;
     }
     return $contact;
 }
 /**
  * The function checks and updates the status of all membership records for a given domain using the
  * calc_membership_status and update_contact_membership APIs.
  *
  * IMPORTANT:
  * It uses the default Domain FROM Name and FROM Email Address as the From email address for emails sent by this api.
  * Verify that this value has been properly set from Administer > Configure > Domain Information
  * If you want to use some other FROM email address, modify line 125 and set your valid email address.
  *
  * @return array $result
  * @access public
  */
 static function updateAllMembershipStatus()
 {
     require_once 'api/api.php';
     //get all active statuses of membership, CRM-3984
     $allStatus = CRM_Member_PseudoConstant::membershipStatus();
     $statusLabels = CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label');
     $allTypes = CRM_Member_PseudoConstant::membershipType();
     $contribStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $query = "\nSELECT     civicrm_membership.id                    as membership_id,\n           civicrm_membership.is_override           as is_override,\n           civicrm_membership.reminder_date         as reminder_date,\n           civicrm_membership.membership_type_id    as membership_type_id,\n           civicrm_membership.status_id             as status_id,\n           civicrm_membership.join_date             as join_date,\n           civicrm_membership.start_date            as start_date,\n           civicrm_membership.end_date              as end_date,\n           civicrm_membership.source                as source,\n           civicrm_contact.id                       as contact_id,\n           civicrm_contact.is_deceased              as is_deceased,\n           civicrm_membership.owner_membership_id   as owner_membership_id,\n           civicrm_membership.contribution_recur_id as recur_id\nFROM       civicrm_membership\nINNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )\nWHERE      civicrm_membership.is_test = 0";
     $params = array();
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     $today = date("Y-m-d");
     $processCount = 0;
     $updateCount = 0;
     $reminderCount = 0;
     $smarty = CRM_Core_Smarty::singleton();
     $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
     $domainFromEmail = "{$domainValues['0']} <{$domainValues['1']}>";
     //use domain email address as a default From email.
     $fromEmailAddress = $domainFromEmail;
     while ($dao->fetch()) {
         // echo ".";
         $processCount++;
         /**
                $count++;
                echo $dao->contact_id . ', '. CRM_Utils_System::memory( ) . "<p>\n";
         
                CRM_Core_Error::debug( 'fBegin', count( $GLOBALS['_DB_DATAOBJECT']['RESULTS'] ) );
                if ( $count > 2 ) {
                foreach ( $GLOBALS['_DB_DATAOBJECT']['RESULTS'] as $r ) {
                CRM_Core_Error::debug( 'r', $r->query );
                }
                // CRM_Core_Error::debug( 'f', $GLOBALS['_DB_DATAOBJECT']['RESULTS'] );
                exit( );
                }
                **/
         // Put common parameters into array for easy access
         $memberParams = array('id' => $dao->membership_id, 'status_id' => $dao->status_id, 'contact_id' => $dao->contact_id, 'membership_type_id' => $dao->membership_type_id, 'membership_type' => $allTypes[$dao->membership_type_id], 'join_date' => $dao->join_date, 'start_date' => $dao->start_date, 'end_date' => $dao->end_date, 'reminder_date' => $dao->reminder_date, 'source' => $dao->source, 'skipStatusCal' => TRUE, 'skipRecentView' => TRUE);
         $smarty->assign_by_ref('memberParams', $memberParams);
         //update membership record to Deceased if contact is deceased
         if ($dao->is_deceased) {
             // check for 'Deceased' membership status, CRM-5636
             $deceaseStatusId = array_search('Deceased', $allStatus);
             if (!$deceaseStatusId) {
                 CRM_Core_Error::fatal(ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.", array(1 => CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1'))));
             }
             //process only when status change.
             if ($dao->status_id != $deceaseStatusId) {
                 //take all params that need to save.
                 $deceasedMembership = $memberParams;
                 $deceasedMembership['status_id'] = $deceaseStatusId;
                 $deceasedMembership['createActivity'] = TRUE;
                 $deceasedMembership['version'] = 3;
                 //since there is change in status.
                 $statusChange = array('status_id' => $deceaseStatusId);
                 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
                 //process membership record.
                 civicrm_api('membership', 'create', $deceasedMembership);
             }
             continue;
         }
         //we fetch related, since we need to check for deceased
         //now further processing is handle w/ main membership record.
         if ($dao->owner_membership_id) {
             continue;
         }
         //update membership records where status is NOT - Pending OR Cancelled.
         //as well as membership is not override.
         //skipping Expired membership records -> reduced extra processing( kiran )
         if (!$dao->is_override && !in_array($dao->status_id, array(array_search('Pending', $allStatus), array_search('Cancelled', $allStatus), array_search('Expired', $allStatus)))) {
             // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
             //get the membership status as per id.
             $newStatus = civicrm_api('membership_status', 'calc', array('membership_id' => $dao->membership_id, 'version' => 3, 'ignore_admin_only' => FALSE), TRUE);
             $statusId = CRM_Utils_Array::value('id', $newStatus);
             //process only when status change.
             if ($statusId && $statusId != $dao->status_id) {
                 //take all params that need to save.
                 $memParams = $memberParams;
                 $memParams['status_id'] = $statusId;
                 $memParams['createActivity'] = TRUE;
                 $memParams['version'] = 3;
                 //since there is change in status.
                 $statusChange = array('status_id' => $statusId);
                 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
                 //process member record.
                 civicrm_api('membership', 'create', $memParams);
                 $updateCount++;
             }
         }
         //convert date from string format to timestamp format
         $reminder_date = CRM_Utils_DATE::unixTime($dao->reminder_date);
         $today_date = CRM_Utils_DATE::unixTime($today);
         //send reminder for membership renewal
         if ($dao->reminder_date && $dao->reminder_date != '0000-00-00' && $reminder_date <= $today_date) {
             $memType = new CRM_Member_BAO_MembershipType();
             $memType->id = $dao->membership_type_id;
             $memType->find(TRUE);
             $renewalMsgId = $memType->renewal_msg_id;
             if ($memType->autorenewal_msg_id && $dao->recur_id) {
                 $contribStatusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $dao->recur_id, 'contribution_status_id');
                 if ($contribStatusId != array_search('Cancelled', $contribStatus)) {
                     $renewalMsgId = $memType->autorenewal_msg_id;
                 }
             }
             if ($renewalMsgId) {
                 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contact_id);
                 if ($toEmail) {
                     $sendResult = CRM_Core_BAO_MessageTemplates::sendReminder($dao->contact_id, $toEmail, $renewalMsgId, $fromEmailAddress);
                     if (!$sendResult || is_a($sendResult, 'PEAR_Error')) {
                         // we could not send an email, for now we ignore
                         // CRM-3406
                         // at some point we might decide to do something
                     } else {
                         $reminderCount++;
                     }
                     //set membership reminder date to NULL since we've sent the reminder.
                     CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'reminder_date', 'null');
                     // insert the activity log record.
                     $config = CRM_Core_Config::singleton();
                     $activityParams = array();
                     $activityParams['subject'] = $allTypes[$dao->membership_type_id] . ": Status - " . $statusLabels[$newStatus['id']] . ", End Date - " . CRM_Utils_Date::customFormat(CRM_Utils_Date::isoToMysql($dao->end_date), $config->dateformatFull);
                     $activityParams['source_record_id'] = $dao->membership_id;
                     $session = CRM_Core_Session::singleton();
                     $activityParams['source_contact_id'] = $session->get('userID') ? $session->get('userID') : $dao->contact_id;
                     $activityParams['assignee_contact_id'] = $dao->contact_id;
                     $activityParams['activity_date_time'] = date('YmdHis');
                     static $actRelIds = array();
                     if (!isset($actRelIds['activity_type_id'])) {
                         $actRelIds['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
                     }
                     $activityParams['activity_type_id'] = $actRelIds['activity_type_id'];
                     if (!isset($actRelIds['activity_status_id'])) {
                         $actRelIds['activity_status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
                     }
                     $activityParams['status_id'] = $actRelIds['activity_status_id'];
                     static $msgTpl = array();
                     if (!isset($msgTpl[$memType->renewal_msg_id])) {
                         $msgTpl[$memType->renewal_msg_id] = array();
                         $messageTemplate = new CRM_Core_DAO_MessageTemplates();
                         $messageTemplate->id = $memType->renewal_msg_id;
                         if ($messageTemplate->find(TRUE)) {
                             $msgTpl[$memType->renewal_msg_id]['subject'] = $messageTemplate->msg_subject;
                             $msgTpl[$memType->renewal_msg_id]['details'] = $messageTemplate->msg_text;
                         }
                         $messageTemplate->free();
                     }
                     $activityParams['details'] = "Subject: {$msgTpl[$memType->renewal_msg_id]['subject']}\nMessage: {$msgTpl[$memType->renewal_msg_id]['details']}\n";
                     $activity = CRM_Activity_BAO_Activity::create($activityParams);
                 }
             }
             $memType->free();
         }
         // CRM_Core_Error::debug( 'fEnd', count( $GLOBALS['_DB_DATAOBJECT']['RESULTS'] ) );
     }
     $result['is_error'] = 0;
     $result['messages'] = ts('Processed %1 membership records. Updated %2 records. Sent %3 renewal reminders.', array(1 => $processCount, 2 => $updateCount, 3 => $reminderCount));
     return $result;
 }
Example #16
0
 /**
  * update the uf_name in the user object
  *
  * @param int    $contactId id of the contact to update
  *
  * @return void
  * @access public
  * @static
  */
 static function updateUFName($contactId)
 {
     if (!$contactId) {
         return;
     }
     $config = CRM_Core_Config::singleton();
     if ($config->userFramework == 'Standalone') {
         $ufName = CRM_Contact_BAO_Contact::getPrimaryOpenId($contactId);
     } else {
         $ufName = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
     }
     if (!$ufName) {
         return;
     }
     $update = false;
     // 1.do check for contact Id.
     $ufmatch = new CRM_Core_DAO_UFMatch();
     $ufmatch->contact_id = $contactId;
     $ufmatch->domain_id = CRM_Core_Config::domainID();
     if (!$ufmatch->find(true)) {
         return;
     }
     if ($ufmatch->uf_name != $ufName) {
         $update = true;
     }
     // CRM-6928
     // 2.do check for duplicate ufName.
     $ufDupeName = new CRM_Core_DAO_UFMatch();
     $ufDupeName->uf_name = $ufName;
     $ufDupeName->domain_id = CRM_Core_Config::domainID();
     if ($ufDupeName->find(true) && $ufDupeName->contact_id != $contactId) {
         $update = false;
     }
     if (!$update) {
         return;
     }
     // save the updated ufmatch object
     $ufmatch->uf_name = $ufName;
     $ufmatch->save();
     require_once 'CRM/Core/BAO/CMSUser.php';
     CRM_Core_BAO_CMSUser::updateUFName($ufmatch->uf_id, $ufName);
 }