/**
  * Confirm a pending subscription
  *
  * @param int $contact_id       The id of the contact
  * @param int $subscribe_id     The id of the subscription event
  * @param string $hash          The hash
  *
  * @return boolean              True on success
  * @access public
  * @static
  */
 public static function confirm($contact_id, $subscribe_id, $hash)
 {
     $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash);
     if (!$se) {
         return FALSE;
     }
     // before we proceed lets just check if this contact is already 'Added'
     // if so, we should ignore this request and hence avoid sending multiple
     // emails - CRM-11157
     $details = CRM_Contact_BAO_GroupContact::getMembershipDetail($contact_id, $se->group_id);
     if ($details && $details->status == 'Added') {
         // This contact is already subscribed
         // lets return the group title
         return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $se->group_id, 'title');
     }
     $transaction = new CRM_Core_Transaction();
     $ce = new CRM_Mailing_Event_BAO_Confirm();
     $ce->event_subscribe_id = $se->id;
     $ce->time_stamp = date('YmdHis');
     $ce->save();
     CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id);
     $transaction->commit();
     $config = CRM_Core_Config::singleton();
     $domain = CRM_Core_BAO_Domain::getDomain();
     list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail();
     list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id);
     $group = new CRM_Contact_DAO_Group();
     $group->id = $se->group_id;
     $group->find(TRUE);
     $component = new CRM_Mailing_BAO_Component();
     $component->is_default = 1;
     $component->is_active = 1;
     $component->component_type = 'Welcome';
     $component->find(TRUE);
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $html = $component->body_html;
     if ($component->body_text) {
         $text = $component->body_text;
     } else {
         $text = CRM_Utils_String::htmlToText($component->body_html);
     }
     $bao = new CRM_Mailing_BAO_Mailing();
     $bao->body_text = $text;
     $bao->body_html = $html;
     $tokens = $bao->getTokens();
     $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
     $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, TRUE);
     $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
     $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE);
     $mailParams = array('groupName' => 'Mailing Event ' . $component->component_type, 'subject' => $component->subject, 'from' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'toEmail' => $email, 'toName' => $display_name, 'replyTo' => "do-not-reply@{$emailDomain}", 'returnPath' => "do-not-reply@{$emailDomain}", 'html' => $html, 'text' => $text);
     // send - ignore errors because the desired status change has already been successful
     $unused_result = CRM_Utils_Mail::send($mailParams);
     return $group->title;
 }
 function testForceCiviToMailchimpSyncNullEmail()
 {
     $mailchimp_sync_setting = CRM_CiviMailchimp_BAO_SyncSettingsTest::createTestGroupAndSyncSettings('Test Group testForceCiviToMailchimpSyncNullEmail');
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     unset($params['email']);
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contact_ids = array($contact->id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $mailchimp_sync_setting->civicrm_group_id);
     $contacts = CRM_CiviMailchimp_Form_Sync::forceCiviToMailchimpSync($mailchimp_sync_setting);
     $mailchimp_api_subscribe = civimailchimp_static('mailchimp_api_subscribe');
     $this->assertCount(0, $contacts);
     $this->assertNull($mailchimp_api_subscribe);
 }
 function testFindByContactId()
 {
     $expected_mailchimp_sync_setting = self::createTestGroupAndSyncSettings('Test group testFindByContactId');
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contact_ids = array($contact->id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $expected_mailchimp_sync_setting->civicrm_group_id);
     $mailchimp_sync_settings = CRM_CiviMailchimp_BAO_SyncSettings::findByContactId($contact->id);
     $mailchimp_sync_setting = $mailchimp_sync_settings[$expected_mailchimp_sync_setting->civicrm_group_id];
     $this->assertEquals($expected_mailchimp_sync_setting->id, $mailchimp_sync_setting->id);
     $this->assertEquals($expected_mailchimp_sync_setting->civicrm_group_id, $mailchimp_sync_setting->civicrm_group_id);
     $this->assertEquals($expected_mailchimp_sync_setting->mailchimp_list_id, $mailchimp_sync_setting->mailchimp_list_id);
     $this->assertEquals($expected_mailchimp_sync_setting->mailchimp_interest_groups, $mailchimp_sync_setting->mailchimp_interest_groups);
 }
Exemple #4
0
/**
 * subscribe contacts to a group 
 * 
 * @param CRM_Contact $group       A valid group object (passed by reference).
 * @param array       $contacts    An array of one or more valid Contact objects (passed by reference).
 *
 *  
 * @return null if success or CRM_Error (db error or contacts were not valid)
 *
 * @access public
 */
