예제 #1
0
 /**
  * Run the page.
  *
  * This method is called after the page is created.
  */
 public function run()
 {
     // get the emails for this contact
     $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST);
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'display_name'));
     $entityBlock = array('contact_id' => $contactId);
     $emails = CRM_Core_BAO_Email::getValues($entityBlock);
     if (!empty($emails)) {
         foreach ($emails as $key => &$value) {
             $value['location_type'] = $locationTypes[$value['location_type_id']];
         }
     }
     $contact = new CRM_Contact_BAO_Contact();
     $contact->id = $contactId;
     $contact->find(TRUE);
     $privacy = array();
     foreach (CRM_Contact_BAO_Contact::$_commPrefs as $name) {
         if (isset($contact->{$name})) {
             $privacy[$name] = $contact->{$name};
         }
     }
     $this->assign('contactId', $contactId);
     $this->assign('email', $emails);
     $this->assign('privacy', $privacy);
     // check logged in user permission
     CRM_Contact_Page_View::checkUserPermission($this, $contactId);
     // finally call parent
     parent::run();
 }
예제 #2
0
 static function preProcessSingle(&$form, $cid)
 {
     // TO DO: need to check where and why we use this function
     $form->_single = true;
     $form->_emails = array();
     if ($form->_context != 'standalone') {
         $form->_contactIds = array($cid);
         $emails = CRM_Core_BAO_Email::allEmails($cid);
         $form->_onHold = array();
         $toName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
         foreach ($emails as $emailId => $item) {
             $email = $item['email'];
             if (!$email && count($emails) <= 1) {
                 $form->_emails[$email] = '"' . $toName . '"';
                 $form->_noEmails = true;
             } else {
                 if ($email) {
                     if (isset($form->_emails[$email])) {
                         // CRM-3624
                         continue;
                     }
                     $form->_emails[$email] = '"' . $toName . '" <' . $email . '> ' . $item['locationType'];
                     $form->_onHold[$email] = $item['on_hold'];
                 }
             }
             if ($item['is_primary']) {
                 $form->_emails[$email] .= ' ' . ts('(preferred)');
             }
             $form->_emails[$email] = htmlspecialchars($form->_emails[$email]);
         }
     }
 }
예제 #3
0
 static function create($params)
 {
     if (is_numeric(CRM_Utils_Array::value('is_primary', $params)) || empty($params['id'])) {
         CRM_Core_BAO_Block::handlePrimary($params, get_class());
     }
     $email = CRM_Core_BAO_Email::add($params);
     return $email;
 }
예제 #4
0
 public function preProcess()
 {
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
     $this->_view = CRM_Utils_Request::retrieve('view', 'String', $this, FALSE);
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     $this->assign('component', $this->_component);
     $this->assign('id', $this->_id);
     $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
     if ($this->_view == 'transaction' && $this->_action & CRM_Core_Action::BROWSE) {
         $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, TRUE);
         $transactionRows = $paymentInfo['transaction'];
         $title = ts('View Payment');
         if ($this->_component == 'event') {
             $info = CRM_Event_BAO_Participant::participantDetails($this->_id);
             $title .= " - {$info['title']}";
         }
         CRM_Utils_System::setTitle($title);
         $this->assign('transaction', TRUE);
         $this->assign('rows', $transactionRows);
         return;
     }
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     $enitityType = NULL;
     if ($this->_component == 'event') {
         $enitityType = 'participant';
         $this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
     }
     $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
     $this->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($eventId);
     $paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_id, $enitityType);
     $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, FALSE, TRUE);
     $this->_amtPaid = $paymentDetails['paid'];
     $this->_amtTotal = $paymentDetails['total'];
     if (!empty($paymentInfo['refund_due'])) {
         $paymentAmt = $this->_refund = $paymentInfo['refund_due'];
         $this->_paymentType = 'refund';
     } elseif (!empty($paymentInfo['amount_owed'])) {
         $paymentAmt = $this->_owed = $paymentInfo['amount_owed'];
         $this->_paymentType = 'owed';
     } else {
         CRM_Core_Error::fatal(ts('No payment information found for this record'));
     }
     //set the payment mode - _mode property is defined in parent class
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     if (!empty($this->_mode) && $this->_paymentType == 'refund') {
         CRM_Core_Error::fatal(ts('Credit card payment is not for Refund payments use'));
     }
     list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
     $this->assignPaymentRelatedVariables();
     $this->assign('contributionMode', $this->_mode);
     $this->assign('contactId', $this->_contactId);
     $this->assign('paymentType', $this->_paymentType);
     $this->assign('paymentAmt', abs($paymentAmt));
     $this->setPageTitle($this->_refund ? ts('Refund') : ts('Payment'));
 }
예제 #5
0
 /**
  * Create email address - note that the create function calls 'add' but
  * has more business logic
  *
  * @param array $params
  *   Input parameters.
  *
  * @return object
  */
 public static function create($params)
 {
     // if id is set & is_primary isn't we can assume no change
     if (is_numeric(CRM_Utils_Array::value('is_primary', $params)) || empty($params['id'])) {
         CRM_Core_BAO_Block::handlePrimary($params, get_class());
     }
     $email = CRM_Core_BAO_Email::add($params);
     return $email;
 }
예제 #6
0
 /**
  * AllEmails() method - get all emails for our contact, with primary email first
  */
 public function testAllEmails()
 {
     $contactParams = array('first_name' => 'Alan', 'last_name' => 'Smith', 'email-1' => '*****@*****.**', 'email-2' => '*****@*****.**', 'email-3' => '*****@*****.**');
     $contactId = Contact::createIndividual($contactParams);
     $emails = CRM_Core_BAO_Email::allEmails($contactId);
     $this->assertEquals(count($emails), 3, 'Checking number of returned emails.');
     $firstEmailValue = array_slice($emails, 0, 1);
     $this->assertEquals('*****@*****.**', $firstEmailValue[0]['email'], 'Confirm primary email address value.');
     $this->assertEquals(1, $firstEmailValue[0]['is_primary'], 'Confirm first email address is primary.');
     Contact::delete($contactId);
 }
예제 #7
0
 /**
  * AllEmails() method - get all emails for our contact, with primary email first
  */
 public function testAllEmails()
 {
     $contactParams = array('first_name' => 'Alan', 'last_name' => 'Smith', 'email' => '*****@*****.**', 'api.email.create.0' => array('email' => '*****@*****.**', 'location_type_id' => 'Home'), 'api.email.create.1' => array('email' => '*****@*****.**', 'location_type_id' => 'Main'));
     $contactId = $this->individualCreate($contactParams);
     $emails = CRM_Core_BAO_Email::allEmails($contactId);
     $this->assertEquals(count($emails), 3, 'Checking number of returned emails.');
     $firstEmailValue = array_slice($emails, 0, 1);
     $this->assertEquals('*****@*****.**', $firstEmailValue[0]['email'], 'Confirm primary email address value.');
     $this->assertEquals(1, $firstEmailValue[0]['is_primary'], 'Confirm first email address is primary.');
     $this->contactDelete($contactId);
 }
