/** * Browse all saved searches. * * @return mixed * content of the parents run method */ public function browse() { $rows = array(); $savedSearch = new CRM_Contact_DAO_SavedSearch(); $savedSearch->is_active = 1; $savedSearch->selectAdd(); $savedSearch->selectAdd('id, form_values'); $savedSearch->find(); $properties = array('id', 'name', 'description'); while ($savedSearch->fetch()) { // get name and description from group object $group = new CRM_Contact_DAO_Group(); $group->saved_search_id = $savedSearch->id; if ($group->find(TRUE)) { $permissions = CRM_Group_Page_Group::checkPermission($group->id, $group->title); if (!CRM_Utils_System::isNull($permissions)) { $row = array(); $row['name'] = $group->title; $row['description'] = $group->description; $row['id'] = $savedSearch->id; $formValues = unserialize($savedSearch->form_values); $query = new CRM_Contact_BAO_Query($formValues); $row['query_detail'] = $query->qill(); $action = array_sum(array_keys(self::links())); $action = $action & CRM_Core_Action::mask($permissions); $row['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $row['id']), ts('more'), FALSE, 'savedSearch.manage.action', 'SavedSearch', $row['id']); $rows[] = $row; } } } $this->assign('rows', $rows); return parent::run(); }
/** * 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; }
/** * Subscribe from mailing group * * @param array $params Associative array of property * name/value pairs to insert in new 'survey' * * @throws API_Exception * @return array api result array * {@getfields mailing_event_subscribe_create} * @access public */ function civicrm_api3_mailing_event_subscribe_create($params) { $email = $params['email']; $group_id = $params['group_id']; $contact_id = CRM_Utils_Array::value('contact_id', $params); $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->id = (int) $group_id; if (!$group->find(TRUE)) { throw new API_Exception('Invalid Group id'); } $subscribe = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $email, $contact_id); if ($subscribe !== NULL) { /* Ask the contact for confirmation */ $subscribe->send_confirm_request($email); $values = array(); $values[$subscribe->id]['contact_id'] = $subscribe->contact_id; $values[$subscribe->id]['subscribe_id'] = $subscribe->id; $values[$subscribe->id]['hash'] = $subscribe->hash; return civicrm_api3_create_success($values); } return civicrm_api3_create_error('Subscription failed'); }
/** * Returns array of group object(s) matching a set of one or Group properties. * * @param array $params * Limits the set of groups returned. * @param array $returnProperties * Which properties should be included in the returned group objects. * (member_count should be last element.) * @param string $sort * @param int $offset * @param int $rowCount * * @return array * Array of group objects. * * * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and * add in essential fields (e.g. id). This should follow a regular pattern like the others */ public static function getGroups($params = NULL, $returnProperties = NULL, $sort = NULL, $offset = NULL, $rowCount = NULL) { $dao = new CRM_Contact_DAO_Group(); if (!isset($params['is_active'])) { $dao->is_active = 1; } if ($params) { foreach ($params as $k => $v) { if ($k == 'name' || $k == 'title') { $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO::escapeString($v) . '"'); } elseif ($k == 'group_type') { foreach ((array) $v as $type) { $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . (int) $type . CRM_Core_DAO::VALUE_SEPARATOR . "%'"); } } elseif (is_array($v)) { foreach ($v as &$num) { $num = (int) $num; } $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')'); } else { $dao->{$k} = $v; } } } if ($offset || $rowCount) { $offset = $offset > 0 ? $offset : 0; $rowCount = $rowCount > 0 ? $rowCount : 25; $dao->limit($offset, $rowCount); } if ($sort) { $dao->orderBy($sort); } // return only specific fields if returnproperties are sent if (!empty($returnProperties)) { $dao->selectAdd(); $dao->selectAdd(implode(',', $returnProperties)); } $dao->find(); $flag = $returnProperties && in_array('member_count', $returnProperties) ? 1 : 0; $groups = array(); while ($dao->fetch()) { $group = new CRM_Contact_DAO_Group(); if ($flag) { $dao->member_count = CRM_Contact_BAO_Group::memberCount($dao->id); } $groups[] = clone $dao; } return $groups; }
function from() { //define table name $randomNum = md5(uniqid()); $this->_tableName = "civicrm_temp_custom_{$randomNum}"; //block for Group search $smartGroup = array(); if ($this->_groups || $this->_allSearch) { require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); while ($group->fetch()) { $allGroups[] = $group->id; if ($group->saved_search_id) { $smartGroup[$group->saved_search_id] = $group->id; } } $includedGroups = implode(',', $allGroups); if (!empty($this->_includeGroups)) { $iGroups = implode(',', $this->_includeGroups); } else { //if no group selected search for all groups $iGroups = null; } if (is_array($this->_excludeGroups)) { $xGroups = implode(',', $this->_excludeGroups); } else { $xGroups = 0; } $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql); //used only when exclude group is selected if ($xGroups != 0) { $excludeGroup = "INSERT INTO Xg_{$this->_tableName} ( contact_id )\n SELECT DISTINCT civicrm_group_contact.contact_id\n FROM civicrm_group_contact, civicrm_contact \n WHERE \n civicrm_contact.id = civicrm_group_contact.contact_id AND \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN( {$xGroups})"; CRM_Core_DAO::executeQuery($excludeGroup); //search for smart group contacts foreach ($this->_excludeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql = $smartSql . " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact \n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery); } } } $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName} ( id int PRIMARY KEY AUTO_INCREMENT,\n contact_id int,\n group_names varchar(64)) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql); if ($iGroups) { $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n SELECT civicrm_contact.id as contact_id, civicrm_group.title as group_name\n FROM civicrm_contact\n INNER JOIN civicrm_group_contact\n ON civicrm_group_contact.contact_id = civicrm_contact.id\n LEFT JOIN civicrm_group\n ON civicrm_group_contact.group_id = civicrm_group.id"; } else { $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n SELECT civicrm_contact.id as contact_id, ''\n FROM civicrm_contact"; } //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " LEFT JOIN Xg_{$this->_tableName}\n ON civicrm_contact.id = Xg_{$this->_tableName}.contact_id"; } if ($iGroups) { $includeGroup .= " WHERE \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN({$iGroups})"; } else { $includeGroup .= " WHERE ( 1 ) "; } //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null"; } CRM_Core_DAO::executeQuery($includeGroup); //search for smart group contacts foreach ($this->_includeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql .= " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact\n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; //used only when exclude group is selected if ($xGroups != 0) { $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM Xg_{$this->_tableName})"; } $smartGroupQuery = " INSERT IGNORE INTO Ig_{$this->_tableName}(contact_id) \n {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery); $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName}\n SET group_names = (SELECT title FROM civicrm_group\n WHERE civicrm_group.id = {$values})\n WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL \n AND Ig_{$this->_tableName}.group_names IS NULL"; CRM_Core_DAO::executeQuery($insertGroupNameQuery); } } } //group contact search end here; //block for Tags search if ($this->_tags || $this->_allSearch) { //find all tags require_once 'CRM/Core/DAO/Tag.php'; $tag = new CRM_Core_DAO_Tag(); $tag->is_active = 1; $tag->find(); while ($tag->fetch()) { $allTags[] = $tag->id; } $includedTags = implode(',', $allTags); if (!empty($this->_includeTags)) { $iTags = implode(',', $this->_includeTags); } else { //if no group selected search for all groups $iTags = null; } if (is_array($this->_excludeTags)) { $xTags = implode(',', $this->_excludeTags); } else { $xTags = 0; } $sql = "CREATE TEMPORARY TABLE Xt_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql); //used only when exclude tag is selected if ($xTags != 0) { $excludeTag = "INSERT INTO Xt_{$this->_tableName} ( contact_id )\n SELECT DISTINCT civicrm_entity_tag.entity_id\n FROM civicrm_entity_tag, civicrm_contact \n WHERE \n civicrm_entity_tag.entity_table = 'civicrm_contact' AND\n civicrm_contact.id = civicrm_entity_tag.entity_id AND \n civicrm_entity_tag.tag_id IN( {$xTags})"; CRM_Core_DAO::executeQuery($excludeTag); } $sql = "CREATE TEMPORARY TABLE It_{$this->_tableName} ( id int PRIMARY KEY AUTO_INCREMENT,\n contact_id int,\n tag_names varchar(64)) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql); if ($iTags) { $includeTag = "INSERT INTO It_{$this->_tableName} (contact_id, tag_names)\n SELECT civicrm_contact.id as contact_id, civicrm_tag.name as tag_name\n FROM civicrm_contact\n INNER JOIN civicrm_entity_tag\n ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND\n civicrm_entity_tag.entity_id = civicrm_contact.id )\n LEFT JOIN civicrm_tag\n ON civicrm_entity_tag.tag_id = civicrm_tag.id"; } else { $includeTag = "INSERT INTO It_{$this->_tableName} (contact_id, tag_names)\n SELECT civicrm_contact.id as contact_id, ''\n FROM civicrm_contact"; } //used only when exclude tag is selected if ($xTags != 0) { $includeTag .= " LEFT JOIN Xt_{$this->_tableName}\n ON civicrm_contact.id = Xt_{$this->_tableName}.contact_id"; } if ($iTags) { $includeTag .= " WHERE civicrm_entity_tag.tag_id IN({$iTags})"; } else { $includeTag .= " WHERE ( 1 ) "; } //used only when exclude tag is selected if ($xTags != 0) { $includeTag .= " AND Xt_{$this->_tableName}.contact_id IS null"; } CRM_Core_DAO::executeQuery($includeTag); } $from = " FROM civicrm_contact contact_a"; /* * check the situation and set booleans */ if ($iGroups != 0) { $iG = true; } else { $iG = false; } if ($iTags != 0) { $iT = true; } else { $iT = false; } if ($xGroups != 0) { $xG = true; } else { $xG = false; } if ($xTags != 0) { $xT = true; } else { $xT = false; } if (!$this->_groups || !$this->_tags) { $this->_andOr = 1; } /* * Set from statement depending on array sel */ if ($iG && $iT && $xG && $xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " INNER JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL )\n AND contact_a.id NOT IN(SELECT contact_id FROM Xg_{$this->_tableName})\n AND contact_a.id NOT IN(SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $from .= " LEFT JOIN Xg_{$this->_tableName} temptable3 ON (contact_a.id = temptable3.contact_id)"; $from .= " LEFT JOIN Xt_{$this->_tableName} temptable4 ON (contact_a.id = temptable4.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL OR\n temptable3.contact_id IS NOT NULL OR temptable4.contact_id IS NOT NULL)"; } } if ($iG && $iT && $xG && !$xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " INNER JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL )\n AND contact_a.id NOT IN(SELECT contact_id FROM Xg_{$this->_tableName})"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $from .= " LEFT JOIN Xg_{$this->_tableName} temptable3 ON (contact_a.id = temptable3.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL OR\n temptable3.contact_id IS NOT NULL)"; } } if ($iG && $iT && !$xG && $xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " INNER JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL )\n AND contact_a.id NOT IN(SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $from .= " LEFT JOIN Xt_{$this->_tableName} temptable3 ON (contact_a.id = temptable3.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL OR\n temptable3.contact_id IS NOT NULL)"; } } if ($iG && $iT && !$xG && !$xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " INNER JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL )"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL)"; } } if ($iG && !$iT && $xG && $xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xg_{$this->_tableName}) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xg_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $from .= " LEFT JOIN Xt_{$this->_tableName} temptable3 ON (contact_a.id = temptable3.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL OR\n temptable3.contact_id IS NOT NULL)"; } } if ($iG && !$iT && $xG && !$xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xg_{$this->_tableName})"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xg_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL)"; } } if ($iG && !$iT && !$xG && $xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xt_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL)"; } } if ($iG && !$iT && !$xG && !$xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL)"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL)"; } } if (!$iG && $iT && $xG && $xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xg_{$this->_tableName}) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xg_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $from .= " LEFT JOIN Xt_{$this->_tableName} temptable3 ON (contact_a.id = temptable3.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL OR\n temptable3.contact_id IS NOT NULL)"; } } if (!$iG && $iT && $xG && !$xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xg_{$this->_tableName})"; } else { $from .= " LEFT JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xg_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL)"; } } if (!$iG && $iT && !$xG && $xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL) AND contact_a.id NOT IN(\n SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xt_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL)"; } } if (!$iG && $iT && !$xG && !$xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL)"; } else { $from .= " LEFT JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL)"; } } if (!$iG && !$iT && $xG && $xT) { if ($this->_andOr == 1) { $this->_where = "contact_a.id NOT IN(SELECT contact_id FROM Xg_{$this->_tableName})\n AND contact_a.id NOT IN(SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN Xg_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xt_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL)"; } } if (!$iG && !$iT && !$xG && $xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN It_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "contact_a.id NOT IN(SELECT contact_id FROM Xt_{$this->_tableName})"; } else { $from .= " LEFT JOIN Xt_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN It_{$this->_tableName} temptable2 ON (contact_a.id = temptable2.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL OR temptable2.contact_id IS NOT NULL)"; } } if (!$iG && !$iT && $xG && !$xT) { if ($this->_andOr == 1) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "contact_a.id NOT IN(SELECT contact_id FROM Xg_{$this->_tableName})"; } else { $from .= " LEFT JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $from .= " LEFT JOIN Xg_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; $this->_where = "( temptable1.contact_id IS NOT NULL)"; } } $from .= " LEFT JOIN civicrm_email ON ( contact_a.id = civicrm_email.contact_id AND ( civicrm_email.is_primary = 1 OR civicrm_email.is_bulkmail = 1 ) )"; return $from; }
/** * Get group clause for this user. The group Clause filters the * list of groups that the user is permitted to see in a group listing. * For example it will filter both the list on the 'Manage Groups' page * and on the contact 'Groups' tab * * the aclGroup hook & configured ACLs contribute to this data. * If the contact is allowed to see all contacts the function will return ( 1 ) * * @todo the history of this function is that there was some confusion as to * whether it was filtering contacts or groups & some cruft may remain * * @param int $type * The type of permission needed. * @param array $tables * (reference) add the tables that are needed for the select clause. * @param array $whereTables * (reference) add the tables that are needed for the where clause. * * @return string * the clause to add to the query retrieving viewable groups */ public function groupClause($type, &$tables, &$whereTables) { if (!isset($this->_viewPermissionedGroups)) { $this->group(); } // we basically get all the groups here $groupKey = 'all'; if ($type == CRM_Core_Permission::EDIT) { if ($this->_editAdminUser) { $clause = ' ( 1 ) '; } elseif (empty($this->_editPermissionedGroups[$groupKey])) { $clause = ' ( 0 ) '; } else { $clauses = array(); $groups = implode(', ', $this->_editPermissionedGroups[$groupKey]); $clauses[] = ' ( civicrm_group_contact.group_id IN ( ' . implode(', ', array_keys($this->_editPermissionedGroups[$groupKey])) . " ) AND civicrm_group_contact.status = 'Added' ) "; $tables['civicrm_group_contact'] = 1; $whereTables['civicrm_group_contact'] = 1; // foreach group that is potentially a saved search, add the saved search clause foreach (array_keys($this->_editPermissionedGroups[$groupKey]) as $id) { $group = new CRM_Contact_DAO_Group(); $group->id = $id; if ($group->find(TRUE) && $group->saved_search_id) { $clause = CRM_Contact_BAO_SavedSearch::whereClause($group->saved_search_id, $tables, $whereTables); if (trim($clause)) { $clauses[] = $clause; } } } $clause = ' ( ' . implode(' OR ', $clauses) . ' ) '; } } else { if ($this->_viewAdminUser) { $clause = ' ( 1 ) '; } elseif (empty($this->_viewPermissionedGroups[$groupKey])) { $clause = ' ( 0 ) '; } else { $clauses = array(); $groups = implode(', ', $this->_viewPermissionedGroups[$groupKey]); $clauses[] = ' civicrm_group.id IN (' . implode(', ', array_keys($this->_viewPermissionedGroups[$groupKey])) . " ) "; $tables['civicrm_group'] = 1; $whereTables['civicrm_group'] = 1; $clause = ' ( ' . implode(' OR ', $clauses) . ' ) '; } } return $clause; }
/** * given an id, get the name of the saved search * * @param int $id the id of the saved search * * @return string the name of the saved search * @access public * @static */ static function getName($id, $value = 'name') { require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->saved_search_id = $id; if ($group->find(true)) { return $group->{$value}; } return null; }
function engageWhereGroupClause($clause) { $smartGroupQuery = ""; require_once 'CRM/Contact/DAO/Group.php'; require_once 'CRM/Contact/BAO/SavedSearch.php'; $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); while ($group->fetch()) { if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) { $smartGroups[] = $group->id; } } if (!empty($smartGroups)) { $smartGroups = implode(',', $smartGroups); $smartGroupQuery = " UNION DISTINCT \n SELECT DISTINCT smartgroup_contact.contact_id \n FROM civicrm_group_contact_cache smartgroup_contact \n WHERE smartgroup_contact.group_id IN ({$smartGroups}) "; } if ($this->_params['gid_op'] == 'in') { return " {$this->_aliases['civicrm_contact']}.id IN ( \n SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id \n FROM civicrm_group_contact {$this->_aliases['civicrm_group']}\n WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added' \n {$smartGroupQuery} ) "; } elseif ($this->_params['gid_op'] == 'mand') { $query = " {$this->_aliases['civicrm_contact']}.id IN ( \n SELECT DISTINCT {$this->_aliases['civicrm_group']}1.contact_id \n FROM civicrm_group_contact {$this->_aliases['civicrm_group']}1\n"; for ($i = 2; $i <= count($this->_params['gid_value']); $i++) { $j = $i - 1; $status[] = "{$this->_aliases['civicrm_group']}{$i}.group_id != {$this->_aliases['civicrm_group']}{$j}.group_id"; $query .= " INNER JOIN civicrm_group_contact {$this->_aliases['civicrm_group']}{$i} \n ON {$this->_aliases['civicrm_group']}{$i}.contact_id = {$this->_aliases['civicrm_group']}{$j}.contact_id AND " . implode(" AND ", $status) . "\n"; } $query .= " WHERE "; for ($i = 1; $i <= count($this->_params['gid_value']); $i++) { $query .= $i > 1 ? " AND " : ""; $query .= " {$this->_aliases['civicrm_group']}{$i}.group_id IN ( '" . implode("' , '", $this->_params['gid_value']) . "') AND {$this->_aliases['civicrm_group']}{$i}.status = 'Added'\n"; } $query .= " {$smartGroupQuery} ) "; return $query; } }
/** * 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 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) { $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); } $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; }
/** * Get group clause for this user * * @param int $type the type of permission needed * @param array $tables (reference ) add the tables that are needed for the select clause * @param array $whereTables (reference ) add the tables that are needed for the where clause * * @return string the group where clause for this user * @access public */ public static function groupClause($type, &$tables, &$whereTables) { if (!isset(self::$_viewPermissionedGroups)) { self::group(); } if ($type == CRM_Core_Permission::EDIT) { if (self::$_editAdminUser) { $clause = ' ( 1 ) '; } else { if (empty(self::$_editPermissionedGroups)) { $clause = ' ( 0 ) '; } else { $clauses = array(); $groups = implode(', ', self::$_editPermissionedGroups); $clauses[] = ' ( civicrm_group_contact.group_id IN ( ' . implode(', ', array_keys(self::$_editPermissionedGroups)) . " ) AND civicrm_group_contact.status = 'Added' ) "; $tables['civicrm_group_contact'] = 1; $whereTables['civicrm_group_contact'] = 1; // foreach group that is potentially a saved search, add the saved search clause foreach (array_keys(self::$_editPermissionedGroups) as $id) { $group = new CRM_Contact_DAO_Group(); $group->id = $id; if ($group->find(true) && $group->saved_search_id) { require_once 'CRM/Contact/BAO/SavedSearch.php'; $clause = CRM_Contact_BAO_SavedSearch::whereClause($group->saved_search_id, $tables, $whereTables); if (trim($clause)) { $clauses[] = $clause; } } } $clause = ' ( ' . implode(' OR ', $clauses) . ' ) '; } } } else { if (self::$_viewAdminUser) { $clause = ' ( 1 ) '; } else { if (empty(self::$_viewPermissionedGroups)) { $clause = ' ( 0 ) '; } else { $clauses = array(); $groups = implode(', ', self::$_viewPermissionedGroups); $clauses[] = ' ( civicrm_group_contact.group_id IN (' . implode(', ', array_keys(self::$_viewPermissionedGroups)) . " ) AND civicrm_group_contact.status = 'Added' ) "; $tables['civicrm_group_contact'] = 1; $whereTables['civicrm_group_contact'] = 1; // foreach group that is potentially a saved search, add the saved search clause foreach (array_keys(self::$_viewPermissionedGroups) as $id) { $group = new CRM_Contact_DAO_Group(); $group->id = $id; if ($group->find(true) && $group->saved_search_id) { require_once 'CRM/Contact/BAO/SavedSearch.php'; $clause = CRM_Contact_BAO_SavedSearch::whereClause($group->saved_search_id, $tables, $whereTables); if (trim($clause)) { $clauses[] = $clause; } } } $clause = ' ( ' . implode(' OR ', $clauses) . ' ) '; } } } return $clause; }
function from() { //define table name $randomNum = md5(uniqid()); $this->_tableName = "civicrm_temp_custom_{$randomNum}"; //block for Group search $smartGroup = array(); $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); while ($group->fetch()) { $allGroups[] = $group->id; if ($group->saved_search_id) { $smartGroup[$group->saved_search_id] = $group->id; } } $includedGroups = implode(',', $allGroups); if (!empty($this->_includeGroups)) { $iGroups = implode(',', $this->_includeGroups); } else { //if no group selected search for all groups $iGroups = $includedGroups; } if (is_array($this->_excludeGroups)) { $xGroups = implode(',', $this->_excludeGroups); } else { $xGroups = 0; } $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}"; CRM_Core_DAO::executeQuery($sql); $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql); //used only when exclude group is selected if ($xGroups != 0) { $excludeGroup = "INSERT INTO Xg_{$this->_tableName} ( contact_id )\n SELECT DISTINCT civicrm_group_contact.contact_id\n FROM civicrm_group_contact\n WHERE \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN ( {$xGroups} )"; CRM_Core_DAO::executeQuery($excludeGroup); //search for smart group contacts foreach ($this->_excludeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql = $smartSql . " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact \n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery); } } } $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}"; CRM_Core_DAO::executeQuery($sql); $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName}\n ( id int PRIMARY KEY AUTO_INCREMENT,\n contact_id int,\n group_names varchar(64)) ENGINE=HEAP"; if ($this->_debug > 0) { print "-- Include groups query: <pre>"; print "{$sql};"; print "</pre>"; } CRM_Core_DAO::executeQuery($sql); $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n SELECT civicrm_group_contact.contact_id, civicrm_group.name as group_name\n FROM civicrm_group_contact\n LEFT JOIN civicrm_group\n ON civicrm_group_contact.group_id = civicrm_group.id"; //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " LEFT JOIN Xg_{$this->_tableName}\n ON civicrm_group_contact.contact_id = Xg_{$this->_tableName}.contact_id"; } $includeGroup .= " WHERE \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN({$iGroups})"; //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null"; } if ($this->_debug > 0) { print "-- Include groups query: <pre>"; print "{$includeGroup};"; print "</pre>"; } CRM_Core_DAO::executeQuery($includeGroup); //search for smart group contacts foreach ($this->_includeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql .= " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact\n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; //used only when exclude group is selected if ($xGroups != 0) { $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM Xg_{$this->_tableName})"; } $smartGroupQuery = " INSERT IGNORE INTO Ig_{$this->_tableName}(contact_id) \n {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery); $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName}\n SET group_names = (SELECT title FROM civicrm_group\n WHERE civicrm_group.id = {$values})\n WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL \n AND Ig_{$this->_tableName}.group_names IS NULL"; CRM_Core_DAO::executeQuery($insertGroupNameQuery); } } $from = "FROM civicrm_contact contact_a"; $fromTail = "LEFT JOIN civicrm_email ON ( contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1 )"; $fromTail .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; // now create a temp table to store the randomized contacts $sql = "DROP TEMPORARY TABLE IF EXISTS random_{$this->_tableName}"; CRM_Core_DAO::executeQuery($sql); $sql = "CREATE TEMPORARY TABLE random_{$this->_tableName} ( id int primary key ) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql); if (substr($this->_segmentSize, -1) == '%') { $countSql = "SELECT DISTINCT contact_a.id {$from} {$fromTail}\n WHERE " . $this->where(); $dao = CRM_Core_DAO::executeQuery($countSql); $totalSize = $dao->N; $multiplier = substr($this->_segmentSize, 0, strlen($this->_segmentSize) - 1); $multiplier /= 100; //CRM_Core_Error::debug( "Total size: $totalSize<br/>Multiplier: $multiplier<br/>"); $this->_segmentSize = round($totalSize * $multiplier); } $sql = "INSERT INTO random_{$this->_tableName} ( id )\n SELECT DISTINCT contact_a.id {$from} {$fromTail}\n WHERE " . $this->where() . "\n ORDER BY RAND()\n LIMIT {$this->_segmentSize}"; CRM_Core_DAO::executeQuery($sql); $from = "FROM random_{$this->_tableName} random"; $from .= " INNER JOIN civicrm_contact contact_a ON random.id = contact_a.id"; $from .= " {$fromTail}"; return $from; }
/** * Returns array of group object(s) matching a set of one or Group properties. * * @param array $param Array of one or more valid property_name=>value pairs. * Limits the set of groups returned. * @param array $returnProperties Which properties should be included in the returned group objects. * (member_count should be last element.) * * @return An array of group objects. * * @access public */ static function getGroups($params = NULL, $returnProperties = NULL) { $dao = new CRM_Contact_DAO_Group(); $dao->is_active = 1; if ($params) { foreach ($params as $k => $v) { if ($k == 'name' || $k == 'title') { $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO::escapeString($v) . '"'); } elseif (is_array($v)) { $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')'); } else { $dao->{$k} = $v; } } } // return only specific fields if returnproperties are sent if (!empty($returnProperties)) { $dao->selectAdd(); $dao->selectAdd(implode(',', $returnProperties)); } $dao->find(); $flag = $returnProperties && in_array('member_count', $returnProperties) ? 1 : 0; $groups = array(); while ($dao->fetch()) { $group = new CRM_Contact_DAO_Group(); if ($flag) { $dao->member_count = CRM_Contact_BAO_Group::memberCount($dao->id); } $groups[] = clone $dao; } return $groups; }
/** * Function to call syncontacts with smart groups and static groups xxx delete * * Returns object that can iterate over a slice of the live contacts in given group. */ static function getGroupMemberships($groupIDs) { CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Utils getGroupMemberships $groupIDs', $groupIDs); $group = new CRM_Contact_DAO_Group(); $group->id = $groupID; $group->find(); if ($group->fetch()) { //Check smart groups if ($group->saved_search_id) { $groupContactCache = new CRM_Contact_BAO_GroupContactCache(); $groupContactCache->group_id = $groupID; if ($start !== null) { $groupContactCache->limit($start, CRM_Mailchimp_Form_Sync::BATCH_COUNT); } $groupContactCache->find(); return $groupContactCache; } else { $groupContact = new CRM_Contact_BAO_GroupContact(); $groupContact->group_id = $groupID; $groupContact->whereAdd("status = 'Added'"); if ($start !== null) { $groupContact->limit($start, CRM_Mailchimp_Form_Sync::BATCH_COUNT); } $groupContact->find(); return $groupContact; } } CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Utils getGroupMemberships $groupIDs', $groupIDs); return FALSE; }
/** * Handle a subscription event * * @param array $params * * @return array */ function civicrm_mailer_event_subscribe($params) { $errors = _civicrm_mailer_check_params($params, array('email', 'group_id')); if (!empty($errors)) { return $errors; } $email = $params['email']; $group_id = $params['group_id']; $contact_id = CRM_Utils_Array::value('contact_id', $params); $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->id = (int) $group_id; if (!$group->find(TRUE)) { return civicrm_create_error(ts('Invalid Group id')); } $subscribe = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $email, $contact_id); if ($subscribe !== NULL) { /* Ask the contact for confirmation */ $subscribe->send_confirm_request($email); $values = array(); $values['contact_id'] = $subscribe->contact_id; $values['subscribe_id'] = $subscribe->id; $values['hash'] = $subscribe->hash; $values['is_error'] = 0; return $values; } return civicrm_create_error(ts('Subscription failed')); }
/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { require_once 'CRM/Mailing/Event/BAO/Subscribe.php'; $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return false; } require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $ce = new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); require_once 'CRM/Contact/BAO/GroupContact.php'; CRM_Contact_BAO_GroupContact::updateGroupMembershipStatus($contact_id, $se->group_id, 'Email', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); require_once 'CRM/Contact/BAO/Contact/Location.php'; list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(true); require_once 'CRM/Mailing/BAO/Component.php'; $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(true); require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } require_once 'CRM/Mailing/BAO/Mailing.php'; $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, true); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, false); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); require_once 'CRM/Mailing/BAO/Mailing.php'; PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($email, $h, $b); CRM_Core_Error::setCallback(); } return $group->title; }
function whereGroupClause($clause) { $smartGroupQuery = ""; require_once 'CRM/Contact/DAO/Group.php'; require_once 'CRM/Contact/BAO/SavedSearch.php'; $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); while ($group->fetch()) { if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) { $smartGroups[] = $group->id; } } require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::check($smartGroups); if (!empty($smartGroups)) { $smartGroups = implode(',', $smartGroups); $smartGroupQuery = " UNION DISTINCT \n SELECT DISTINCT smartgroup_contact.contact_id \n FROM civicrm_group_contact_cache smartgroup_contact \n WHERE smartgroup_contact.group_id IN ({$smartGroups}) "; } return " {$this->_aliases['civicrm_contact']}.id IN ( \n SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id \n FROM civicrm_group_contact {$this->_aliases['civicrm_group']}\n WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added' \n {$smartGroupQuery} ) "; }
/** * Build where clause for groups. * * @param string $field * @param mixed $value * @param string $op * * @return string */ public function whereGroupClause($field, $value, $op) { $smartGroupQuery = ""; $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); $smartGroups = array(); while ($group->fetch()) { if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) { $smartGroups[] = $group->id; } } CRM_Contact_BAO_GroupContactCache::check($smartGroups); $smartGroupQuery = ''; if (!empty($smartGroups)) { $smartGroups = implode(',', $smartGroups); $smartGroupQuery = " UNION DISTINCT\n SELECT DISTINCT smartgroup_contact.contact_id\n FROM civicrm_group_contact_cache smartgroup_contact\n WHERE smartgroup_contact.group_id IN ({$smartGroups}) "; } $sqlOp = $this->getSQLOperator($op); if (!is_array($value)) { $value = array($value); } $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")"; $contactAlias = $this->_aliases['civicrm_contact']; if (!empty($this->relationType) && $this->relationType == 'b_a') { $contactAlias = $this->_aliases['civicrm_contact_b']; } return " {$contactAlias}.id {$sqlOp} (\n SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id\n FROM civicrm_group_contact {$this->_aliases['civicrm_group']}\n WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'\n {$smartGroupQuery} ) "; }
/** * Given an array of contact ids, remove all the contacts from the group * * @param array $contactIds * (reference ) the array of contact ids to be removed. * @param int $groupId * The id of the group. * * @param string $method * @param string $status * @param NULL $tracking * * @return array * (total, removed, notRemoved) count of contacts removed to group */ public static function removeContactsFromGroup(&$contactIds, $groupId, $method = 'Admin', $status = 'Removed', $tracking = NULL) { if (!is_array($contactIds)) { return array(0, 0, 0); } if ($status == 'Removed' || $status == 'Deleted') { $op = 'delete'; } else { $op = 'edit'; } CRM_Utils_Hook::pre($op, 'GroupContact', $groupId, $contactIds); $date = date('YmdHis'); $numContactsRemoved = 0; $numContactsNotRemoved = 0; $group = new CRM_Contact_DAO_Group(); $group->id = $groupId; $group->find(TRUE); foreach ($contactIds as $contactId) { if ($status == 'Deleted') { $query = "DELETE FROM civicrm_group_contact WHERE contact_id={$contactId} AND group_id={$groupId}"; $dao = CRM_Core_DAO::executeQuery($query); $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); } else { $groupContact = new CRM_Contact_DAO_GroupContact(); $groupContact->group_id = $groupId; $groupContact->contact_id = $contactId; // check if the selected contact id already a member, or if this is // an opt-out of a smart group. // if not a member remove to groupContact else keep the count of contacts that are not removed if ($groupContact->find(TRUE) || $group->saved_search_id) { // remove the contact from the group $numContactsRemoved++; } else { $numContactsNotRemoved++; } //now we grant the negative membership to contact if not member. CRM-3711 $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); $groupContact->status = $status; $groupContact->save(); } } // also reset the acl cache $config = CRM_Core_Config::singleton(); if (!$config->doNotResetCache) { CRM_ACL_BAO_Cache::resetCache(); } // reset the group contact cache for all group(s) // if this group is being used as a smart group CRM_Contact_BAO_GroupContactCache::remove(); CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds); return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved); }
/** * 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; } }
/** * Given an id, get the name of the saved search. * * @param int $id * The id of the saved search. * * @param string $value * * @return string * the name of the saved search */ public static function getName($id, $value = 'name') { $group = new CRM_Contact_DAO_Group(); $group->saved_search_id = $id; if ($group->find(TRUE)) { return $group->{$value}; } return NULL; }
function from() { $iGroups = $xGroups = $iTags = $xTags = 0; //define table name $randomNum = md5(uniqid()); $this->_tableName = "civicrm_temp_custom_{$randomNum}"; //block for Group search $smartGroup = array(); if ($this->_groups || $this->_allSearch) { $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); while ($group->fetch()) { $allGroups[] = $group->id; if ($group->saved_search_id) { $smartGroup[$group->saved_search_id] = $group->id; } } $includedGroups = implode(',', $allGroups); if (!empty($this->_includeGroups)) { $iGroups = implode(',', $this->_includeGroups); } else { //if no group selected search for all groups $iGroups = NULL; } if (is_array($this->_excludeGroups)) { $xGroups = implode(',', $this->_excludeGroups); } else { $xGroups = 0; } $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=MyISAM"; CRM_Core_DAO::executeQuery($sql); //used only when exclude group is selected if ($xGroups != 0) { $excludeGroup = "INSERT INTO Xg_{$this->_tableName} ( contact_id )\n SELECT DISTINCT civicrm_group_contact.contact_id\n FROM civicrm_group_contact, civicrm_contact\n WHERE\n civicrm_contact.id = civicrm_group_contact.contact_id AND\n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN( {$xGroups})"; CRM_Core_DAO::executeQuery($excludeGroup); //search for smart group contacts foreach ($this->_excludeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssGroup = new CRM_Contact_DAO_Group(); $ssGroup->id = $values; if (!$ssGroup->find(TRUE)) { CRM_Core_Error::fatal(); } CRM_Contact_BAO_GroupContactCache::load($ssGroup); $smartSql = "\nSELECT gcc.contact_id\nFROM civicrm_group_contact_cache gcc\nWHERE gcc.group_id = {$ssGroup->id}\n"; $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery); } } } $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName} ( id int PRIMARY KEY AUTO_INCREMENT,\n contact_id int,\n group_names varchar(64)) ENGINE=MyISAM"; CRM_Core_DAO::executeQuery($sql); if ($iGroups) { $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n SELECT civicrm_contact.id as contact_id, civicrm_group.title as group_name\n FROM civicrm_contact\n INNER JOIN civicrm_group_contact\n ON civicrm_group_contact.contact_id = civicrm_contact.id\n LEFT JOIN civicrm_group\n ON civicrm_group_contact.group_id = civicrm_group.id"; } else { $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n SELECT civicrm_contact.id as contact_id, ''\n FROM civicrm_contact"; } //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " LEFT JOIN Xg_{$this->_tableName}\n ON civicrm_contact.id = Xg_{$this->_tableName}.contact_id"; } if ($iGroups) { $includeGroup .= " WHERE\n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN({$iGroups})"; } else { $includeGroup .= " WHERE ( 1 ) "; } //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null"; } CRM_Core_DAO::executeQuery($includeGroup); //search for smart group contacts foreach ($this->_includeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssGroup = new CRM_Contact_DAO_Group(); $ssGroup->id = $values; if (!$ssGroup->find(TRUE)) { CRM_Core_Error::fatal(); } CRM_Contact_BAO_GroupContactCache::load($ssGroup); $smartSql = "\nSELECT gcc.contact_id\nFROM civicrm_group_contact_cache gcc\nWHERE gcc.group_id = {$ssGroup->id}\n"; //used only when exclude group is selected if ($xGroups != 0) { $smartSql .= " AND gcc.contact_id NOT IN (SELECT contact_id FROM Xg_{$this->_tableName})"; } $smartGroupQuery = " INSERT IGNORE INTO Ig_{$this->_tableName}(contact_id)\n {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery); $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName}\n SET group_names = (SELECT title FROM civicrm_group\n WHERE civicrm_group.id = {$values})\n WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL\n AND Ig_{$this->_tableName}.group_names IS NULL"; CRM_Core_DAO::executeQuery($insertGroupNameQuery); } } } //group contact search end here; //block for Tags search if ($this->_tags || $this->_allSearch) { //find all tags $tag = new CRM_Core_DAO_Tag(); $tag->is_active = 1; $tag->find(); while ($tag->fetch()) { $allTags[] = $tag->id; } $includedTags = implode(',', $allTags); if (!empty($this->_includeTags)) { $iTags = implode(',', $this->_includeTags); } else { //if no group selected search for all groups $iTags = NULL; } if (is_array($this->_excludeTags)) { $xTags = implode(',', $this->_excludeTags); } else { $xTags = 0; } $sql = "CREATE TEMPORARY TABLE Xt_{$this->_tableName} ( contact_id int primary key) ENGINE=MyISAM"; CRM_Core_DAO::executeQuery($sql); //used only when exclude tag is selected if ($xTags != 0) { $excludeTag = "INSERT INTO Xt_{$this->_tableName} ( contact_id )\n SELECT DISTINCT civicrm_entity_tag.entity_id\n FROM civicrm_entity_tag, civicrm_contact\n WHERE\n civicrm_entity_tag.entity_table = 'civicrm_contact' AND\n civicrm_contact.id = civicrm_entity_tag.entity_id AND\n civicrm_entity_tag.tag_id IN( {$xTags})"; CRM_Core_DAO::executeQuery($excludeTag); } $sql = "CREATE TEMPORARY TABLE It_{$this->_tableName} ( id int PRIMARY KEY AUTO_INCREMENT,\n contact_id int,\n tag_names varchar(64)) ENGINE=MyISAM"; CRM_Core_DAO::executeQuery($sql); if ($iTags) { $includeTag = "INSERT INTO It_{$this->_tableName} (contact_id, tag_names)\n SELECT civicrm_contact.id as contact_id, civicrm_tag.name as tag_name\n FROM civicrm_contact\n INNER JOIN civicrm_entity_tag\n ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND\n civicrm_entity_tag.entity_id = civicrm_contact.id )\n LEFT JOIN civicrm_tag\n ON civicrm_entity_tag.tag_id = civicrm_tag.id"; } else { $includeTag = "INSERT INTO It_{$this->_tableName} (contact_id, tag_names)\n SELECT civicrm_contact.id as contact_id, ''\n FROM civicrm_contact"; } //used only when exclude tag is selected if ($xTags != 0) { $includeTag .= " LEFT JOIN Xt_{$this->_tableName}\n ON civicrm_contact.id = Xt_{$this->_tableName}.contact_id"; } if ($iTags) { $includeTag .= " WHERE civicrm_entity_tag.tag_id IN({$iTags})"; } else { $includeTag .= " WHERE ( 1 ) "; } //used only when exclude tag is selected if ($xTags != 0) { $includeTag .= " AND Xt_{$this->_tableName}.contact_id IS null"; } CRM_Core_DAO::executeQuery($includeTag); } $from = " FROM civicrm_contact contact_a"; /* * CRM-10850 / CRM-10848 * If we use include / exclude groups as smart groups for ACL's having the below causes * a cycle which messes things up. Hence commenting out for now * $this->buildACLClause('contact_a'); */ /* * check the situation and set booleans */ $Ig = $iGroups != 0; $It = $iTags != 0; $Xg = $xGroups != 0; $Xt = $xTags != 0; //PICK UP FROM HERE if (!$this->_groups && !$this->_tags) { $this->_andOr = 1; } /* * Set from statement depending on array sel */ $whereitems = array(); foreach (array('Ig', 'It') as $inc) { if ($this->_andOr == 1) { if (${$inc}) { $from .= " INNER JOIN {$inc}_{$this->_tableName} temptable{$inc} ON (contact_a.id = temptable{$inc}.contact_id)"; } } else { if (${$inc}) { $from .= " LEFT JOIN {$inc}_{$this->_tableName} temptable{$inc} ON (contact_a.id = temptable{$inc}.contact_id)"; } } if (${$inc}) { $whereitems[] = "temptable{$inc}.contact_id IS NOT NULL"; } } $this->_where = $whereitems ? "(" . implode(' OR ', $whereitems) . ')' : '(1)'; foreach (array('Xg', 'Xt') as $exc) { if (${$exc}) { $from .= " LEFT JOIN {$exc}_{$this->_tableName} temptable{$exc} ON (contact_a.id = temptable{$exc}.contact_id)"; $this->_where .= " AND temptable{$exc}.contact_id IS NULL"; } } $from .= " LEFT JOIN civicrm_email ON ( contact_a.id = civicrm_email.contact_id AND ( civicrm_email.is_primary = 1 OR civicrm_email.is_bulkmail = 1 ) ) {$this->_aclFrom}"; if ($this->_aclWhere) { $this->_where .= " AND {$this->_aclWhere} "; } // also exclude all contacts that are deleted // CRM-11627 $this->_where .= " AND (contact_a.is_deleted != 1) "; return $from; }
/** * Given an array of contact ids, remove all the contacts from the group * * @param array $contactIds * (reference ) the array of contact ids to be removed. * @param int $groupId * The id of the group. * * @param string $method * @param string $status * @param NULL $tracking * * @return array * (total, removed, notRemoved) count of contacts removed to group */ public static function removeContactsFromGroup(&$contactIds, $groupId, $method = 'Admin', $status = 'Removed', $tracking = NULL) { if (!is_array($contactIds)) { return array(0, 0, 0); } if ($status == 'Removed' || $status == 'Deleted') { $op = 'delete'; } else { $op = 'edit'; } CRM_Utils_Hook::pre($op, 'GroupContact', $groupId, $contactIds); $date = date('YmdHis'); $numContactsRemoved = 0; $numContactsNotRemoved = 0; $group = new CRM_Contact_DAO_Group(); $group->id = $groupId; $group->find(TRUE); foreach ($contactIds as $contactId) { if ($status == 'Deleted') { $query = "DELETE FROM civicrm_group_contact WHERE contact_id={$contactId} AND group_id={$groupId}"; $dao = CRM_Core_DAO::executeQuery($query); $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); } else { $groupContact = new CRM_Contact_DAO_GroupContact(); $groupContact->group_id = $groupId; $groupContact->contact_id = $contactId; // check if the selected contact id already a member, or if this is // an opt-out of a smart group. // if not a member remove to groupContact else keep the count of contacts that are not removed if ($groupContact->find(TRUE) || $group->saved_search_id) { // remove the contact from the group $numContactsRemoved++; } else { $numContactsNotRemoved++; } //now we grant the negative membership to contact if not member. CRM-3711 $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); $groupContact->status = $status; $groupContact->save(); } } // also reset the acl cache $config = CRM_Core_Config::singleton(); if (!$config->doNotResetCache) { CRM_ACL_BAO_Cache::resetCache(); } // reset the group contact cache for all group(s) // if this group is being used as a smart group // @todo consider what to do here - it feels like we should either // 1) just invalidate the specific group's cache(& perhaps any parents) & let cron do it's thing or // possibly clear this specific groups cache, or just call opportunisticCacheFlush() - which would have the // same effect as the remove call. The reservation about that is that it is no more aggressive for the group that // we know is altered than for all the others, or perhaps, more the point with it's parents & groups that use it in // their criteria. CRM_Contact_BAO_GroupContactCache::remove(); CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds); return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved); }
/** * Replace unsubscribe tokens. * * @param string $str * The string with tokens to be replaced. * @param object $domain * The domain BAO. * @param array $groups * The groups (if any) being unsubscribed. * @param bool $html * Replace tokens with html or plain text. * @param int $contact_id * The contact ID. * @param string $hash The security hash of the unsub event * * @return string * The processed string */ public static function &replaceUnsubscribeTokens($str, &$domain, &$groups, $html, $contact_id, $hash) { if (self::token_match('unsubscribe', 'group', $str)) { if (!empty($groups)) { $config = CRM_Core_Config::singleton(); $base = CRM_Utils_System::baseURL(); // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented $dao = new CRM_Contact_DAO_Group(); $dao->find(); while ($dao->fetch()) { if (substr($dao->visibility, 0, 6) == 'Public') { $visibleGroups[] = $dao->id; } } $value = implode(', ', $groups); self::token_replace('unsubscribe', 'group', $value, $str); } } return $str; }
/** * Build where clause for groups. * * This has been overridden in order to: * 1) only build the group clause when filtering * 2) render the id field as id rather than contact_id in * order to allow us to join on hte created temp table as if it * were the contact table. * * Further refactoring could break down the parent function so it can be selectively * leveraged. * * @param string $field * @param mixed $value * @param string $op * * @return string */ public function whereGroupClause($field, $value, $op) { if ($op == 'notin') { // We do not have an optimisation for this scenario at this stage. Use // parent. return parent::whereGroupClause($field, $value, $op); } if (empty($this->groupTempTable)) { $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); $smartGroups = array(); while ($group->fetch()) { if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) { $smartGroups[] = $group->id; } } CRM_Contact_BAO_GroupContactCache::check($smartGroups); $smartGroupQuery = ''; if (!empty($smartGroups)) { $smartGroups = implode(',', $smartGroups); $smartGroupQuery = " UNION DISTINCT\n SELECT DISTINCT smartgroup_contact.contact_id as id\n FROM civicrm_group_contact_cache smartgroup_contact\n WHERE smartgroup_contact.group_id IN ({$smartGroups}) "; } $sqlOp = $this->getSQLOperator($op); if (!is_array($value)) { $value = array($value); } $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")"; $query = "SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id as id\n FROM civicrm_group_contact {$this->_aliases['civicrm_group']}\n WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'\n {$smartGroupQuery} "; $this->buildGroupTempTable($query); } return "1"; }
function from() { //define table name $randomNum = md5(uniqid()); $this->_tableName = "civicrm_temp_custom_{$randomNum}"; //grab the contacts added in the date range first $sql = "CREATE TEMPORARY TABLE dates_{$this->_tableName} ( id int primary key, date_added date ) ENGINE=HEAP"; if ($this->_debug > 0) { print "-- Date range query: <pre>"; print "{$sql};"; print "</pre>"; } CRM_Core_DAO::executeQuery($sql); $startDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['start_date'])); $endDateFix = NULL; if (!empty($this->_formValues['end_date'])) { $endDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['end_date'])); # tack 11:59pm on to make search inclusive of the end date $endDateFix = "AND date_added <= '" . substr($endDate, 0, 10) . " 23:59:00'"; } $dateRange = "INSERT INTO dates_{$this->_tableName} ( id, date_added )\n SELECT\n civicrm_contact.id,\n min(civicrm_log.modified_date) AS date_added\n FROM\n civicrm_contact LEFT JOIN civicrm_log\n ON (civicrm_contact.id = civicrm_log.entity_id AND\n civicrm_log.entity_table = 'civicrm_contact')\n GROUP BY\n civicrm_contact.id\n HAVING\n date_added >= '{$startDate}' \n {$endDateFix}"; if ($this->_debug > 0) { print "-- Date range query: <pre>"; print "{$dateRange};"; print "</pre>"; } CRM_Core_DAO::executeQuery($dateRange, CRM_Core_DAO::$_nullArray); // Only include groups in the search query of one or more Include OR Exclude groups has been selected. // CRM-6356 if ($this->_groups) { //block for Group search $smartGroup = array(); require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); while ($group->fetch()) { $allGroups[] = $group->id; if ($group->saved_search_id) { $smartGroup[$group->saved_search_id] = $group->id; } } $includedGroups = implode(',', $allGroups); if (!empty($this->_includeGroups)) { $iGroups = implode(',', $this->_includeGroups); } else { //if no group selected search for all groups $iGroups = $includedGroups; } if (is_array($this->_excludeGroups)) { $xGroups = implode(',', $this->_excludeGroups); } else { $xGroups = 0; } $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); //used only when exclude group is selected if ($xGroups != 0) { $excludeGroup = "INSERT INTO Xg_{$this->_tableName} ( contact_id )\n SELECT DISTINCT civicrm_group_contact.contact_id\n FROM civicrm_group_contact, dates_{$this->_tableName} AS d\n WHERE \n d.id = civicrm_group_contact.contact_id AND \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN( {$xGroups})"; CRM_Core_DAO::executeQuery($excludeGroup, CRM_Core_DAO::$_nullArray); //search for smart group contacts foreach ($this->_excludeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql = $smartSql . " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact \n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray); } } } $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName}\n ( id int PRIMARY KEY AUTO_INCREMENT,\n contact_id int,\n group_names varchar(64)) ENGINE=HEAP"; if ($this->_debug > 0) { print "-- Include groups query: <pre>"; print "{$sql};"; print "</pre>"; } CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n SELECT d.id as contact_id, civicrm_group.name as group_name\n FROM dates_{$this->_tableName} AS d\n INNER JOIN civicrm_group_contact\n ON civicrm_group_contact.contact_id = d.id\n LEFT JOIN civicrm_group\n ON civicrm_group_contact.group_id = civicrm_group.id"; //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " LEFT JOIN Xg_{$this->_tableName}\n ON d.id = Xg_{$this->_tableName}.contact_id"; } $includeGroup .= " WHERE \n civicrm_group_contact.status = 'Added' AND\n civicrm_group_contact.group_id IN({$iGroups})"; //used only when exclude group is selected if ($xGroups != 0) { $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null"; } if ($this->_debug > 0) { print "-- Include groups query: <pre>"; print "{$includeGroup};"; print "</pre>"; } CRM_Core_DAO::executeQuery($includeGroup, CRM_Core_DAO::$_nullArray); //search for smart group contacts foreach ($this->_includeGroups as $keys => $values) { if (in_array($values, $smartGroup)) { $ssId = CRM_Utils_Array::key($values, $smartGroup); $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId); $smartSql .= " AND contact_a.id IN (\n SELECT id AS contact_id\n FROM dates_{$this->_tableName} )"; $smartSql .= " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact\n WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; //used only when exclude group is selected if ($xGroups != 0) { $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM Xg_{$this->_tableName})"; } $smartGroupQuery = " INSERT IGNORE INTO\n Ig_{$this->_tableName}(contact_id) \n {$smartSql}"; CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray); if ($this->_debug > 0) { print "-- Smart group query: <pre>"; print "{$smartGroupQuery};"; print "</pre>"; } $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName}\n SET group_names = (SELECT title FROM civicrm_group\n WHERE civicrm_group.id = {$values})\n WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL \n AND Ig_{$this->_tableName}.group_names IS NULL"; CRM_Core_DAO::executeQuery($insertGroupNameQuery, CRM_Core_DAO::$_nullArray); if ($this->_debug > 0) { print "-- Smart group query: <pre>"; print "{$insertGroupNameQuery};"; print "</pre>"; } } } } // end if( $this->_groups ) condition $from = "FROM civicrm_contact contact_a"; /* We need to join to this again to get the date_added value */ $from .= " INNER JOIN dates_{$this->_tableName} d ON (contact_a.id = d.id)"; // Only include groups in the search query of one or more Include OR Exclude groups has been selected. // CRM-6356 if ($this->_groups) { $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; } //this makes smart groups using this search compatible w/ CiviMail $from .= " LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id)"; return $from; }
function postProcess() { $formValues = $this->controller->exportValues($this->_name); require_once 'CRM/Standalone/User.php'; require_once 'CRM/Utils/System/Standalone.php'; require_once 'CRM/Core/BAO/OpenID.php'; $user = new CRM_Standalone_User($formValues['user_unique_id'], $formValues['email'], $formValues['first_name'], $formValues['last_name']); CRM_Utils_System_Standalone::getUserID($user); require_once 'CRM/Core/Session.php'; $session = CRM_Core_Session::singleton(); $contactId = $session->get('userID'); $query = "SELECT count(id) FROM civicrm_uf_match"; $ufCount = CRM_Core_DAO::singleValueQuery($query); if ($ufCount == 1 || defined('ALLOWED_TO_LOGIN')) { $openId = new CRM_Core_DAO_OpenID(); $openId->contact_id = $contactId; $openId->find(true); $openId->allowed_to_login = 1; $openId->update(); } // add first user to admin group if ($ufCount == 1) { require_once 'CRM/Contact/BAO/GroupContact.php'; require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->name = 'Administrators'; $group->is_active = 1; if ($group->find(true)) { $contactIds = array($contactId); CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $group->id, 'Web', 'Added'); } } else { if ($ufCount > 1 && !defined('CIVICRM_ALLOW_ALL')) { $session->set('msg', 'You are not allowed to login. Login failed. Contact your Administrator.'); $session->set('goahead', "no"); } } // Set this to false if the registration is successful $session->set('new_install', false); header("Location: index.php"); CRM_Utils_System::civiExit(); }