function crm_subscribe_group_contacts(&$group, $contacts)
{
    _crm_initialize();
    if (!is_array($contacts)) {
        return _crm_error('$contacts is not  Array ');
    }
    if (!is_a($group, 'CRM_Contact_BAO_Group') && !is_a($group, 'CRM_Contact_DAO_Group')) {
        return _crm_error('Invalid group object passed in');
    }
    foreach ($contacts as $contact) {
        if (!isset($contact->id)) {
            return _crm_error('Invalid contact object passed in');
        }
        $contactID[] = $contact->id;
    }
    $status = 'Pending';
    $method = 'Email';
    CRM_Contact_BAO_GroupContact::addContactsToGroup($contactID, $group->id, $method, $status);
    return null;
}
Exemple #5
0
 /**
  * Register a subscription event.  Create a new contact if one does not
  * already exist.
  *
  * @param int $group_id
  *   The group id to subscribe to.
  * @param string $email
  *   The email address of the (new) contact.
  * @param int $contactId
  *   Currently used during event registration/contribution.
  *   Specifically to avoid linking group to wrong duplicate contact
  *   during event registration.
  * @param string $context
  *
  * @return int|null
  *   $se_id      The id of the subscription event, null on failure
  */
 public static function &subscribe($group_id, $email, $contactId = NULL, $context = NULL)
 {
     // CRM-1797 - allow subscription only to public groups
     $params = array('id' => (int) $group_id);
     $defaults = array();
     $contact_id = NULL;
     $success = NULL;
     $bao = CRM_Contact_BAO_Group::retrieve($params, $defaults);
     if ($bao && substr($bao->visibility, 0, 6) != 'Public' && $context != 'profile') {
         return $success;
     }
     $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
     $email = $strtolower($email);
     // process the query only if no contactId
     if ($contactId) {
         $contact_id = $contactId;
     } else {
         /* First, find out if the contact already exists */
         $query = "\n   SELECT DISTINCT contact_a.id as contact_id\n     FROM civicrm_contact contact_a\nLEFT JOIN civicrm_email      ON contact_a.id = civicrm_email.contact_id\n    WHERE civicrm_email.email = %1 AND contact_a.is_deleted = 0";
         $params = array(1 => array($email, 'String'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         $id = array();
         // lets just use the first contact id we got
         if ($dao->fetch()) {
             $contact_id = $dao->contact_id;
         }
         $dao->free();
     }
     $transaction = new CRM_Core_Transaction();
     if (!$contact_id) {
         require_once 'CRM/Utils/DeprecatedUtils.php';
         /* If the contact does not exist, create one. */
         $formatted = array('contact_type' => 'Individual', 'version' => 3);
         $locationType = CRM_Core_BAO_LocationType::getDefault();
         $value = array('email' => $email, 'location_type_id' => $locationType->id);
         _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
         $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP;
         $formatted['fixAddress'] = TRUE;
         require_once 'api/api.php';
         $contact = civicrm_api('contact', 'create', $formatted);
         if (civicrm_error($contact)) {
             return $success;
         }
         $contact_id = $contact['id'];
     } elseif (!is_numeric($contact_id) && (int) $contact_id > 0) {
         // make sure contact_id is numeric
         return $success;
     }
     /* Get the primary email id from the contact to use as a hash input */
     $dao = new CRM_Core_DAO();
     $query = "\nSELECT     civicrm_email.id as email_id\n  FROM     civicrm_email\n     WHERE civicrm_email.email = %1\n       AND civicrm_email.contact_id = %2";
     $params = array(1 => array($email, 'String'), 2 => array($contact_id, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     if (!$dao->fetch()) {
         CRM_Core_Error::fatal('Please file an issue with the backtrace');
         return $success;
     }
     $se = new CRM_Mailing_Event_BAO_Subscribe();
     $se->group_id = $group_id;
     $se->contact_id = $contact_id;
     $se->time_stamp = date('YmdHis');
     $se->hash = substr(sha1("{$group_id}:{$contact_id}:{$dao->email_id}:" . time()), 0, 16);
     $se->save();
     $contacts = array($contact_id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id);
     $transaction->commit();
     return $se;
 }
 /**
  * @param int $groupID
  */
 public function add2group($groupID)
 {
     if (is_numeric($groupID)) {
         $sql = "\n{$this->_select} {$this->_from}  {$this->_where} {$this->_groupBy}\nORDER BY civicrm_contribution_total_amount_sum DESC\n) as abc {$this->_groupLimit}";
         $dao = CRM_Core_DAO::executeQuery($sql);
         $contact_ids = array();
         // Add resulting contacts to group
         while ($dao->fetch()) {
             $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
         }
         CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
         CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
     }
 }
 /**
  *
  * @return void
  */
 public function postProcess()
 {
     $contactID = array($this->_contactId);
     $groupId = $this->controller->exportValue('GroupContact', 'group_id');
     $method = $this->_context == 'user' ? 'Web' : 'Admin';
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     if ($userID == $this->_contactId) {
         $method = 'Web';
     }
     $groupContact = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactID, $groupId, $method);
     if ($groupContact && $this->_context != 'user') {
         $groups = CRM_Core_PseudoConstant::group();
         CRM_Core_Session::setStatus(ts("Contact has been added to '%1'.", array(1 => $groups[$groupId])), ts('Added to Group'), 'success');
     }
 }
/**
 * Update group contact status.
 *
 * @deprecated - this should be part of create but need to know we aren't missing something
 *
 * @param array $params
 *
 * @return bool
 * @throws \API_Exception
 */
function civicrm_api3_group_contact_update_status($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('contact_id', 'group_id'));
    CRM_Contact_BAO_GroupContact::addContactsToGroup(array($params['contact_id']), $params['group_id'], CRM_Utils_Array::value('method', $params, 'API'), 'Added', CRM_Utils_Array::value('tracking', $params));
    return TRUE;
}
  /**
   * @param $groupID
   */
  function add2group($groupID) {
    if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
      $contact = CRM_Utils_Array::value('btn_group_contact', $this->_submitValues, 'civicrm_contact');
      $select = "SELECT DISTINCT {$this->_aliases[$contact]}.id AS addtogroup_contact_id";
      //    $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);

      $sql = "{$select} {$this->_from} {$this->_where} AND {$this->_aliases[$contact]}.id IS NOT NULL {$this->_groupBy}  {$this->_having} {$this->_orderBy}";
      $sql = str_replace('WITH ROLLUP', '', $sql);
      $dao = CRM_Core_DAO::executeQuery($sql);

      $contact_ids = array();
      // Add resulting contacts to group
      while ($dao->fetch()) {
        $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
      }

      CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
      CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."));
    }
  }
 /**
 * takes an associative array and sends a thank you or email verification email
 *
 * @param array $params (reference ) an assoc array of name/value pairs
 *
 * @param $sendEmailMode
 *
 * @throws Exception
 * @return void
   @access public
 * @static
 */
 public static function sendEmail($params, $sendEmailMode)
 {
     /* sendEmailMode
      * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
      *   connected user via login/pwd - thank you
      *    or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
      *   or login using fb connect - thank you + click to add msg to fb wall
      *
      * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
      *  send a confirmation request email
      */
     // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
     $petitionGroupName = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'petition_contacts', NULL, 'Petition Contacts');
     $dao = new CRM_Contact_DAO_Group();
     $dao->title = $petitionGroupName;
     if (!$dao->find(TRUE)) {
         $dao->is_active = 1;
         $dao->visibility = 'User and User Admin Only';
         $dao->save();
     }
     $group_id = $dao->id;
     // get petition info
     $petitionParams['id'] = $params['sid'];
     $petitionInfo = array();
     CRM_Campaign_BAO_Survey::retrieve($petitionParams, $petitionInfo);
     if (empty($petitionInfo)) {
         CRM_Core_Error::fatal('Petition doesn\'t exist.');
     }
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $toName = CRM_Contact_BAO_Contact::displayName($params['contactId']);
     $replyTo = "do-not-reply@{$emailDomain}";
     // set additional general message template params (custom tokens to use in email msg templates)
     // tokens then available in msg template as {$petition.title}, etc
     $petitionTokens['title'] = $petitionInfo['title'];
     $petitionTokens['petitionId'] = $params['sid'];
     $tplParams['petition'] = $petitionTokens;
     switch ($sendEmailMode) {
         case CRM_Campaign_Form_Petition_Signature::EMAIL_THANK:
             // add this contact to the CIVICRM_PETITION_CONTACTS group
             // Cannot pass parameter 1 by reference
             $p = array($params['contactId']);
             CRM_Contact_BAO_GroupContact::addContactsToGroup($p, $group_id, 'API');
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_sign', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title']));
             }
             break;
         case CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM:
             // create mailing event subscription record for this contact
             // this will allow using a hash key to confirm email address by sending a url link
             $se = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $params['email-Primary'], $params['contactId'], 'profile');
             //    require_once 'CRM/Core/BAO/Domain.php';
             //    $domain = CRM_Core_BAO_Domain::getDomain();
             $config = CRM_Core_Config::singleton();
             $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
             $replyTo = implode($config->verpSeparator, array($localpart . 'c', $se->contact_id, $se->id, $se->hash)) . "@{$emailDomain}";
             $confirmUrl = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE);
             $confirmUrlPlainText = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE, NULL, FALSE);
             // set email specific message template params and assign to tplParams
             $petitionTokens['confirmUrl'] = $confirmUrl;
             $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
             $tplParams['petition'] = $petitionTokens;
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_confirmation_needed', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'], 'confirmUrl' => $confirmUrl));
             }
             break;
     }
 }
 /**
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $contactID = array($this->_contactId);
     $groupId = $this->controller->exportValue('GroupContact', 'group_id');
     $method = 'Admin';
     $method = $this->_context == 'user' ? 'Web' : 'Admin';
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     if ($userID == $this->_contactId) {
         $method = 'Web';
     }
     $groupContact = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactID, $groupId, $method);
     if ($groupContact && $this->_context != 'user') {
         CRM_Core_Session::setStatus(ts('Contact has been added to the selected group.'));
     }
 }
 /**
  * TODO: Find a way to move this into CRM_Simplemail_Form_Task_SimpleMail::postProcess()
  *
  * Note: A lot of the logic in this method (for creating hidden and smart groups) is taken from
  * CRM_Mailing_Form_Group::postProcess()
  *
  * @return null|string
  * @throws Exception
  */
 private static function createSmartContactGroupForSearchContacts()
 {
     $searchParams = simplemail_civicrm_getFromSessionScope('searchParams');
     $contactIds = simplemail_civicrm_getFromSessionScope('contactIds');
     $smartGroupId = NULL;
     if ($contactIds) {
         $resultSelectOption = $searchParams['radio_ts'];
         // Only the ticked contacts in the search result need to be sent mailing - create a hidden group for them
         if ($resultSelectOption == 'ts_sel') {
             // create a static grp if only a subset of result set was selected:
             $randID = md5(time());
             $grpTitle = "Hidden Group {$randID}";
             $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
             if (!$grpID) {
                 $groupParams = array('title' => $grpTitle, 'is_active' => 1, 'is_hidden' => 1, 'group_type' => array('2' => 1));
                 $group = CRM_Contact_BAO_Group::create($groupParams);
                 $grpID = $group->id;
                 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $group->id);
                 $newGroupTitle = "Hidden Group {$grpID}";
                 $groupParams = array('id' => $grpID, 'name' => CRM_Utils_String::titleToVar($newGroupTitle), 'title' => $newGroupTitle, 'group_type' => array('2' => 1));
                 $group = CRM_Contact_BAO_Group::create($groupParams);
             }
             // note at this point its a static group
             $smartGroupId = $grpID;
         } else {
             // Get the saved search ID
             $ssId = simplemail_civicrm_getFromSessionScope('ssId');
             $formValues = simplemail_civicrm_getFromSessionScope('formValues');
             $customSearchId = simplemail_civicrm_getFromSessionScope('customSearchId');
             $context = simplemail_civicrm_getFromSessionScope('context');
             $hiddenSmartParams = array('group_type' => array('2' => 1), 'form_values' => $formValues, 'saved_search_id' => $ssId, 'search_custom_id' => $customSearchId, 'search_context' => $context);
             list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
             // Set the saved search ID
             if (!$ssId) {
                 if ($savedSearchId) {
                     simplemail_civicrm_addToSessionScope('ssId', $savedSearchId);
                 } else {
                     CRM_Core_Error::fatal();
                 }
             }
         }
     }
     simplemail_civicrm_addToSessionScope('smartGroupId', $smartGroupId);
 }