예제 #8
0
 /**
  * @param $form
  */
 static function preProcessFromAddress(&$form)
 {
     $form->_single = FALSE;
     $className = CRM_Utils_System::getClassName($form);
     if (property_exists($form, '_context') && $form->_context != 'search' && $className == 'CRM_Contact_Form_Task_Email') {
         $form->_single = TRUE;
     }
     $form->_emails = $emails = array();
     $session = CRM_Core_Session::singleton();
     $contactID = $session->get('userID');
     $form->_contactIds = array($contactID);
     $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
     $form->_onHold = array();
     $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
     foreach ($contactEmails as $emailId => $item) {
         $email = $item['email'];
         if (!$email && count($emails) < 1) {
             // set it if no emails are present at all
             $form->_noEmails = TRUE;
         } else {
             if ($email) {
                 if (in_array($email, $emails)) {
                     // CRM-3624
                     continue;
                 }
                 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
                 $form->_onHold[$emailId] = $item['on_hold'];
                 $form->_noEmails = FALSE;
             }
         }
         $form->_emails[$emailId] = $emails[$emailId];
         $emails[$emailId] .= $item['locationType'];
         if ($item['is_primary']) {
             $emails[$emailId] .= ' ' . ts('(preferred)');
         }
         $emails[$emailId] = htmlspecialchars($emails[$emailId]);
     }
     $form->assign('noEmails', $form->_noEmails);
     if ($form->_noEmails) {
         CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address'));
     }
     // now add domain from addresses
     $domainEmails = array();
     $domainFrom = CRM_Core_OptionGroup::values('from_email_address');
     foreach (array_keys($domainFrom) as $k) {
         $domainEmail = $domainFrom[$k];
         $domainEmails[$domainEmail] = htmlspecialchars($domainEmail);
         $form->_emails[$domainEmail] = $domainEmail;
     }
     $form->_fromEmails = CRM_Utils_Array::crmArrayMerge($emails, $domainEmails);
 }
 public function preProcess()
 {
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     $enitityType = NULL;
     if ($this->_component == 'event') {
         $enitityType = 'participant';
         $this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
     }
     $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
     $this->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($eventId);
     $paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_id, $enitityType);
     $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component);
     $this->_amtPaid = $paymentDetails['paid'];
     $this->_amtTotal = $paymentDetails['total'];
     if (!empty($paymentInfo['refund_due'])) {
         $paymentAmt = $this->_refund = $paymentInfo['refund_due'];
         $this->_paymentType = 'refund';
     } elseif (!empty($paymentInfo['amount_owed'])) {
         $paymentAmt = $this->_owed = $paymentInfo['amount_owed'];
         $this->_paymentType = 'owed';
     } else {
         CRM_Core_Error::fatal(ts('No payment information found for this record'));
     }
     //set the payment mode - _mode property is defined in parent class
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     if (!empty($this->_mode) && $this->_paymentType == 'refund') {
         CRM_Core_Error::fatal(ts('Credit card payment is not for Refund payments use'));
     }
     list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
     if (!$this->_refund) {
         $this->assignProcessors();
         // also check for billing information
         // get the billing location type
         $this->assignBillingType();
     }
     $this->assign('contributionMode', $this->_mode);
     $this->assign('contactId', $this->_contactId);
     $this->assign('component', $this->_component);
     $this->assign('id', $this->_id);
     $this->assign('paymentType', $this->_paymentType);
     $this->assign('paymentAmt', abs($paymentAmt));
     $this->_paymentProcessor = array('billing_mode' => 1);
     $title = $this->_refund ? "Refund for {$this->_contributorDisplayName}" : "Payment from {$this->_contributorDisplayName}";
     if ($title) {
         CRM_Utils_System::setTitle(ts('%1', array(1 => $title)));
     }
 }
예제 #10
0
 /**
  * Build the form object elements for an email object.
  *
  * @param CRM_Core_Form $form
  *   Reference to the form object.
  * @param int $blockCount
  *   Block number to build.
  * @param bool $blockEdit
  *   Is it block edit.
  */
 public static function buildQuickForm(&$form, $blockCount = NULL, $blockEdit = FALSE)
 {
     // passing this via the session is AWFUL. we need to fix this
     if (!$blockCount) {
         $blockId = $form->get('Email_Block_Count') ? $form->get('Email_Block_Count') : 1;
     } else {
         $blockId = $blockCount;
     }
     $form->applyFilter('__ALL__', 'trim');
     //Email box
     $form->addField("email[{$blockId}][email]", array('entity' => 'email'));
     $form->addRule("email[{$blockId}][email]", ts('Email is not valid.'), 'email');
     if (isset($form->_contactType) || $blockEdit) {
         //Block type
         $form->addField("email[{$blockId}][location_type_id]", array('entity' => 'email', 'placeholder' => NULL, 'class' => 'eight'));
         //TODO: Refactor on_hold field to select.
         $multipleBulk = CRM_Core_BAO_Email::isMultipleBulkMail();
         //On-hold select
         if ($multipleBulk) {
             $holdOptions = array(0 => ts('- select -'), 1 => ts('On Hold Bounce'), 2 => ts('On Hold Opt Out'));
             $form->addElement('select', "email[{$blockId}][on_hold]", '', $holdOptions);
         } else {
             $form->addField("email[{$blockId}][on_hold]", array('entity' => 'email', 'type' => 'advcheckbox'));
         }
         //Bulkmail checkbox
         $form->assign('multipleBulk', $multipleBulk);
         if ($multipleBulk) {
             $js = array('id' => "Email_" . $blockId . "_IsBulkmail");
             $form->addElement('advcheckbox', "email[{$blockId}][is_bulkmail]", NULL, '', $js);
         } else {
             $js = array('id' => "Email_" . $blockId . "_IsBulkmail");
             if (!$blockEdit) {
                 $js['onClick'] = 'singleSelect( this.id );';
             }
             $form->addElement('radio', "email[{$blockId}][is_bulkmail]", '', '', '1', $js);
         }
         //is_Primary radio
         $js = array('id' => "Email_" . $blockId . "_IsPrimary");
         if (!$blockEdit) {
             $js['onClick'] = 'singleSelect( this.id );';
         }
         $form->addElement('radio', "email[{$blockId}][is_primary]", '', '', '1', $js);
         if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Contact') {
             $form->add('textarea', "email[{$blockId}][signature_text]", ts('Signature (Text)'), array('rows' => 2, 'cols' => 40));
             $form->add('wysiwyg', "email[{$blockId}][signature_html]", ts('Signature (HTML)'), array('rows' => 2, 'cols' => 40));
         }
     }
 }
예제 #11
0
 function testFindReferences()
 {
     $params = array('first_name' => 'Testy', 'last_name' => 'McScallion', 'contact_type' => 'Individual');
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertNotNull($contact->id);
     $params = array('email' => '*****@*****.**', 'contact_id' => $contact->id, 'is_primary' => 0, 'location_type_id' => 1);
     $email = CRM_Core_BAO_Email::add($params);
     $refs = $contact->findReferences();
     $refsByTable = array();
     foreach ($refs as $refObj) {
         $refsByTable[$refObj->__table] = $refObj;
     }
     $this->assertTrue(array_key_exists('civicrm_email', $refsByTable));
     $refDao = $refsByTable['civicrm_email'];
     $refDao->find(TRUE);
     $this->assertEquals($contact->id, $refDao->contact_id);
 }