Exemple #13
0
 /**
  * @param $contactIds
  *
  * @return array
  */
 private function _addRespondentToGroup($contactIds)
 {
     $groupAdditions = array();
     if (empty($contactIds)) {
         return $groupAdditions;
     }
     $params = $this->controller->exportValues($this->_name);
     $groups = CRM_Utils_Array::value('groups', $params, array());
     $newGroupName = CRM_Utils_Array::value('newGroupName', $params);
     $newGroupDesc = CRM_Utils_Array::value('newGroupDesc', $params);
     $newGroupId = NULL;
     //create new group.
     if ($newGroupName) {
         $grpParams = array('title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => TRUE);
         $group = CRM_Contact_BAO_Group::create($grpParams);
         $groups[] = $newGroupId = $group->id;
     }
     //add the respondents to groups.
     if (is_array($groups)) {
         $existingGroups = CRM_Core_PseudoConstant::group();
         foreach ($groups as $groupId) {
             $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             $totalCount = CRM_Utils_Array::value(1, $addCount);
             if ($groupId == $newGroupId) {
                 $name = $newGroupName;
                 $new = TRUE;
             } else {
                 $name = $existingGroups[$groupId];
                 $new = FALSE;
             }
             if ($totalCount) {
                 $url = CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId);
                 $groupAdditions[] = '<a href="' . $url . '">' . $name . '</a>';
             }
         }
     }
     return $groupAdditions;
 }
Exemple #14
0
 /**
  * Given this task's list of targets, produce a hidden group.
  *
  * @return array
  *   Array(0 => int $groupID, 1 => int|NULL $ssID).
  * @throws Exception
  */
 public function createHiddenGroup()
 {
     // Did the user select "All" matches or cherry-pick a few records?
     $searchParams = $this->controller->exportValues();
     if ($searchParams['radio_ts'] == 'ts_sel') {
         // Create a static group.
         $randID = md5(time() . rand(1, 1000));
         // groups require a unique name
         $grpTitle = "Hidden Group {$randID}";
         $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
         if (!$grpID) {
             $groupParams = array('title' => $grpTitle, 'is_active' => 1, 'is_hidden' => 1, 'group_type' => array('2' => 1));
             $group = CRM_Contact_BAO_Group::create($groupParams);
             $grpID = $group->id;
             CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
             $newGroupTitle = "Hidden Group {$grpID}";
             $groupParams = array('id' => $grpID, 'name' => CRM_Utils_String::titleToVar($newGroupTitle), 'title' => $newGroupTitle, 'group_type' => array('2' => 1));
             $group = CRM_Contact_BAO_Group::create($groupParams);
         }
         // note at this point its a static group
         return array($grpID, NULL);
     } else {
         // Create a smart group.
         $ssId = $this->get('ssID');
         $hiddenSmartParams = array('group_type' => array('2' => 1), 'form_values' => $this->get('formValues'), 'saved_search_id' => $ssId, 'search_custom_id' => $this->get('customSearchID'), 'search_context' => $this->get('context'));
         list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
         return array($smartGroupId, $savedSearchId);
     }
 }