예제 #12
0
파일: Form.php 프로젝트: kidaa30/yes
 public function preProcess()
 {
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'membership');
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     $this->assign('context', $this->_context);
     $this->assign('membershipMode', $this->_mode);
     $this->assign('contactID', $this->_contactID);
     if ($this->_mode) {
         $this->assignPaymentRelatedVariables();
     }
     if ($this->_id) {
         $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
         $this->_membershipIDs[] = $this->_id;
     }
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
 }
예제 #13
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 int    $locationId
  * @param int    $emailId
  * @param bool   $isPrimary      Has any previous entry been marked as isPrimary?
  *
  * @return object    CRM_Core_BAO_Email object if successful 
  *                   else null will be returned
  * @access public
  * @static
  */
 function add(&$params, &$ids, $locationId, $emailId, &$isPrimary)
 {
     // if no data and we are not updating an exisiting record
     if (!CRM_Core_BAO_Email::dataExists($params, $locationId, $emailId, $ids)) {
         return null;
     }
     $email =& new CRM_Core_DAO_Email();
     $email->id = CRM_Utils_Array::value($emailId, $ids['location'][$locationId]['email']);
     $email->email = $params['location'][$locationId]['email'][$emailId]['email'];
     if (empty($email->email)) {
         $email->delete();
         return null;
     }
     $email->location_id = $params['location'][$locationId]['id'];
     // set this object to be the value of isPrimary and make sure no one else can be isPrimary
     $email->is_primary = $isPrimary;
     $isPrimary = false;
     return $email->save();
 }
예제 #14
0
 /**
  * Register a subscription event.  Create a new contact if one does not
  * already exist.
  *
  * @param int $domain_id        The domain id of the new subscription
  * @param int $group_id         The group id to subscribe to
  * @param string $email         The email address of the (new) contact
  * @return int|null $se_id      The id of the subscription event, null on failure
  * @access public
  * @static
  */
 function &subscribe($domain_id, $group_id, $email)
 {
     /* First, find out if the contact already exists */
     $params = array('email' => $email, 'domain_id' => $domain_id);
     require_once 'CRM/Core/BAO/UFGroup.php';
     $contact_id = CRM_Core_BAO_UFGroup::findContact($params);
     CRM_Core_DAO::transaction('BEGIN');
     if (is_a($contact_id, CRM_Core_Error)) {
         require_once 'CRM/Core/BAO/LocationType.php';
         /* If the contact does not exist, create one. */
         $formatted = array('contact_type' => 'Individual');
         $value = array('email' => $email, 'location_type' => CRM_Core_BAO_LocationType::getDefaultID());
         _crm_add_formatted_param($value, $formatted);
         $contact =& crm_create_contact_formatted($formatted, CRM_IMPORT_PARSER_DUPLICATE_SKIP);
         if (is_a($contact, CRM_Core_Error)) {
             return null;
         }
         $contact_id = $contact->id;
     }
     require_once 'CRM/Core/BAO/Email.php';
     require_once 'CRM/Core/BAO/Location.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     /* Get the primary email id from the contact to use as a hash input */
     $dao =& new CRM_Core_DAO();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $locTable = CRM_Core_BAO_Location::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $dao->query("SELECT {$emailTable}.id as email_id\n                    FROM {$emailTable}\n                    INNER JOIN {$locTable}\n                        ON  {$emailTable}.location_id = {$locTable}.id\n                    WHERE   {$emailTable}.is_primary = 1\n                    AND     {$locTable}.is_primary = 1\n                    AND     {$locTable}.entity_table = '{$contactTable}'\n                    AND     {$locTable}.entity_id = " . CRM_Utils_Type::escape($contact_id, 'Integer'));
     $dao->fetch();
     $se =& new CRM_Mailing_Event_BAO_Subscribe();
     $se->group_id = $group_id;
     $se->contact_id = $contact_id;
     $se->time_stamp = date('YmdHis');
     $se->hash = sha1("{$group_id}:{$contact_id}:{$dao->email_id}");
     $se->save();
     $contacts = array($contact_id);
     require_once 'CRM/Contact/BAO/GroupContact.php';
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id);
     CRM_Core_DAO::transaction('COMMIT');
     return $se;
 }
예제 #15
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];
 }
예제 #16
0
 /**
  * @param array $deliveredParams
  * @param array $targetParams
  * @param $mailing
  * @param $job_date
  *
  * @return bool
  * @throws CRM_Core_Exception
  * @throws Exception
  */
 public function writeToDB(&$deliveredParams, &$targetParams, &$mailing, $job_date)
 {
     static $activityTypeID = NULL;
     static $writeActivity = NULL;
     if (!empty($deliveredParams)) {
         CRM_Mailing_Event_BAO_Delivered::bulkCreate($deliveredParams);
         $deliveredParams = array();
     }
     if ($writeActivity === NULL) {
         $writeActivity = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'write_activity_record', NULL, TRUE);
     }
     if (!$writeActivity) {
         return TRUE;
     }
     $result = TRUE;
     if (!empty($targetParams) && !empty($mailing->scheduled_id)) {
         if (!$activityTypeID) {
             if ($mailing->sms_provider_id) {
                 $mailing->subject = $mailing->name;
                 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Mass SMS', 'name');
             } else {
                 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name');
             }
             if (!$activityTypeID) {
                 CRM_Core_Error::fatal();
             }
         }
         $activity = array('source_contact_id' => $mailing->scheduled_id, 'target_contact_id' => array_unique($targetParams), 'activity_type_id' => $activityTypeID, 'source_record_id' => $this->mailing_id, 'activity_date_time' => $job_date, 'subject' => $mailing->subject, 'status_id' => 2, 'deleteActivityTarget' => FALSE, 'campaign_id' => $mailing->campaign_id);
         //check whether activity is already created for this mailing.
         //if yes then create only target contact record.
         $query = "\nSELECT id\nFROM   civicrm_activity\nWHERE  civicrm_activity.activity_type_id = %1\nAND    civicrm_activity.source_record_id = %2\n";
         $queryParams = array(1 => array($activityTypeID, 'Integer'), 2 => array($this->mailing_id, 'Integer'));
         $activityID = CRM_Core_DAO::singleValueQuery($query, $queryParams);
         if ($activityID) {
             $activity['id'] = $activityID;
             // CRM-9519
             if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
                 static $targetRecordID = NULL;
                 if (!$targetRecordID) {
                     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
                     $targetRecordID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
                 }
                 // make sure we don't attempt to duplicate the target activity
                 foreach ($activity['target_contact_id'] as $key => $targetID) {
                     $sql = "\nSELECT id\nFROM   civicrm_activity_contact\nWHERE  activity_id = {$activityID}\nAND    contact_id = {$targetID}\nAND    record_type_id = {$targetRecordID}\n";
                     if (CRM_Core_DAO::singleValueQuery($sql)) {
                         unset($activity['target_contact_id'][$key]);
                     }
                 }
             }
         }
         if (is_a(CRM_Activity_BAO_Activity::create($activity), 'CRM_Core_Error')) {
             $result = FALSE;
         }
         $targetParams = array();
     }
     return $result;
 }
예제 #17
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  *
  * @return array                Result set
  * @access public
  * @static
  */
 public static function &getRows($mailing_id, $job_id = NULL, $is_distinct = FALSE, $offset = NULL, $rowCount = NULL, $sort = NULL)
 {
     $dao = new CRM_Core_Dao();
     $bounce = self::getTableName();
     $bounceType = CRM_Mailing_DAO_BounceType::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$bounce}.time_stamp as date,\n                        {$bounce}.bounce_reason as reason,\n                        {$bounceType}.name as bounce_type\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$bounce}\n                    ON  {$bounce}.event_queue_id = {$queue}.id\n            LEFT JOIN   {$bounceType}\n                    ON  {$bounce}.bounce_type_id = {$bounceType}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n                    AND {$job}.is_test = 0\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $orderBy = "sort_name ASC, {$bounce}.time_stamp DESC";
     if ($sort) {
         if (is_string($sort)) {
             $sort = CRM_Utils_Type::escape($sort, 'String');
             $orderBy = $sort;
         } else {
             $orderBy = trim($sort->orderBy());
         }
     }
     $query .= " ORDER BY {$orderBy} ";
     if ($offset || $rowCount) {
         //Added "||$rowCount" to avoid displaying all records on first page
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'type' => empty($dao->bounce_type) ? ts('Unknown') : $dao->bounce_type, 'reason' => $dao->reason, 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
예제 #18
0
 public function preProcess()
 {
     //custom data related code
     $this->_cdType = CRM_Utils_Array::value('type', $_GET);
     $this->assign('cdType', FALSE);
     if ($this->_cdType) {
         $this->assign('cdType', TRUE);
         return CRM_Custom_Form_CustomData::preProcess($this);
     }
     // get price set id.
     $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
     $this->set('priceSetId', $this->_priceSetId);
     $this->assign('priceSetId', $this->_priceSetId);
     // action
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     $this->_processors = array();
     CRM_Core_Resources::singleton()->addSetting(array('ids' => array('contact' => $this->_contactID)));
     // check for edit permission
     if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
     }
     if ($this->_action & CRM_Core_Action::DELETE) {
         $contributionID = CRM_Member_BAO_Membership::getMembershipContributionId($this->_id);
         // check delete permission for contribution
         if ($this->_id && $contributionID && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
             CRM_Core_Error::fatal(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
         }
     }
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('context', $this->_context);
     if ($this->_id) {
         $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
         $this->_membershipIDs[] = $this->_id;
     }
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     $this->assign('membershipMode', $this->_mode);
     if ($this->_mode) {
         $this->_paymentProcessor = array('billing_mode' => 1);
         $validProcessors = array();
         $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'billing_mode IN ( 1, 3 )');
         foreach ($processors as $ppID => $label) {
             $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
             if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
                 continue;
             } elseif ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
                 continue;
             } else {
                 $paymentObject = CRM_Core_Payment::singleton($this->_mode, $paymentProcessor, $this);
                 $error = $paymentObject->checkConfig();
                 if (empty($error)) {
                     $validProcessors[$ppID] = $label;
                 }
                 $paymentObject = NULL;
             }
         }
         if (empty($validProcessors)) {
             CRM_Core_Error::fatal(ts('Could not find valid payment processor for this page'));
         } else {
             $this->_processors = $validProcessors;
         }
         // also check for billing information
         // get the billing location type
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
         // CRM-8108 remove ts around Billing location type
         //$this->_bltID = array_search( ts('Billing'),  $locationTypes );
         $this->_bltID = array_search('Billing', $locationTypes);
         if (!$this->_bltID) {
             CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
         }
         $this->set('bltID', $this->_bltID);
         $this->assign('bltID', $this->_bltID);
         $this->_fields = array();
         CRM_Core_Payment_Form::setCreditCardFields($this);
         // this required to show billing block
         $this->assign_by_ref('paymentProcessor', $paymentProcessor);
         $this->assign('hidePayPalExpress', TRUE);
     }
     if ($this->_action & CRM_Core_Action::ADD) {
         if (!CRM_Member_BAO_Membership::statusAvailabilty($this->_contactID)) {
             // all possible statuses are disabled - redirect back to contact form
             CRM_Core_Error::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
         }
         if ($this->_contactID) {
             //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
             $contactMemberships = array();
             $memParams = array('contact_id' => $this->_contactID);
             CRM_Member_BAO_Membership::getValues($memParams, $contactMemberships, TRUE);
             $cMemTypes = array();
             foreach ($contactMemberships as $mem) {
                 $cMemTypes[] = $mem['membership_type_id'];
             }
             if (count($cMemTypes) > 0) {
                 $memberorgs = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($cMemTypes);
                 $mems_by_org = array();
                 foreach ($contactMemberships as $memid => $mem) {
                     $mem['member_of_contact_id'] = CRM_Utils_Array::value($mem['membership_type_id'], $memberorgs);
                     if (CRM_Utils_Array::value('membership_end_date', $mem)) {
                         $mem['membership_end_date'] = CRM_Utils_Date::customformat($mem['membership_end_date']);
                     }
                     $mem['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $mem['membership_type_id'], 'name', 'id');
                     $mem['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $mem['status_id'], 'label', 'id');
                     if ($this->_mode) {
                         $mem['renewUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member&mode=live");
                     } else {
                         $mem['renewUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member");
                     }
                     $mem['membershipTab'] = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$this->_contactID}&selectedChild=member");
                     $mems_by_org[$mem['member_of_contact_id']] = $mem;
                 }
                 $resources = CRM_Core_Resources::singleton();
                 $resources->addSetting(array('existingMems' => array('memberorgs' => $mems_by_org)));
                 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/Membership.js');
             }
         } else {
             $resources = CRM_Core_Resources::singleton();
             $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
             $statuses = array();
             $membershipStatus = new CRM_Member_DAO_MembershipStatus();
             $membershipStatus->is_current_member = 1;
             $membershipStatus->find();
             $membershipStatus->selectAdd();
             $membershipStatus->selectAdd('id');
             while ($membershipStatus->fetch()) {
                 $statuses[$membershipStatus->id] = $membershipStatus->label;
             }
             $membershipStatus->free();
             $passthru = array('typeorgs' => CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(), 'memtypes' => CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE), 'statuses' => $statuses);
             $resources->addSetting(array('existingMems' => $passthru));
         }
     }
     // when custom data is included in this page
     if (CRM_Utils_Array::value('hidden_custom', $_POST)) {
         CRM_Custom_Form_CustomData::preProcess($this);
         CRM_Custom_Form_CustomData::buildQuickForm($this);
         CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     // CRM-4395, get the online pending contribution id.
     $this->_onlinePendingContributionId = NULL;
     if (!$this->_mode && $this->_id && $this->_action & CRM_Core_Action::UPDATE) {
         $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id, 'Membership');
     }
     $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId);
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
     // Set title
     if ($this->_contactID) {
         $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactID);
         // Check if this is default domain contact CRM-10482
         if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactID)) {
             $displayName .= ' (' . ts('default organization') . ')';
         }
         // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
         CRM_Utils_System::setTitle(ts('Membership for') . ' ' . $displayName);
     }
     parent::preProcess();
 }