Exemple #15
0
 private function _addImportedContactsToNewGroup($contactIds, $newGroupName, $newGroupDesc)
 {
     $newGroupId = NULL;
     if ($newGroupName) {
         /* Create a new group */
         $gParams = array('title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => TRUE);
         $group = CRM_Contact_BAO_Group::create($gParams);
         $this->_groups[] = $newGroupId = $group->id;
     }
     if (is_array($this->_groups)) {
         $groupAdditions = array();
         foreach ($this->_groups as $groupId) {
             $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             $totalCount = $addCount[1];
             if ($groupId == $newGroupId) {
                 $name = $newGroupName;
                 $new = TRUE;
             } else {
                 $name = $this->_allGroups[$groupId];
                 $new = FALSE;
             }
             $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2], 'new' => $new);
         }
         return $groupAdditions;
     }
     return FALSE;
 }
 /**
  * Unsubscribe a contact from all groups that received this mailing.
  *
  * @param int $job_id
  *   The job ID.
  * @param int $queue_id
  *   The Queue Event ID of the recipient.
  * @param string $hash
  *   The hash.
  * @param bool $return
  *   If true return the list of groups.
  *
  * @return array|null
  *   $groups    Array of all groups from which the contact was removed, or null if the queue event could not be found.
  */
 public static function &unsub_from_mailing($job_id, $queue_id, $hash, $return = FALSE)
 {
     // First make sure there's a matching queue event.
     $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     $success = NULL;
     if (!$q) {
         return $success;
     }
     $contact_id = $q->contact_id;
     $transaction = new CRM_Core_Transaction();
     $do = new CRM_Core_DAO();
     $mgObject = new CRM_Mailing_DAO_MailingGroup();
     $mg = $mgObject->getTableName();
     $jobObject = new CRM_Mailing_BAO_MailingJob();
     $job = $jobObject->getTableName();
     $mailingObject = new CRM_Mailing_BAO_Mailing();
     $mailing = $mailingObject->getTableName();
     $groupObject = new CRM_Contact_BAO_Group();
     $group = $groupObject->getTableName();
     $gcObject = new CRM_Contact_BAO_GroupContact();
     $gc = $gcObject->getTableName();
     //We Need the mailing Id for the hook...
     $do->query("SELECT {$job}.mailing_id as mailing_id\n                     FROM   {$job}\n                     WHERE {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer'));
     $do->fetch();
     $mailing_id = $do->mailing_id;
     $do->query("\n            SELECT      {$mg}.entity_table as entity_table,\n                        {$mg}.entity_id as entity_id,\n                        {$mg}.group_type as group_type\n            FROM        {$mg}\n            INNER JOIN  {$job}\n                ON      {$job}.mailing_id = {$mg}.mailing_id\n            INNER JOIN  {$group}\n                ON      {$mg}.entity_id = {$group}.id\n            WHERE       {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer') . "\n                AND     {$mg}.group_type IN ('Include', 'Base')\n                AND     {$group}.is_hidden = 0");
     // Make a list of groups and a list of prior mailings that received
     // this mailing.
     $groups = array();
     $base_groups = array();
     $mailings = array();
     while ($do->fetch()) {
         if ($do->entity_table == $group) {
             if ($do->group_type == 'Base') {
                 $base_groups[$do->entity_id] = NULL;
             } else {
                 $groups[$do->entity_id] = NULL;
             }
         } elseif ($do->entity_table == $mailing) {
             $mailings[] = $do->entity_id;
         }
     }
     // As long as we have prior mailings, find their groups and add to the
     // list.
     while (!empty($mailings)) {
         $do->query("\n                SELECT      {$mg}.entity_table as entity_table,\n                            {$mg}.entity_id as entity_id\n                FROM        {$mg}\n                WHERE       {$mg}.mailing_id IN (" . implode(', ', $mailings) . ")\n                    AND     {$mg}.group_type = 'Include'");
         $mailings = array();
         while ($do->fetch()) {
             if ($do->entity_table == $group) {
                 $groups[$do->entity_id] = TRUE;
             } elseif ($do->entity_table == $mailing) {
                 $mailings[] = $do->entity_id;
             }
         }
     }
     //Pass the groups to be unsubscribed from through a hook.
     $group_ids = array_keys($groups);
     $base_group_ids = array_keys($base_groups);
     CRM_Utils_Hook::unsubscribeGroups('unsubscribe', $mailing_id, $contact_id, $group_ids, $base_group_ids);
     // Now we have a complete list of recipient groups.  Filter out all
     // those except smart groups, those that the contact belongs to and
     // base groups from search based mailings.
     $baseGroupClause = '';
     if (!empty($base_group_ids)) {
         $baseGroupClause = "OR  {$group}.id IN(" . implode(', ', $base_group_ids) . ")";
     }
     $groupIdClause = '';
     if ($group_ids || $base_group_ids) {
         $groupIdClause = "AND {$group}.id IN (" . implode(', ', array_merge($group_ids, $base_group_ids)) . ")";
     }
     $do->query("\n            SELECT      {$group}.id as group_id,\n                        {$group}.title as title,\n                        {$group}.description as description\n            FROM        {$group}\n            LEFT JOIN   {$gc}\n                ON      {$gc}.group_id = {$group}.id\n            WHERE       {$group}.is_hidden = 0\n                        {$groupIdClause}\n                AND     ({$group}.saved_search_id is not null\n                            OR  ({$gc}.contact_id = {$contact_id}\n                                AND {$gc}.status = 'Added')\n                            {$baseGroupClause}\n                        )");
     if ($return) {
         $returnGroups = array();
         while ($do->fetch()) {
             $returnGroups[$do->group_id] = array('title' => $do->title, 'description' => $do->description);
         }
         return $returnGroups;
     } else {
         while ($do->fetch()) {
             $groups[$do->group_id] = $do->title;
         }
     }
     $contacts = array($contact_id);
     foreach ($groups as $group_id => $group_name) {
         $notremoved = FALSE;
         if ($group_name) {
             if (in_array($group_id, $base_group_ids)) {
                 list($total, $removed, $notremoved) = CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Removed');
             } else {
                 list($total, $removed, $notremoved) = CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contacts, $group_id, 'Email');
             }
         }
         if ($notremoved) {
             unset($groups[$group_id]);
         }
     }
     $ue = new CRM_Mailing_Event_BAO_Unsubscribe();
     $ue->event_queue_id = $queue_id;
     $ue->org_unsubscribe = 0;
     $ue->time_stamp = date('YmdHis');
     $ue->save();
     $transaction->commit();
     return $groups;
 }
 /**
  * Resubscribe a contact to the groups, he/she was unsubscribed from.
  *
  * @param int $job_id       The job ID
  * @param int $queue_id     The Queue Event ID of the recipient
  * @param string $hash      The hash
  * @return array|null $groups    Array of all groups to which the contact was added, or null if the queue event could not be found.
  * @access public
  * @static
  */
 public static function &resub_to_mailing($job_id, $queue_id, $hash)
 {
     /* First make sure there's a matching queue event */
     $q =& CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     $success = null;
     if (!$q) {
         return $success;
     }
     // check if this queue_id was actually unsubscribed
     $ue = new CRM_Mailing_Event_BAO_Unsubscribe();
     $ue->event_queue_id = $queue_id;
     $ue->org_unsubscribe = 0;
     if (!$ue->find(true)) {
         return $success;
     }
     $contact_id = $q->contact_id;
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $do = new CRM_Core_DAO();
     $mg = CRM_Mailing_DAO_Group::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $group = CRM_Contact_BAO_Group::getTableName();
     $gc = CRM_Contact_BAO_GroupContact::getTableName();
     $do->query("\n            SELECT      {$mg}.entity_table as entity_table,\n                        {$mg}.entity_id as entity_id\n            FROM        {$mg}\n            INNER JOIN  {$job}\n                ON      {$job}.mailing_id = {$mg}.mailing_id\n            WHERE       {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer') . "\n                AND     {$mg}.group_type = 'Include'");
     /* Make a list of groups and a list of prior mailings that received 
      * this mailing */
     $groups = array();
     $mailings = array();
     while ($do->fetch()) {
         if ($do->entity_table == $group) {
             $groups[$do->entity_id] = null;
         } else {
             if ($do->entity_table == $mailing) {
                 $mailings[] = $do->entity_id;
             }
         }
     }
     /* As long as we have prior mailings, find their groups and add to the
      * list */
     while (!empty($mailings)) {
         $do->query("\n                SELECT      {$mg}.entity_table as entity_table,\n                            {$mg}.entity_id as entity_id\n                FROM        {$mg}\n                WHERE       {$mg}.mailing_id IN (" . implode(', ', $mailings) . ")\n                    AND     {$mg}.group_type = 'Include'");
         $mailings = array();
         while ($do->fetch()) {
             if ($do->entity_table == $group) {
                 $groups[$do->entity_id] = true;
             } else {
                 if ($do->entity_table == $mailing) {
                     $mailings[] = $do->entity_id;
                 }
             }
         }
     }
     /* Now we have a complete list of recipient groups.  Filter out all
      * those except smart groups and those that the contact belongs to */
     $do->query("\n            SELECT      {$group}.id as group_id,\n                        {$group}.title as title\n            FROM        {$group}\n            LEFT JOIN   {$gc}\n                ON      {$gc}.group_id = {$group}.id\n            WHERE       {$group}.id IN (" . implode(', ', array_keys($groups)) . ")\n                AND     ({$group}.saved_search_id is not null\n                            OR  ({$gc}.contact_id = {$contact_id}\n                                AND {$gc}.status = 'Removed')\n                        )");
     while ($do->fetch()) {
         $groups[$do->group_id] = $do->title;
     }
     $contacts = array($contact_id);
     foreach ($groups as $group_id => $group_name) {
         $notadded = 0;
         if ($group_name) {
             list($total, $added, $notadded) = CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email');
         }
         if ($notadded) {
             unset($groups[$group_id]);
         }
     }
     // remove entry from Unsubscribe table.
     $ue = new CRM_Mailing_Event_BAO_Unsubscribe();
     $ue->event_queue_id = $queue_id;
     $ue->org_resubscribe = 0;
     if ($ue->find(true)) {
         $ue->delete();
     }
     $transaction->commit();
     return $groups;
 }
 function postProcess()
 {
     $values = $this->exportValues();
     // if group_id does not exist or is empty skip it
     if (isset($values['group_id']) and !empty($values['group_id'])) {
         // get method
         $groupId = $values['group_id'];
         $method = 'Admin';
         $session = CRM_Core_Session::singleton();
         $userID = $session->get('userID');
         if ($userID == $this->_contactId) {
             $method = 'Web';
         }
         $groupContact = CRM_Contact_BAO_GroupContact::addContactsToGroup(array($this->_contactId), $groupId, $method);
         // check no error
         if ($groupContact) {
             $groups = CRM_Core_PseudoConstant::group();
             //CRM_Core_Session::setStatus(ts("Contact has been added to '%1'.", array(1 => $groups[$groupId])), ts('Added to Group'), 'success');
             // set message
             $session = CRM_Core_Session::singleton();
             $session->setStatus(ts('%1 is toegevoegd aan %2 !', array($this->_display_name, $groups[$groupId])), ts('Lidmaatschap Wijziging - Groep'), 'success');
             // redirect user
             $url = CRM_Utils_System::url('civicrm/lidmaatschapwijziging/registratieopleidingbelangstelling', 'reset=1&cid=' . $this->_contactId);
             CRM_Utils_System::redirect($url);
         } else {
             // if there is a error
             // set message
             $session = CRM_Core_Session::singleton();
             $session->setStatus(ts('Er is een error: %1, %2 is niet opgeslagen !', array($result['error_message'], $this->_display_name)), ts('Lidmaatschap Wijziging - Groep'), 'error');
             // redirect user
             $url = CRM_Utils_System::url('civicrm/lidmaatschapwijziging/groep', 'reset=1&cid=' . $this->_contactId);
             CRM_Utils_System::redirect($url);
         }
     } else {
         $session = CRM_Core_Session::singleton();
         $session->setStatus(ts("Geen groep gekozen ! %1 is niet aan een groep toegevoegd.", array(1 => $this->_display_name)), ts('Lidmaatschap Wijziging - Groep'), 'warning');
         // redirect user
         $url = CRM_Utils_System::url('civicrm/lidmaatschapwijziging/registratieopleidingbelangstelling', 'reset=1&cid=' . $this->_contactId);
         CRM_Utils_System::redirect($url);
     }
     parent::postProcess();
 }
 /**
  * Add/edit/register contacts through profile.
  *
  * @param array $params
  *   Array of profile fields to be edited/added.
  * @param array $fields
  *   Array of fields from UFGroup.
  * @param int $contactID
  *   Id of the contact to be edited/added.
  * @param int $addToGroupID
  *   Specifies the default group to which contact is added.
  * @param int $ufGroupId
  *   Uf group id (profile id).
  * @param string $ctype
  * @param bool $visibility
  *   Basically lets us know where this request is coming from.
  *                                if via a profile from web, we restrict what groups are changed
  *
  * @return int
  *   contact id created/edited
  */
 public static function createProfileContact(&$params, &$fields, $contactID = NULL, $addToGroupID = NULL, $ufGroupId = NULL, $ctype = NULL, $visibility = FALSE)
 {
     // add ufGroupID to params array ( CRM-2012 )
     if ($ufGroupId) {
         $params['uf_group_id'] = $ufGroupId;
     }
     if ($contactID) {
         $editHook = TRUE;
         CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params);
     } else {
         $editHook = FALSE;
         CRM_Utils_Hook::pre('create', 'Profile', NULL, $params);
     }
     list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
     // manage is_opt_out
     if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
         $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE);
         $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
         $data['is_opt_out'] = $isOptOut;
         // on change, create new civicrm_subscription_history entry
         if ($wasOptOut != $isOptOut && !empty($contactDetails['contact_id'])) {
             $shParams = array('contact_id' => $contactDetails['contact_id'], 'status' => $isOptOut ? 'Removed' : 'Added', 'method' => 'Web');
             CRM_Contact_BAO_SubscriptionHistory::create($shParams);
         }
     }
     $contact = self::create($data);
     // contact is null if the profile does not have any contact fields
     if ($contact) {
         $contactID = $contact->id;
     }
     if (empty($contactID)) {
         CRM_Core_Error::fatal('Cannot proceed without a valid contact id');
     }
     // Process group and tag
     if (!empty($fields['group'])) {
         $method = 'Admin';
         // this for sure means we are coming in via profile since i added it to fix
         // removing contacts from user groups -- lobo
         if ($visibility) {
             $method = 'Web';
         }
         CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method);
     }
     if (!empty($fields['tag'])) {
         CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $contactID);
     }
     //to add profile in default group
     if (is_array($addToGroupID)) {
         $contactIds = array($contactID);
         foreach ($addToGroupID as $groupId) {
             CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
         }
     } elseif ($addToGroupID) {
         $contactIds = array($contactID);
         CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID);
     }
     // reset the group contact cache for this group
     CRM_Contact_BAO_GroupContactCache::remove();
     if ($editHook) {
         CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
     } else {
         CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
     }
     return $contactID;
 }