예제 #19
0
 /**
  * Returns array of contacts who are members of the specified group.
  *
  * @param CRM_Contact $group                A valid group object (passed by reference)
  * @param array       $returnProperties     Which properties
  *                    should be included in the returned Contact object(s). If NULL,
  *                    the default set of contact properties will be
  *                    included. group_contact properties (such as 'status',
  * '                  in_date', etc.) are included automatically.Note:Do not inclue
  *                    Id releted properties.  
  * @param text        $status               A valid status value ('Added', 'Pending', 'Removed').
  * @param text        $sort                 Associative array of
  *                    one or more "property_name"=>"sort direction"
  *                    pairs which will control order of Contact objects returned.
  * @param Int         $offset               Starting row index.
  * @param Int         $row_count            Maximum number of rows to returns.
  *
  *
  * @return            $contactArray         Array of contacts who are members of the specified group
  *
  * @access public
  */
 static function getGroupContacts(&$group, $returnProperties = null, $status = 'Added', $sort = null, $offset = null, $row_count = null, $includeChildGroups = false)
 {
     $groupDAO =& new CRM_Contact_DAO_Group();
     $groupDAO->id = $group->id;
     if (!$groupDAO->find(true)) {
         return CRM_Core_Error::createError("Could not locate group with id: {$id}");
     }
     // make sure user has got permission to view this group
     require_once 'CRM/Contact/BAO/Group.php';
     if (!CRM_Contact_BAO_Group::checkPermission($groupDAO->id, $groupDAO->title)) {
         return CRM_Core_Error::createError("You do not have permission to access group with id: {$id}");
     }
     $query = '';
     if (empty($returnProperties)) {
         $query = "SELECT contact_a.id as contact_id,\n                      civicrm_email.email as email";
     } else {
         $query = "SELECT contact_a.id as contact_id , {$grpStatus} as status,";
         $query .= implode(',', $returnProperties);
     }
     $params = array();
     if ($includeChildGroups) {
         require_once 'CRM/Contact/BAO/GroupNesting.php';
         $groupIds = CRM_Contact_BAO_GroupNesting::getDescendentGroupIds(array($group->id));
     } else {
         $groupIds = array($group->id);
     }
     foreach ($groupIds as $groupId) {
         $params[] = array('group', 'IN', array($group->id => true), 0, 0);
     }
     require_once 'CRM/Core/BAO/Email.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     $tables = array(CRM_Core_BAO_Email::getTableName() => true, CRM_Contact_BAO_Contact::getTableName() => true);
     $inner = array();
     $whereTables = array();
     $where = CRM_Contact_BAO_Query::getWhereClause($params, null, $tables, $whereTables);
     $permission = CRM_Core_Permission::whereClause(CRM_Core_Permission::VIEW, $tables, $whereTables);
     $from = CRM_Contact_BAO_Query::fromClause($tables, $inner);
     $query .= " {$from} WHERE {$permission} AND {$where} ";
     if ($sort != null) {
         $order = array();
         foreach ($sort as $key => $direction) {
             $order[] = " {$key} {$direction} ";
         }
         $query .= " ORDER BY " . implode(',', $order);
     }
     if (!is_null($offset) && !is_null($row_count)) {
         $query .= " LIMIT {$offset}, {$row_count}";
     }
     $dao =& new CRM_Contact_DAO_Contact();
     $dao->query($query);
     // this is quite inefficient, we need to change the return
     // values in docs
     $contactArray = array();
     while ($dao->fetch()) {
         $contactArray[] = clone $dao;
     }
     return $contactArray;
 }
예제 #20
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  * @return array                Result set
  * @access public
  * @static
  */
 function &getRows($mailing_id, $job_id = null, $is_distinct = false, $offset = null, $rowCount = null, $sort = null)
 {
     $dao =& new CRM_Core_Dao();
     $bounce = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $bounceType = CRM_Mailing_DAO_BounceType::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$bounce}.time_stamp as date,\n                        {$bounce}.bounce_reason as reason,\n                        {$bounceType}.name as bounce_type\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$bounce}\n                    ON  {$bounce}.event_queue_id = {$queue}.id\n            LEFT JOIN   {$bounceType}\n                    ON  {$bounce}.bounce_type_id = {$bounceType}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $query .= " ORDER BY {$contact}.sort_name, {$bounce}.time_stamp ";
     if ($offset) {
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'type' => empty($dao->bounce_type) ? ts('Unknown') : $dao->bounce_type, 'reason' => $dao->reason, 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
예제 #21
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)
 {
     $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
     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');
         $eventEmail = array();
         CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
         if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
             $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
             $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
             $fromEmailId = array('cc' => CRM_Utils_Array::value('cc_confirm', $eventEmail), 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventEmail));
             $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
         }
     }
     return $fromEmailValues;
 }
예제 #22
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  * @return array                Result set
  * @access public
  * @static
  */
 public static function &getRows($mailing_id, $job_id = null, $is_distinct = false, $offset = null, $rowCount = null, $sort = null)
 {
     $dao =& new CRM_Core_Dao();
     $unsub = self::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$unsub}.time_stamp as date,\n                        {$unsub}.org_unsubscribe as org_unsubscribe\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$unsub}\n                    ON  {$unsub}.event_queue_id = {$queue}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n                    AND {$job}.is_test = 0\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $query .= " ORDER BY {$contact}.sort_name, {$unsub}.time_stamp DESC ";
     if ($offset) {
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'org' => $dao->org_unsubscribe ? ts('Yes') : ts('No'), 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
예제 #23
0
파일: Forward.php 프로젝트: bhirsch/voipdev
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  * @return array                Result set
  * @access public
  * @static
  */
 public static function &getRows($mailing_id, $job_id = null, $is_distinct = false, $offset = null, $rowCount = null, $sort = null)
 {
     $dao =& new CRM_Core_Dao();
     $forward = self::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as from_name,\n                        {$contact}.id as from_id,\n                        {$email}.email as from_email,\n                        dest_contact.id as dest_id,\n                        dest_email.email as dest_email,\n                        {$forward}.time_stamp as date\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$forward}\n                    ON  {$forward}.event_queue_id = {$queue}.id\n            INNER JOIN  {$queue} as dest_queue\n                    ON  {$forward}.dest_queue_id = dest_queue.id\n            INNER JOIN  {$contact} as dest_contact\n                    ON  dest_queue.contact_id = dest_contact.id\n            INNER JOIN  {$email} as dest_email\n                    ON  dest_queue.email_id = dest_email.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n                    AND {$job}.is_test = 0\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $query .= " ORDER BY {$contact}.sort_name, {$forward}.time_stamp DESC ";
     if ($offset || $rowCount) {
         //Added "||$rowCount" to avoid displaying all records on first page
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $from_url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->from_id}");
         $dest_url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->dest_id}");
         $results[] = array('from_name' => "<a href=\"{$from_url}\">{$dao->from_name}</a>", 'from_email' => $dao->from_email, 'dest_email' => "<a href=\"{$dest_url}\">{$dao->dest_email}</a>", 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
예제 #24
0
파일: Event.php 프로젝트: hguru/224Civi
 /**
  * returns the column headers as an array of tuples:
  * (name, sortName (key to the sort array))
  *
  * @param string $action the action being performed
  * @param enum   $output what should the result set include (web/email/csv)
  *
  * @return array the column headers that need to be displayed
  * @access public
  */
 function &getColumnHeaders($action = NULL, $output = NULL)
 {
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     if (!isset($this->_columnHeaders)) {
         $this->_columnHeaders = array(array('name' => ts('Contact'), 'sort' => $contact . '.sort_name', 'direction' => CRM_Utils_Sort::ASCENDING), array('name' => ts('Email Address'), 'sort' => $email . '.email', 'direction' => CRM_Utils_Sort::DONTCARE));
         switch ($this->_event_type) {
             case 'queue':
                 $dateSort = $job . '.start_date';
                 break;
             case 'delivered':
                 $dateSort = CRM_Mailing_Event_BAO_Delivered::getTableName() . '.time_stamp';
                 break;
             case 'opened':
                 $dateSort = CRM_Mailing_Event_BAO_Opened::getTableName() . '.time_stamp';
                 break;
             case 'bounce':
                 $dateSort = CRM_Mailing_Event_BAO_Bounce::getTableName() . '.time_stamp';
                 $this->_columnHeaders = array_merge($this->_columnHeaders, array(array('name' => ts('Bounce Type')), array('name' => ts('Bounce Reason'))));
                 break;
             case 'forward':
                 $dateSort = CRM_Mailing_Event_BAO_Forward::getTableName() . '.time_stamp';
                 $this->_columnHeaders = array_merge($this->_columnHeaders, array(array('name' => ts('Forwarded Email'))));
                 break;
             case 'reply':
                 $dateSort = CRM_Mailing_Event_BAO_Reply::getTableName() . '.time_stamp';
                 break;
             case 'unsubscribe':
                 $dateSort = CRM_Mailing_Event_BAO_Unsubscribe::getTableName() . '.time_stamp';
                 $this->_columnHeaders = array_merge($this->_columnHeaders, array(array('name' => ts('Unsubscribe'))));
                 break;
             case 'optout':
                 $dateSort = CRM_Mailing_Event_BAO_Unsubscribe::getTableName() . '.time_stamp';
                 $this->_columnHeaders = array_merge($this->_columnHeaders, array(array('name' => ts('Opt-Out'))));
                 break;
             case 'click':
                 $dateSort = CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName() . '.time_stamp';
                 $this->_columnHeaders = array_merge($this->_columnHeaders, array(array('name' => ts('URL'))));
                 break;
             default:
                 return 0;
         }
         $this->_columnHeaders = array_merge($this->_columnHeaders, array(array('name' => ts('Date'), 'sort' => $dateSort, 'direction' => CRM_Utils_Sort::DESCENDING)));
     }
     return $this->_columnHeaders;
 }
예제 #25
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     // Check permission for action.
     if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     }
     parent::preProcess();
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     // Get price set id.
     $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
     $this->set('priceSetId', $this->_priceSetId);
     $this->assign('priceSetId', $this->_priceSetId);
     // Get the pledge payment id
     $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
     $this->assign('action', $this->_action);
     // Get the contribution id if update
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     if (!empty($this->_id)) {
         $this->assign('contribID', $this->_id);
     }
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('context', $this->_context);
     $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
     $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
     //set the contribution mode.
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     $this->assign('contributionMode', $this->_mode);
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->assign('showCheckNumber', TRUE);
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
     $this->assignPaymentRelatedVariables();
     if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
         $this->preProcessPledge();
     }
     if ($this->_id) {
         $this->showRecordLinkMesssage($this->_id);
     }
     $this->_values = array();
     // Current contribution id.
     if ($this->_id) {
         $this->assignPremiumProduct($this->_id);
         $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
     }
     // when custom data is included in this page
     if (!empty($_POST['hidden_custom'])) {
         $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
     }
     $this->_lineItems = array();
     if ($this->_id) {
         if (!empty($this->_compId) && $this->_compContext == 'participant') {
             $this->assign('compId', $this->_compId);
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
         } else {
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
         }
         empty($lineItem) ? NULL : ($this->_lineItems[] = $lineItem);
     }
     $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems);
     // Set title
     if ($this->_mode) {
         $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
     } else {
         $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
     }
     if ($this->_id) {
         CRM_Contribute_Form_SoftCredit::preprocess($this);
     }
 }
예제 #26
0
 /**
  * Set variables in a way that can be accessed from different places.
  *
  * This is part of refactoring for unit testability on the submit function.
  *
  * @param array $params
  */
 protected function setContextVariables($params)
 {
     $variables = array('action' => '_action', 'context' => '_context', 'id' => '_id', 'cid' => '_contactID', 'mode' => '_mode');
     foreach ($variables as $paramKey => $classVar) {
         if (isset($params[$paramKey]) && !isset($this->{$classVar})) {
             $this->{$classVar} = $params[$paramKey];
         }
     }
     if ($this->_mode) {
         $this->assignPaymentRelatedVariables();
     }
     if ($this->_id) {
         $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
         $this->_membershipIDs[] = $this->_id;
     }
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
 }
예제 #27
0
 /**
  * Ensure that civicrm_contact.modified_date is updated when manipulating a phone record.
  */
 public function testTimestampsEmail()
 {
     $test = $this;
     $this->_testTimestamps(array('INSERT' => function ($contactId) use($test) {
         $params = array('email' => '*****@*****.**', 'is_primary' => 1, 'location_type_id' => 1, 'contact_id' => $contactId);
         CRM_Core_BAO_Email::add($params);
         $test->assertDBQuery('*****@*****.**', 'SELECT email FROM civicrm_email WHERE contact_id = %1 ORDER BY id DESC LIMIT 1', array(1 => array($contactId, 'Integer')));
     }, 'UPDATE' => function ($contactId) use($test) {
         CRM_Core_DAO::executeQuery('UPDATE civicrm_email SET email = "*****@*****.**" WHERE contact_id = %1', array(1 => array($contactId, 'Integer')));
     }, 'DELETE' => function ($contactId) use($test) {
         CRM_Core_DAO::executeQuery('DELETE FROM civicrm_email WHERE contact_id = %1', array(1 => array($contactId, 'Integer')));
     }));
 }