Exemple #20
0
 /**
  * Confirm email verification.
  *
  * @param int $contact_id
  *   The id of the contact.
  * @param int $subscribe_id
  *   The id of the subscription event.
  * @param string $hash
  *   The hash.
  *
  * @param int $activity_id
  * @param int $petition_id
  *
  * @return bool
  *   True on success
  */
 public static function confirm($contact_id, $subscribe_id, $hash, $activity_id, $petition_id)
 {
     $se = CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash);
     if (!$se) {
         return FALSE;
     }
     $transaction = new CRM_Core_Transaction();
     $ce = new CRM_Mailing_Event_BAO_Confirm();
     $ce->event_subscribe_id = $se->id;
     $ce->time_stamp = date('YmdHis');
     $ce->save();
     CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id);
     $bao = new CRM_Campaign_BAO_Petition();
     $bao->confirmSignature($activity_id, $contact_id, $petition_id);
 }
Exemple #21
0
 /**
  * Add contact to group.
  *
  * @param int $groupID
  */
 public function add2group($groupID)
 {
     if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
         $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
         // here are we are prepending / adding  contact id field that could be used for adding group
         // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
         if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select)) {
             $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
         } else {
             $select = str_ireplace('SELECT ', $select, $this->_select);
         }
         $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
         $sql = str_replace('WITH ROLLUP', '', $sql);
         $dao = CRM_Core_DAO::executeQuery($sql);
         $contact_ids = array();
         // Add resulting contacts to group
         while ($dao->fetch()) {
             if ($dao->addtogroup_contact_id) {
                 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
             }
         }
         if (!empty($contact_ids)) {
             CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
             CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
         } else {
             CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
         }
     }
 }
 /**
  * @param int $groupID
  *
  * @throws Exception
  */
 public function add2group($groupID)
 {
     if (CRM_Utils_Array::value("contact_target_op", $this->_params) == 'nll') {
         CRM_Core_Error::fatal(ts('Current filter criteria didn\'t have any target contact to add to group'));
     }
     $query = "{$this->_select}\nFROM civireport_activity_temp_target tar\nGROUP BY civicrm_activity_id {$this->_having} {$this->_orderBy}";
     $select = 'AS addtogroup_contact_id';
     $query = str_ireplace('AS civicrm_contact_contact_target_id', $select, $query);
     $dao = CRM_Core_DAO::executeQuery($query);
     $contactIDs = array();
     // Add resulting contacts to group
     while ($dao->fetch()) {
         if ($dao->addtogroup_contact_id) {
             $contact_id = explode(';', $dao->addtogroup_contact_id);
             if ($contact_id[0]) {
                 $contactIDs[$contact_id[0]] = $contact_id[0];
             }
         }
     }
     if (!empty($contactIDs)) {
         CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID);
         CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
     } else {
         CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
     }
 }