예제 #28
0
 /**
  * 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);
     }
 }
예제 #29
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  * @return array                Result set
  * @access public
  * @static
  */
 function &getRows($mailing_id, $job_id = null, $offset = null, $rowCount = null, $sort = null)
 {
     $dao =& new CRM_Core_Dao();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$job}.start_date as date\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     $query .= " ORDER BY {$contact}.sort_name, {$job}.start_date ";
     if ($offset) {
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
 /**
  * note that $job_id is used only as a variable in the temp table construction
  * and does not play a role in the queries generated
  * @param int $job_id
  *   (misnomer) a nonce value used to name temporary tables.
  * @param int $mailing_id
  * @param bool $storeRecipients
  * @param bool $dedupeEmail
  * @param null $mode
  *
  * @return CRM_Mailing_Event_BAO_Queue|string
  */
 public static function getRecipients($job_id, $mailing_id = NULL, $storeRecipients = FALSE, $dedupeEmail = FALSE, $mode = NULL)
 {
     $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $mg = CRM_Mailing_DAO_MailingGroup::getTableName();
     $eq = CRM_Mailing_Event_DAO_Queue::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     if ($mode == 'sms') {
         $phone = CRM_Core_DAO_Phone::getTableName();
     }
     $contact = CRM_Contact_DAO_Contact::getTableName();
     $group = CRM_Contact_DAO_Group::getTableName();
     $g2contact = CRM_Contact_DAO_GroupContact::getTableName();
     $m = new CRM_Mailing_DAO_Mailing();
     $m->id = $mailing_id;
     $m->find(TRUE);
     $email_selection_method = $m->email_selection_method;
     $location_type_id = $m->location_type_id;
     // Note: When determining the ORDER that results are returned, it's
     // the record that comes last that counts. That's because we are
     // INSERT'ing INTO a table with a primary id so that last record
     // over writes any previous record.
     switch ($email_selection_method) {
         case 'location-exclude':
             $location_filter = "({$email}.location_type_id != {$location_type_id})";
             // If there is more than one email that doesn't match the location,
             // prefer the one marked is_bulkmail, followed by is_primary.
             $order_by = "ORDER BY {$email}.is_bulkmail, {$email}.is_primary";
             break;
         case 'location-only':
             $location_filter = "({$email}.location_type_id = {$location_type_id})";
             // If there is more than one email of the desired location, prefer
             // the one marked is_bulkmail, followed by is_primary.
             $order_by = "ORDER BY {$email}.is_bulkmail, {$email}.is_primary";
             break;
         case 'location-prefer':
             $location_filter = "({$email}.is_bulkmail = 1 OR {$email}.is_primary = 1 OR {$email}.location_type_id = {$location_type_id})";
             // ORDER BY is more complicated because we have to set an arbitrary
             // order that prefers the location that we want. We do that using
             // the FIELD function. For more info, see:
             // https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
             // We assign the location type we want the value "1" by putting it
             // in the first position after we name the field. All other location
             // types are left out, so they will be assigned the value 0. That
             // means, they will all be equally tied for first place, with our
             // location being last.
             $order_by = "ORDER BY FIELD({$email}.location_type_id, {$location_type_id}), {$email}.is_bulkmail, {$email}.is_primary";
             break;
         case 'automatic':
             // fall through to default
         // fall through to default
         default:
             $location_filter = "({$email}.is_bulkmail = 1 OR {$email}.is_primary = 1)";
             $order_by = "ORDER BY {$email}.is_bulkmail";
     }
     /* Create a temp table for contact exclusion */
     $mailingGroup->query("CREATE TEMPORARY TABLE X_{$job_id}\n            (contact_id int primary key)\n            ENGINE=HEAP");
     /* Add all the members of groups excluded from this mailing to the temp
      * table */
     $excludeSubGroup = "INSERT INTO        X_{$job_id} (contact_id)\n                    SELECT  DISTINCT    {$g2contact}.contact_id\n                    FROM                {$g2contact}\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id AND {$mg}.entity_table = '{$group}'\n                    WHERE\n                                        {$mg}.mailing_id = {$mailing_id}\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$mg}.group_type = 'Exclude'";
     $mailingGroup->query($excludeSubGroup);
     /* Add all unsubscribe members of base group from this mailing to the temp
      * table */
     $unSubscribeBaseGroup = "INSERT INTO        X_{$job_id} (contact_id)\n                    SELECT  DISTINCT    {$g2contact}.contact_id\n                    FROM                {$g2contact}\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id AND {$mg}.entity_table = '{$group}'\n                    WHERE\n                                        {$mg}.mailing_id = {$mailing_id}\n                        AND             {$g2contact}.status = 'Removed'\n                        AND             {$mg}.group_type = 'Base'";
     $mailingGroup->query($unSubscribeBaseGroup);
     /* Add all the (intended) recipients of an excluded prior mailing to
      * the temp table */
     $excludeSubMailing = "INSERT IGNORE INTO X_{$job_id} (contact_id)\n                    SELECT  DISTINCT    {$eq}.contact_id\n                    FROM                {$eq}\n                    INNER JOIN          {$job}\n                            ON          {$eq}.job_id = {$job}.id\n                    INNER JOIN          {$mg}\n                            ON          {$job}.mailing_id = {$mg}.entity_id AND {$mg}.entity_table = '{$mailing}'\n                    WHERE\n                                        {$mg}.mailing_id = {$mailing_id}\n                        AND             {$mg}.group_type = 'Exclude'";
     $mailingGroup->query($excludeSubMailing);
     // get all the saved searches AND hierarchical groups
     // and load them in the cache
     $sql = "\nSELECT     {$group}.id, {$group}.cache_date, {$group}.saved_search_id, {$group}.children\nFROM       {$group}\nINNER JOIN {$mg} ON {$mg}.entity_id = {$group}.id\nWHERE      {$mg}.entity_table = '{$group}'\n  AND      {$mg}.group_type = 'Exclude'\n  AND      {$mg}.mailing_id = {$mailing_id}\n  AND      ( saved_search_id != 0\n   OR        saved_search_id IS NOT NULL\n   OR        children IS NOT NULL )\n";
     $groupDAO = CRM_Core_DAO::executeQuery($sql);
     while ($groupDAO->fetch()) {
         if ($groupDAO->cache_date == NULL) {
             CRM_Contact_BAO_GroupContactCache::load($groupDAO);
         }
         $smartGroupExclude = "\nINSERT IGNORE INTO X_{$job_id} (contact_id)\nSELECT c.contact_id\nFROM   civicrm_group_contact_cache c\nWHERE  c.group_id = {$groupDAO->id}\n";
         $mailingGroup->query($smartGroupExclude);
     }
     $tempColumn = 'email_id';
     if ($mode == 'sms') {
         $tempColumn = 'phone_id';
     }
     /* Get all the group contacts we want to include */
     $mailingGroup->query("CREATE TEMPORARY TABLE I_{$job_id}\n            ({$tempColumn} int, contact_id int primary key)\n            ENGINE=HEAP");
     /* Get the group contacts, but only those which are not in the
      * exclusion temp table */
     $query = "REPLACE INTO       I_{$job_id} (email_id, contact_id)\n\n                    SELECT DISTINCT     {$email}.id as email_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$email}\n                    INNER JOIN          {$contact}\n                            ON          {$email}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                                AND     {$mg}.entity_table = '{$group}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$mg}.search_id IS NULL\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_email = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$location_filter}\n                        AND             {$email}.email IS NOT NULL\n                        AND             {$email}.email != ''\n                        AND             {$email}.on_hold = 0\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null\n                    {$order_by}";
     if ($mode == 'sms') {
         $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
         $query = "REPLACE INTO       I_{$job_id} (phone_id, contact_id)\n\n                    SELECT DISTINCT     {$phone}.id as phone_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$phone}\n                    INNER JOIN          {$contact}\n                            ON          {$phone}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                                AND     {$mg}.entity_table = '{$group}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$mg}.search_id IS NULL\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_sms = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$phone}.phone_type_id = {$phoneTypes['Mobile']}\n                        AND             {$phone}.phone IS NOT NULL\n                        AND             {$phone}.phone != ''\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null";
     }
     $mailingGroup->query($query);
     /* Query prior mailings */
     $query = "REPLACE INTO       I_{$job_id} (email_id, contact_id)\n                    SELECT DISTINCT     {$email}.id as email_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$email}\n                    INNER JOIN          {$contact}\n                            ON          {$email}.contact_id = {$contact}.id\n                    INNER JOIN          {$eq}\n                            ON          {$eq}.contact_id = {$contact}.id\n                    INNER JOIN          {$job}\n                            ON          {$eq}.job_id = {$job}.id\n                    INNER JOIN          {$mg}\n                            ON          {$job}.mailing_id = {$mg}.entity_id AND {$mg}.entity_table = '{$mailing}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$contact}.do_not_email = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$location_filter}\n                        AND             {$email}.on_hold = 0\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null\n                    {$order_by}";
     if ($mode == 'sms') {
         $query = "REPLACE INTO       I_{$job_id} (phone_id, contact_id)\n                    SELECT DISTINCT     {$phone}.id as phone_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$phone}\n                    INNER JOIN          {$contact}\n                            ON          {$phone}.contact_id = {$contact}.id\n                    INNER JOIN          {$eq}\n                            ON          {$eq}.contact_id = {$contact}.id\n                    INNER JOIN          {$job}\n                            ON          {$eq}.job_id = {$job}.id\n                    INNER JOIN          {$mg}\n                            ON          {$job}.mailing_id = {$mg}.entity_id AND {$mg}.entity_table = '{$mailing}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$contact}.do_not_sms = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$phone}.phone_type_id = {$phoneTypes['Mobile']}\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null";
     }
     $mailingGroup->query($query);
     $sql = "\nSELECT     {$group}.id, {$group}.cache_date, {$group}.saved_search_id, {$group}.children\nFROM       {$group}\nINNER JOIN {$mg} ON {$mg}.entity_id = {$group}.id\nWHERE      {$mg}.entity_table = '{$group}'\n  AND      {$mg}.group_type = 'Include'\n  AND      {$mg}.search_id IS NULL\n  AND      {$mg}.mailing_id = {$mailing_id}\n  AND      ( saved_search_id != 0\n   OR        saved_search_id IS NOT NULL\n   OR        children IS NOT NULL )\n";
     $groupDAO = CRM_Core_DAO::executeQuery($sql);
     while ($groupDAO->fetch()) {
         if ($groupDAO->cache_date == NULL) {
             CRM_Contact_BAO_GroupContactCache::load($groupDAO);
         }
         $smartGroupInclude = "\nREPLACE INTO I_{$job_id} (email_id, contact_id)\nSELECT     civicrm_email.id as email_id, c.id as contact_id\nFROM       civicrm_contact c\nINNER JOIN civicrm_email                ON civicrm_email.contact_id         = c.id\nINNER JOIN civicrm_group_contact_cache gc ON gc.contact_id        = c.id\nLEFT  JOIN X_{$job_id}                      ON X_{$job_id}.contact_id = c.id\nWHERE      gc.group_id = {$groupDAO->id}\n  AND      c.do_not_email = 0\n  AND      c.is_opt_out = 0\n  AND      c.is_deceased <> 1\n  AND      {$location_filter}\n  AND      civicrm_email.on_hold = 0\n  AND      X_{$job_id}.contact_id IS null\n{$order_by}\n";
         if ($mode == 'sms') {
             $smartGroupInclude = "\nREPLACE INTO I_{$job_id} (phone_id, contact_id)\nSELECT     p.id as phone_id, c.id as contact_id\nFROM       civicrm_contact c\nINNER JOIN civicrm_phone p                ON p.contact_id         = c.id\nINNER JOIN civicrm_group_contact_cache gc ON gc.contact_id        = c.id\nLEFT  JOIN X_{$job_id}                      ON X_{$job_id}.contact_id = c.id\nWHERE      gc.group_id = {$groupDAO->id}\n  AND      c.do_not_sms = 0\n  AND      c.is_opt_out = 0\n  AND      c.is_deceased <> 1\n  AND      p.phone_type_id = {$phoneTypes['Mobile']}\n  AND      X_{$job_id}.contact_id IS null";
         }
         $mailingGroup->query($smartGroupInclude);
     }
     /**
      * Construct the filtered search queries
      */
     $query = "\nSELECT search_id, search_args, entity_id\nFROM   {$mg}\nWHERE  {$mg}.search_id IS NOT NULL\nAND    {$mg}.mailing_id = {$mailing_id}\n";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $customSQL = CRM_Contact_BAO_SearchCustom::civiMailSQL($dao->search_id, $dao->search_args, $dao->entity_id);
         $query = "REPLACE INTO       I_{$job_id} ({$tempColumn}, contact_id)\n                         {$customSQL}";
         $mailingGroup->query($query);
     }
     /* Get the emails with only location override */
     $query = "REPLACE INTO       I_{$job_id} (email_id, contact_id)\n                    SELECT DISTINCT     {$email}.id as local_email_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$email}\n                    INNER JOIN          {$contact}\n                            ON          {$email}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                        {$mg}.entity_table = '{$group}'\n                        AND             {$mg}.group_type = 'Include'\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_email = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$location_filter}\n                        AND             {$email}.on_hold = 0\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null\n                    {$order_by}";
     if ($mode == "sms") {
         $query = "REPLACE INTO       I_{$job_id} (phone_id, contact_id)\n                    SELECT DISTINCT     {$phone}.id as phone_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$phone}\n                    INNER JOIN          {$contact}\n                            ON          {$phone}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                        {$mg}.entity_table = '{$group}'\n                        AND             {$mg}.group_type = 'Include'\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_sms = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$phone}.phone_type_id = {$phoneTypes['Mobile']}\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null";
     }
     $mailingGroup->query($query);
     $eq = new CRM_Mailing_Event_BAO_Queue();
     list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause();
     $aclWhere = $aclWhere ? "WHERE {$aclWhere}" : '';
     if ($storeRecipients && $mailing_id) {
         $sql = "\nDELETE\nFROM   civicrm_mailing_recipients\nWHERE  mailing_id = %1\n";
         $params = array(1 => array($mailing_id, 'Integer'));
         CRM_Core_DAO::executeQuery($sql, $params);
         // CRM-3975
         $groupBy = $groupJoin = '';
         if ($dedupeEmail) {
             $groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
             $groupBy = " GROUP BY e.email ";
         }
         $sql = "\nINSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )\nSELECT %1, i.contact_id, i.{$tempColumn}\nFROM       civicrm_contact contact_a\nINNER JOIN I_{$job_id} i ON contact_a.id = i.contact_id\n           {$groupJoin}\n           {$aclFrom}\n           {$aclWhere}\n           {$groupBy}\nORDER BY   i.contact_id, i.{$tempColumn}\n";
         CRM_Core_DAO::executeQuery($sql, $params);
         // if we need to add all emails marked bulk, do it as a post filter
         // on the mailing recipients table
         if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
             self::addMultipleEmails($mailing_id);
         }
     }
     /* Delete the temp table */
     $mailingGroup->reset();
     $mailingGroup->query("DROP TEMPORARY TABLE X_{$job_id}");
     $mailingGroup->query("DROP TEMPORARY TABLE I_{$job_id}");
     return $eq;
 }