Exemple #23
0
 /**
  * takes an associative array and creates / removes
  * contacts from the groups
  *
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $contactId    contact id
  *
  * @return none
  * @access public
  * @static
  */
 static function create(&$params, $contactId, $visibility = false, $method = 'Admin')
 {
     $contactIds = array();
     $contactIds[] = $contactId;
     if ($contactId) {
         $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($contactId, 'Added');
         if (is_array($contactGroupList)) {
             foreach ($contactGroupList as $key) {
                 $groupId = $key['group_id'];
                 $contactGroup[$groupId] = $groupId;
             }
         }
     }
     // get the list of all the groups
     $allGroup =& CRM_Contact_BAO_GroupContact::getGroupList(0, $visibility);
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!is_array($params)) {
         $params = array();
     }
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!isset($contactGroup) || !is_array($contactGroup)) {
         $contactGroup = array();
     }
     // check which values has to be add/remove contact from group
     foreach ($allGroup as $key => $varValue) {
         if (CRM_Utils_Array::value($key, $params) && !array_key_exists($key, $contactGroup)) {
             // add contact to group
             CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $key, $method);
         } else {
             if (!CRM_Utils_Array::value($key, $params) && array_key_exists($key, $contactGroup)) {
                 // remove contact from group
                 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $key, $method);
             }
         }
     }
 }
 public function postProcess()
 {
     $values = $this->controller->exportValues($this->_name);
     //build hidden smart group. when user want to send  mailing
     //through search contact-> more action -> send Mailing. CRM-3711
     $groups = array();
     if ($this->_searchBasedMailing && $this->_contactIds) {
         $session = CRM_Core_Session::singleton();
         if ($this->_resultSelectOption == 'ts_sel') {
             // create a static grp if only a subset of result set was selected:
             $randID = md5(time());
             $grpTitle = "Hidden Group {$randID}";
             $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
             if (!$grpID) {
                 $groupParams = array('title' => $grpTitle, 'is_active' => 1, 'is_hidden' => 1, 'group_type' => array('2' => 1));
                 $group = CRM_Contact_BAO_Group::create($groupParams);
                 $grpID = $group->id;
                 CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
                 $newGroupTitle = "Hidden Group {$grpID}";
                 $groupParams = array('id' => $grpID, 'name' => CRM_Utils_String::titleToVar($newGroupTitle), 'title' => $newGroupTitle);
                 $group = CRM_Contact_BAO_Group::create($groupParams);
             }
             // note at this point its a static group
             $smartGroupId = $grpID;
         } else {
             //get the hidden smart group id.
             $ssId = $this->get('ssID');
             $hiddenSmartParams = array('group_type' => array('2' => 1), 'form_values' => $this->get('formValues'), 'saved_search_id' => $ssId, 'search_custom_id' => $this->get('customSearchID'), 'search_context' => $this->get('context'));
             list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
             //set the saved search id.
             if (!$ssId) {
                 if ($savedSearchId) {
                     $this->set('ssID', $savedSearchId);
                 } else {
                     CRM_Core_Error::fatal();
                 }
             }
         }
         //get the base group for this mailing, CRM-3711
         $groups['base'] = array($values['baseGroup']);
         $values['includeGroups'][] = $smartGroupId;
     }
     foreach (array('name', 'group_id', 'search_id', 'search_args', 'campaign_id', 'dedupe_email') as $n) {
         if (CRM_Utils_Array::value($n, $values)) {
             $params[$n] = $values[$n];
         }
     }
     $qf_Group_submit = $this->controller->exportValue($this->_name, '_qf_Group_submit');
     $this->set('name', $params['name']);
     $inGroups = $values['includeGroups'];
     $outGroups = $values['excludeGroups'];
     $inMailings = $values['includeMailings'];
     $outMailings = $values['excludeMailings'];
     if (is_array($inGroups)) {
         foreach ($inGroups as $key => $id) {
             if ($id) {
                 $groups['include'][] = $id;
             }
         }
     }
     if (is_array($outGroups)) {
         foreach ($outGroups as $key => $id) {
             if ($id) {
                 $groups['exclude'][] = $id;
             }
         }
     }
     $mailings = array();
     if (is_array($inMailings)) {
         foreach ($inMailings as $key => $id) {
             if ($id) {
                 $mailings['include'][] = $id;
             }
         }
     }
     if (is_array($outMailings)) {
         foreach ($outMailings as $key => $id) {
             if ($id) {
                 $mailings['exclude'][] = $id;
             }
         }
     }
     $session = CRM_Core_Session::singleton();
     $params['groups'] = $groups;
     $params['mailings'] = $mailings;
     if ($this->get('mailing_id')) {
         $ids = array();
         // don't create a new mailing if already exists
         $ids['mailing_id'] = $this->get('mailing_id');
         $groupTableName = CRM_Contact_BAO_Group::getTableName();
         $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName();
         // delete previous includes/excludes, if mailing already existed
         foreach (array('groups', 'mailings') as $entity) {
             $mg = new CRM_Mailing_DAO_Group();
             $mg->mailing_id = $ids['mailing_id'];
             $mg->entity_table = $entity == 'groups' ? $groupTableName : $mailingTableName;
             $mg->find();
             while ($mg->fetch()) {
                 $mg->delete();
             }
         }
     } else {
         // new mailing, so lets set the created_id
         $session = CRM_Core_Session::singleton();
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     $mailing = CRM_Mailing_BAO_Mailing::create($params, $ids);
     $this->set('mailing_id', $mailing->id);
     $dedupeEmail = FALSE;
     if (isset($params['dedupe_email'])) {
         $dedupeEmail = $params['dedupe_email'];
     }
     // also compute the recipients and store them in the mailing recipients table
     CRM_Mailing_BAO_Mailing::getRecipients($mailing->id, $mailing->id, NULL, NULL, TRUE, $dedupeEmail);
     $count = CRM_Mailing_BAO_Recipients::mailingSize($mailing->id);
     $this->set('count', $count);
     $this->assign('count', $count);
     $this->set('groups', $groups);
     $this->set('mailings', $mailings);
     if ($qf_Group_submit) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         $ssID = $this->get('ssID');
         $context = $this->get('context');
         if ($ssID && $this->_searchBasedMailing) {
             if ($this->_action == CRM_Core_Action::BASIC) {
                 $fragment = 'search';
             } elseif ($this->_action == CRM_Core_Action::PROFILE) {
                 $fragment = 'search/builder';
             } elseif ($this->_action == CRM_Core_Action::ADVANCED) {
                 $fragment = 'search/advanced';
             } else {
                 $fragment = 'search/custom';
             }
             $context = $this->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}";
             $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
             if (CRM_Utils_Rule::qfKey($qfKey)) {
                 $urlParams .= "&qfKey={$qfKey}";
             }
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("Your mailing has been saved. You can continue later by clicking the 'Continue' action to resume working on it.<br /> From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             CRM_Core_Session::setStatus($status);
             //replace user context to search.
             $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams);
             return $this->controller->setDestination($url);
         } else {
             $status = ts("Your mailing has been saved. Click the 'Continue' action to resume working on it.");
             CRM_Core_Session::setStatus($status);
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             return $this->controller->setDestination($url);
         }
     }
 }
 /**
  * Process the mapped fields and map it into the uploaded file
  * preview the file and extract some summary statistics
  *
  * @return void
  * @access public
  */
 public function postProcessOld()
 {
     $doGeocodeAddress = $this->controller->exportValue('DataSource', 'doGeocodeAddress');
     $invalidRowCount = $this->get('invalidRowCount');
     $conflictRowCount = $this->get('conflictRowCount');
     $onDuplicate = $this->get('onDuplicate');
     $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName');
     $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc');
     $groups = $this->controller->exportValue($this->_name, 'groups');
     $allGroups = $this->get('groups');
     $newTagName = $this->controller->exportValue($this->_name, 'newTagName');
     $newTagDesc = $this->controller->exportValue($this->_name, 'newTagDesc');
     $tag = $this->controller->exportValue($this->_name, 'tag');
     $allTags = $this->get('tag');
     $mapper = $this->controller->exportValue('MapField', 'mapper');
     $mapperKeys = array();
     $mapperLocTypes = array();
     $mapperPhoneTypes = array();
     $mapperRelated = array();
     $mapperRelatedContactType = array();
     $mapperRelatedContactDetails = array();
     $mapperRelatedContactLocType = array();
     $mapperRelatedContactPhoneType = array();
     foreach ($mapper as $key => $value) {
         $mapperKeys[$key] = $mapper[$key][0];
         if (is_numeric($mapper[$key][1])) {
             $mapperLocTypes[$key] = $mapper[$key][1];
         } else {
             $mapperLocTypes[$key] = NULL;
         }
         if (CRM_Utils_Array::value($key, $mapperKeys) == 'phone') {
             $mapperPhoneTypes[$key] = $mapper[$key][2];
         } else {
             $mapperPhoneTypes[$key] = NULL;
         }
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType = new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(TRUE);
             $fieldName = "contact_type_{$second}";
             $mapperRelatedContactType[$key] = $relationType->{$fieldName};
             $mapperRelated[$key] = $mapper[$key][0];
             $mapperRelatedContactDetails[$key] = $mapper[$key][1];
             $mapperRelatedContactLocType[$key] = $mapper[$key][2];
             $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
         } else {
             $mapperRelated[$key] = NULL;
             $mapperRelatedContactType[$key] = NULL;
             $mapperRelatedContactDetails[$key] = NULL;
             $mapperRelatedContactLocType[$key] = NULL;
             $mapperRelatedContactPhoneType[$key] = NULL;
         }
     }
     $parser = new CRM_Contact_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType);
     $mapFields = $this->get('fields');
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     foreach ($mapper as $key => $value) {
         $header = array();
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType = new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(TRUE);
             $header[] = $relationType->name_a_b;
             $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
             if (isset($mapper[$key][2])) {
                 $header[] = $locationTypes[$mapper[$key][2]];
             }
             if (isset($mapper[$key][3])) {
                 $header[] = $phoneTypes[$mapper[$key][3]];
             }
         } else {
             if (isset($mapFields[$mapper[$key][0]])) {
                 $header[] = $mapFields[$mapper[$key][0]];
                 if (isset($mapper[$key][1])) {
                     $header[] = $locationTypes[$mapper[$key][1]];
                 }
                 if (isset($mapper[$key][2])) {
                     $header[] = $phoneTypes[$mapper[$key][2]];
                 }
             }
         }
         $mapperFields[] = implode(' - ', $header);
     }
     $tableName = $this->get('importTableName');
     //print "Running parser on table: $tableName<br/>";
     $parser->run($tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->get('contactType'), $this->get('primaryKeyName'), $this->get('statusFieldName'), $onDuplicate, $this->get('statusID'), $this->get('totalRowCount'), $doGeocodeAddress, CRM_Contact_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'), $this->get('dedupe'));
     // add the new contacts to selected groups
     $contactIds =& $parser->getImportedContacts();
     // add the new related contacts to selected groups
     $relatedContactIds =& $parser->getRelatedImportedContacts();
     $this->set('relatedCount', count($relatedContactIds));
     $newGroupId = NULL;
     //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
     if ($newGroupName) {
         /* Create a new group */
         $gParams = array('name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => TRUE);
         $group = CRM_Contact_BAO_Group::create($gParams);
         $groups[] = $newGroupId = $group->id;
     }
     if (is_array($groups)) {
         $groupAdditions = array();
         foreach ($groups as $groupId) {
             $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             if (!empty($relatedContactIds)) {
                 $addRelCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId);
             }
             $totalCount = $addCount[1] + $addRelCount[1];
             if ($groupId == $newGroupId) {
                 $name = $newGroupName;
                 $new = TRUE;
             } else {
                 $name = $allGroups[$groupId];
                 $new = FALSE;
             }
             $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2] + $addRelCount[2], 'new' => $new);
         }
         $this->set('groupAdditions', $groupAdditions);
     }
     $newTagId = NULL;
     if ($newTagName) {
         /* Create a new Tag */
         $tagParams = array('name' => $newTagName, 'title' => $newTagName, 'description' => $newTagDesc, 'is_active' => TRUE);
         $id = array();
         $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id);
         $tag[$addedTag->id] = 1;
     }
     //add Tag to Import
     if (is_array($tag)) {
         $tagAdditions = array();
         foreach ($tag as $tagId => $val) {
             $addTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId);
             if (!empty($relatedContactIds)) {
                 $addRelTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($relatedContactIds, $tagId);
             }
             $totalTagCount = $addTagCount[1] + $addRelTagCount[1];
             if ($tagId == $addedTag->id) {
                 $tagName = $newTagName;
                 $new = TRUE;
             } else {
                 $tagName = $allTags[$tagId];
                 $new = FALSE;
             }
             $tagAdditions[] = array('url' => CRM_Utils_System::url('civicrm/contact/search', 'reset=1&force=1&context=smog&id=' . $tagId), 'name' => $tagName, 'added' => $totalTagCount, 'notAdded' => $addTagCount[2] + $addRelTagCount[2], 'new' => $new);
         }
         $this->set('tagAdditions', $tagAdditions);
     }
     // add all the necessary variables to the form
     $parser->set($this, CRM_Import_Parser::MODE_IMPORT);
     // check if there is any error occured
     $errorStack = CRM_Core_Error::singleton();
     $errors = $errorStack->getErrors();
     $errorMessage = array();
     if (is_array($errors)) {
         foreach ($errors as $key => $value) {
             $errorMessage[] = $value['message'];
         }
         // there is no fileName since this is a sql import
         // so fudge it
         $config = CRM_Core_Config::singleton();
         $errorFile = $config->uploadDir . "sqlImport.error.log";
         if ($fd = fopen($errorFile, 'w')) {
             fwrite($fd, implode('\\n', $errorMessage));
         }
         fclose($fd);
         $this->set('errorFile', $errorFile);
         $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser';
         $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlparams));
         $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser';
         $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
         $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser';
         $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
     }
 }
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues();
     $groupOption = CRM_Utils_Array::value('group_option', $params, NULL);
     if ($groupOption) {
         $groupParams = array();
         $groupParams['title'] = $params['title'];
         $groupParams['description'] = $params['description'];
         $groupParams['visibility'] = "User and User Admin Only";
         if (array_key_exists('group_type', $params) && is_array($params['group_type'])) {
             $groupParams['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['group_type'])) . CRM_Core_DAO::VALUE_SEPARATOR;
         } else {
             $groupParams['group_type'] = '';
         }
         $groupParams['is_active'] = 1;
         $createdGroup = CRM_Contact_BAO_Group::create($groupParams);
         $groupID = $createdGroup->id;
         $groupName = $groupParams['title'];
     } else {
         $groupID = $params['group_id'];
         $group = CRM_Core_PseudoConstant::group();
         $groupName = $group[$groupID];
     }
     list($total, $added, $notAdded) = CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $groupID);
     $status = array(ts('%count contact added to group', array('count' => $added, 'plural' => '%count contacts added to group')));
     if ($notAdded) {
         $status[] = ts('%count contact was already in group', array('count' => $notAdded, 'plural' => '%count contacts were already in group'));
     }
     $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
     CRM_Core_Session::setStatus($status, ts('Added Contact to %1', array(1 => $groupName, 'count' => $added, 'plural' => 'Added Contacts to %1')), 'success', array('expires' => 0));
 }
 /**
  * Takes an associative array and creates / removes
  * contacts from the groups
  *
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $contactId
  *   Contact id.
  *
  * @param bool $visibility
  * @param string $method
  *
  * @return void
  */
 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin')
 {
     $contactIds = array();
     $contactIds[] = $contactId;
     //if $visibility is true we are coming in via profile mean $method = 'Web'
     $ignorePermission = FALSE;
     if ($visibility) {
         $ignorePermission = TRUE;
     }
     if ($contactId) {
         $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($contactId, 'Added', NULL, FALSE, $ignorePermission);
         if (is_array($contactGroupList)) {
             foreach ($contactGroupList as $key) {
                 $groupId = $key['group_id'];
                 $contactGroup[$groupId] = $groupId;
             }
         }
     }
     // get the list of all the groups
     $allGroup = CRM_Contact_BAO_GroupContact::getGroupList(0, $visibility);
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!is_array($params)) {
         $params = array();
     }
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!isset($contactGroup) || !is_array($contactGroup)) {
         $contactGroup = array();
     }
     // check which values has to be add/remove contact from group
     foreach ($allGroup as $key => $varValue) {
         if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
             // add contact to group
             CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $key, $method);
         } elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
             // remove contact from group
             CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $key, $method);
         }
     }
 }
 /**
  * Process the mapped fields and map it into the uploaded file
  * preview the file and extract some summary statistics
  *
  * @return void
  * @access public
  */
 function postProcess()
 {
     $fileName = $this->controller->exportValue('UploadFile', 'uploadFile');
     $skipColumnHeader = $this->controller->exportValue('UploadFile', 'skipColumnHeader');
     $invalidRowCount = $this->get('invalidRowCount');
     $conflictRowCount = $this->get('conflictRowCount');
     $onDuplicate = $this->get('onDuplicate');
     $newGroup = $this->controller->exportValue($this->_name, 'newGroup');
     $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName');
     $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc');
     $groups = $this->controller->exportValue($this->_name, 'groups');
     $allGroups = $this->get('groups');
     $tagForContact = $this->controller->exportValue($this->_name, 'tag');
     $allTags = $this->get('tag');
     $seperator = ',';
     $mapper = $this->controller->exportValue('MapField', 'mapper');
     $mapperKeys = array();
     $mapperLocTypes = array();
     $mapperPhoneTypes = array();
     $mapperRelated = array();
     $mapperRelatedContactType = array();
     $mapperRelatedContactDetails = array();
     $mapperRelatedContactLocType = array();
     $mapperRelatedContactPhoneType = array();
     foreach ($mapper as $key => $value) {
         $mapperKeys[$key] = $mapper[$key][0];
         if (is_numeric($mapper[$key][1])) {
             $mapperLocTypes[$key] = $mapper[$key][1];
         } else {
             $mapperLocTypes[$key] = null;
         }
         if (!is_numeric($mapper[$key][2])) {
             $mapperPhoneTypes[$key] = $mapper[$key][2];
         } else {
             $mapperPhoneTypes[$key] = null;
         }
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             eval('$mapperRelatedContactType[$key] = $relationType->contact_type_' . $second . ';');
             $mapperRelated[$key] = $mapper[$key][0];
             $mapperRelatedContactDetails[$key] = $mapper[$key][1];
             $mapperRelatedContactLocType[$key] = $mapper[$key][2];
             $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
         } else {
             $mapperRelated[$key] = null;
             $mapperRelatedContactType[$key] = null;
             $mapperRelatedContactDetails[$key] = null;
             $mapperRelatedContactLocType[$key] = null;
             $mapperRelatedContactPhoneType[$key] = null;
         }
     }
     $parser =& new CRM_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType);
     $mapFields = $this->get('fields');
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $phoneTypes = CRM_Core_SelectValues::phoneType();
     foreach ($mapper as $key => $value) {
         $header = array();
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             $header[] = $relationType->name_a_b;
             $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
             if (isset($mapper[$key][2])) {
                 $header[] = $locationTypes[$mapper[$key][2]];
             }
             if (isset($mapper[$key][3])) {
                 $header[] = $phoneTypes[$mapper[$key][3]];
             }
         } else {
             if (isset($mapFields[$mapper[$key][0]])) {
                 $header[] = $mapFields[$mapper[$key][0]];
                 if (isset($mapper[$key][1])) {
                     $header[] = $locationTypes[$mapper[$key][1]];
                 }
                 if (isset($mapper[$key][2])) {
                     $header[] = $phoneTypes[$mapper[$key][2]];
                 }
             }
         }
         $mapperFields[] = implode(' - ', $header);
     }
     $parser->run($fileName, $seperator, $mapperFields, $skipColumnHeader, CRM_IMPORT_PARSER_MODE_IMPORT, $this->get('contactType'), $onDuplicate);
     // add the new contacts to selected groups
     $contactIds =& $parser->getImportedContacts();
     // add the new related contacts to selected groups
     $relatedContactIds =& $parser->getRelatedImportedContacts();
     $this->set('relatedCount', count($relatedContactIds));
     $newGroupId = null;
     //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
     if ($newGroupName) {
         /* Create a new group */
         $gParams = array('domain_id' => CRM_Core_Config::domainID(), 'name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => true);
         $group =& CRM_Contact_BAO_Group::create($gParams);
         $groups[] = $newGroupId = $group->id;
     }
     if (is_array($groups)) {
         $groupAdditions = array();
         foreach ($groups as $groupId) {
             $addCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             if (!empty($relatedContactIds)) {
                 $addRelCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId);
             }
             $totalCount = $addCount[1] + $addRelCount[1];
             if ($groupId == $newGroupId) {
                 $name = $newGroupName;
                 $new = true;
             } else {
                 $name = $allGroups[$groupId];
                 $new = false;
             }
             $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2], 'new' => $new);
         }
         $this->set('groupAdditions', $groupAdditions);
     }
     if (is_array($tagForContact)) {
         $tagAddition = array();
         require_once "CRM/Core/BAO/EntityTag.php";
         foreach ($tagForContact as $tagId => $selected) {
             $taggedContacts = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId);
             $tagName = $allTags[$tagId];
             $tagAdditions[] = array('name' => $tagName, 'added' => $taggedContacts[1], 'notAdded' => $taggedContacts[2]);
         }
         $this->set('tagAdditions', $tagAdditions);
     }
     // add all the necessary variables to the form
     $parser->set($this, CRM_IMPORT_PARSER_MODE_IMPORT);
     // check if there is any error occured
     $errorStack =& CRM_Core_Error::singleton();
     $errors = $errorStack->getErrors();
     $errorMessage = array();
     $config =& CRM_Core_Config::singleton();
     if (is_array($errors)) {
         foreach ($errors as $key => $value) {
             $errorMessage[] = $value['message'];
         }
         $errorFile = $fileName . '.error.log';
         if ($fd = fopen($errorFile, 'w')) {
             fwrite($fd, implode('\\n', $errorMessage));
         }
         fclose($fd);
         $this->set('errorFile', $errorFile);
         $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=1'));
         $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=2'));
         $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=4'));
     }
 }
 function testRemoveContactFromGroupMarkedAsNoBulkEmails()
 {
     $no_bulk_emails_on_unsubscribe = CRM_Core_BAO_Setting::setItem(1, 'CiviMailchimp Preferences', 'mailchimp_no_bulk_emails_on_unsubscribe');
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     $contact = CRM_Contact_BAO_Contact::create($params);
     $mailchimp_sync_setting = CRM_CiviMailchimp_BAO_SyncSettingsTest::createTestGroupAndSyncSettings('Test group testRemoveContactFromGroupMarkedAsNoBulkEmails');
     // Test that the contact is in the group
     $contact_ids = array($contact->id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $mailchimp_sync_setting->civicrm_group_id);
     $contact_added_to_group = CRM_Contact_BAO_GroupContact::isContactInGroup($contact->id, $mailchimp_sync_setting->civicrm_group_id);
     $this->assertTrue($contact_added_to_group);
     // Test that the contact is removed from the group
     CRM_CiviMailchimp_Utils::removeContactFromGroup($contact, $mailchimp_sync_setting->mailchimp_list_id);
     $contact_added_to_group = CRM_Contact_BAO_GroupContact::isContactInGroup($contact->id, $mailchimp_sync_setting->civicrm_group_id);
     $this->assertFalse($contact_added_to_group);
     // Test that contact is marked as No Bulk Emails
     $updated_contact = CRM_CiviMailchimp_Utils::getContactById($contact->id);
     $this->assertEquals(1, $updated_contact->is_opt_out);
 }
 static function manageCiviCRMGroupSubcription($contactID = array(), $requestData, $action)
 {
     CRM_Mailchimp_Utils::checkDebug('Start- CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $contactID= ', $contactID);
     CRM_Mailchimp_Utils::checkDebug('Start- CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $requestData= ', $requestData);
     CRM_Mailchimp_Utils::checkDebug('Start- CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $requestType= ', $action);
     if (empty($contactID) || empty($requestData['list_id']) || empty($action)) {
         return NULL;
     }
     $listID = $requestData['list_id'];
     $groupContactRemoves = $groupContactAdditions = array();
     // Deal with subscribe/unsubscribe.
     // We need the CiviCRM membership group for this list.
     $groups = CRM_Mailchimp_Utils::getGroupsToSync(array(), $listID, $membership_only = TRUE);
     $allGroups = CRM_Mailchimp_Utils::getGroupsToSync(array(), $listID, $membership_only = FALSE);
     if (!$groups) {
         // This list is not mapped to a group in CiviCRM.
         return NULL;
     }
     $_ = array_keys($groups);
     $membershipGroupID = $_[0];
     if ($action == 'subscribe') {
         $groupContactAdditions[$membershipGroupID][] = $contactID;
     } elseif ($action == 'unsubscribe') {
         $groupContactRemoves[$membershipGroupID][] = $contactID;
         $mcGroupings = array();
         foreach (empty($requestData['merges']['GROUPINGS']) ? array() : $requestData['merges']['GROUPINGS'] as $grouping) {
             foreach (explode(', ', $grouping['groups']) as $group) {
                 $mcGroupings[$grouping['id']][$group] = 1;
             }
         }
         foreach ($allGroups as $groupID => $details) {
             if ($groupID != $membershipGroupID && $details['is_mc_update_grouping']) {
                 if (!empty($mcGroupings[$details['grouping_id']][$details['group_name']])) {
                     $groupContactRemoves[$groupID][] = $contactID;
                 }
             }
         }
     }
     // Now deal with all the groupings that are mapped to CiviCRM groups for this list
     // and that have the allow MC updates flag set.
     /* Sample groupings from MC:
      *
      *     [GROUPINGS] => Array(
      *       [0] => Array(
      *           [id] => 11365
      *           [name] => CiviCRM
      *           [groups] => special
      *       ))
      * Re-map to mcGroupings[grouping_id][group_name] = 1;
      */
     $mcGroupings = array();
     foreach (empty($requestData['merges']['GROUPINGS']) ? array() : $requestData['merges']['GROUPINGS'] as $grouping) {
         foreach (explode(', ', $grouping['groups']) as $group) {
             $mcGroupings[$grouping['id']][$group] = 1;
         }
     }
     $groups = CRM_Mailchimp_Utils::getGroupsToSync(array(), $listID, $membership_only = FALSE);
     CRM_Mailchimp_Utils::checkDebug('Middle- CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $groups ', $groups);
     CRM_Mailchimp_Utils::checkDebug('Middle- CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $mcGroupings ', $mcGroupings);
     foreach ($groups as $groupID => $details) {
         if ($groupID != $membershipGroupID && $details['is_mc_update_grouping']) {
             // This is a group we allow updates for.
             if (empty($mcGroupings[$details['grouping_id']][$details['group_name']])) {
                 $groupContactRemoves[$groupID][] = $contactID;
             } else {
                 $groupContactAdditions[$groupID][] = $contactID;
             }
         }
     }
     // Add contacts to groups, if anything to do.
     foreach ($groupContactAdditions as $groupID => $contactIDs) {
         CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID, 'Admin', 'Added');
     }
     // Remove contacts from groups, if anything to do.
     foreach ($groupContactRemoves as $groupID => $contactIDs) {
         CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIDs, $groupID, 'Admin', 'Removed');
     }
     CRM_Mailchimp_Utils::checkDebug('End - CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $groupContactRemoves ', $groupContactRemoves);
     CRM_Mailchimp_Utils::checkDebug('End - CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $groupContactAdditions ', $groupContactAdditions);
     CRM_Mailchimp_Utils::checkDebug('End - CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $contactID= ', $contactID);
     CRM_Mailchimp_Utils::checkDebug('End - CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $requestData= ', $requestData);
     CRM_Mailchimp_Utils::checkDebug('End - CRM_Mailchimp_Page_WebHook manageCiviCRMGroupSubcription $requestType= ', $action);
 }