Ejemplo n.º 1
0
 /**
  * Unsubscribe a contact from the domain.
  *
  * @param int $job_id
  *   The job ID.
  * @param int $queue_id
  *   The Queue Event ID of the recipient.
  * @param string $hash
  *   The hash.
  *
  * @return bool
  *   Was the contact successfully unsubscribed?
  */
 public static function unsub_from_domain($job_id, $queue_id, $hash)
 {
     $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     if (!$q) {
         return FALSE;
     }
     $transaction = new CRM_Core_Transaction();
     $now = date('YmdHis');
     if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
         $email = new CRM_Core_BAO_Email();
         $email->id = $q->email_id;
         if ($email->find(TRUE)) {
             $sql = "\nUPDATE civicrm_email\nSET    on_hold = 2,\n       hold_date = %1\nWHERE  email = %2\n";
             $sqlParams = array(1 => array($now, 'Timestamp'), 2 => array($email->email, 'String'));
             CRM_Core_DAO::executeQuery($sql, $sqlParams);
         }
     } else {
         $contact = new CRM_Contact_BAO_Contact();
         $contact->id = $q->contact_id;
         $contact->is_opt_out = TRUE;
         $contact->save();
     }
     $ue = new CRM_Mailing_Event_BAO_Unsubscribe();
     $ue->event_queue_id = $queue_id;
     $ue->org_unsubscribe = 1;
     $ue->time_stamp = $now;
     $ue->save();
     $shParams = array('contact_id' => $q->contact_id, 'group_id' => NULL, 'status' => 'Removed', 'method' => 'Email', 'tracking' => $ue->id);
     CRM_Contact_BAO_SubscriptionHistory::create($shParams);
     $transaction->commit();
     return TRUE;
 }
/**
 * Implementation of hook_civicrm_pre
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_pre
 */
function mailchimp_civicrm_pre($op, $objectName, $id, &$params)
{
    $params1 = array('version' => 3, 'sequential' => 1, 'contact_id' => $id, 'id' => $id);
    if ($objectName == 'Email') {
        $email = new CRM_Core_BAO_Email();
        $email->id = $id;
        $email->find(TRUE);
        // If about to delete an email in CiviCRM, we must delete it from Mailchimp
        // because we won't get chance to delete it once it's gone.
        //
        // The other case covered here is changing an email address's status
        // from for-bulk-mail to not-for-bulk-mail.
        // @todo Note: However, this will delete a subscriber and lose reporting
        // info, where what they might have wanted was to change their email
        // address.
        if ($op == 'delete' || $op == 'edit' && $params['on_hold'] == 0 && $email->on_hold == 0 && $params['is_bulkmail'] == 0) {
            CRM_Mailchimp_Utils::deleteMCEmail(array($id));
        }
    }
    // If deleting an individual, delete their (bulk) email address from Mailchimp.
    if ($op == 'delete' && $objectName == 'Individual') {
        $result = civicrm_api('Contact', 'get', $params1);
        foreach ($result['values'] as $key => $value) {
            $emailId = $value['email_id'];
            if ($emailId) {
                CRM_Mailchimp_Utils::deleteMCEmail(array($emailId));
            }
        }
    }
}
Ejemplo n.º 3
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     $ei = CRM_Appraisals_ExportImportValuesConverter::singleton();
     $response = $this->summary($values);
     $this->formatDateParams();
     $this->_params['skipRecentView'] = TRUE;
     $this->_params['check_permissions'] = TRUE;
     $params = $this->getActiveFieldParams();
     $rowParams = array();
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $importedAppraisalCycleId = null;
     if (!empty($params['appraisal_cycle_id'])) {
         $importedAppraisalCycleId = (int) $params['appraisal_cycle_id'];
     }
     if (!$importedAppraisalCycleId) {
         $importedAppraisalCycleId = $this->_appraisalCycleIdIncremental++;
     }
     if (empty($params['contact_id']) && !empty($params['email'])) {
         $checkEmail = new CRM_Core_BAO_Email();
         $checkEmail->email = $params['email'];
         $checkEmail->find(TRUE);
         if (!empty($checkEmail->contact_id)) {
             $params['contact_id'] = $checkEmail->contact_id;
         }
     }
     if (!empty($formatValues['external_identifier'])) {
         $checkCid = new CRM_Contact_DAO_Contact();
         $checkCid->external_identifier = $formatValues['external_identifier'];
         $checkCid->find(TRUE);
         if (!empty($params['contact_id']) && $params['contact_id'] != $checkCid->id) {
             array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $params['contact_id']);
             return CRM_Import_Parser::ERROR;
         }
         if (!empty($checkCid->id)) {
             $params['contact_id'] = $checkCid->id;
         }
     }
     if (empty($params['contact_id']) && (int) $params['status_id']) {
         $error = 'Missing "contact_id" / "email" / "external_identifier" value.';
         array_unshift($values, $error);
         return CRM_Import_Parser::ERROR;
     }
     foreach ($this->_entity as $tableName => $entity) {
         $rowParams[$entity] = $this->getEntityParams($entity);
         if ($entity === 'AppraisalCycle' && $importedAppraisalCycleId) {
             $rowParams[$entity]['id'] = $importedAppraisalCycleId;
         }
         foreach ($rowParams[$entity] as $key => $value) {
             $rowParams[$entity][$key] = $ei->import($tableName, $key, $value);
         }
     }
     if (empty($this->_appraisalCycleIds[$importedAppraisalCycleId])) {
         try {
             unset($rowParams['AppraisalCycle']['id']);
             $appraisalCycleCreateResponse = civicrm_api3('AppraisalCycle', 'create', $rowParams['AppraisalCycle']);
         } catch (CiviCRM_API3_Exception $e) {
             $error = $e->getMessage();
             array_unshift($values, $error);
             return CRM_Import_Parser::ERROR;
         }
         $this->_appraisalCycleIds[$importedAppraisalCycleId] = (int) $appraisalCycleCreateResponse['id'];
     }
     $localAppraisalCycleId = $this->_appraisalCycleIds[$importedAppraisalCycleId];
     if (!empty($params['contact_id']) && (int) $params['contact_id']) {
         try {
             unset($rowParams['Appraisal']['id']);
             unset($rowParams['Appraisal']['external_identifier']);
             unset($rowParams['Appraisal']['email']);
             $rowParams['Appraisal']['appraisal_cycle_id'] = $localAppraisalCycleId;
             civicrm_api3('Appraisal', 'create', $rowParams['Appraisal']);
         } catch (CiviCRM_API3_Exception $e) {
             $error = $e->getMessage();
             array_unshift($values, $error);
             return CRM_Import_Parser::ERROR;
         }
     }
 }
 public function getContactByEmail($email)
 {
     $contactId = null;
     if (!empty($email)) {
         $checkEmail = new CRM_Core_BAO_Email();
         $checkEmail->email = $email;
         $checkEmail->find(TRUE);
         if (!empty($checkEmail->contact_id)) {
             $contactId = $checkEmail->contact_id;
         }
     }
     return $contactId;
 }
Ejemplo n.º 5
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     $entityNames = array('details', 'hour', 'health', 'leave', 'pay', 'pension', 'role');
     $ei = CRM_Hrjobcontract_ExportImportValuesConverter::singleton();
     $response = $this->summary($values);
     $this->formatDateParams();
     $this->_params['skipRecentView'] = TRUE;
     $this->_params['check_permissions'] = TRUE;
     $params = $this->getActiveFieldParams();
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $importedJobContractId = null;
     if (!empty($params['jobcontract_id'])) {
         $importedJobContractId = (int) $params['jobcontract_id'];
     }
     if (!$importedJobContractId) {
         $importedJobContractId = $this->_jobcontractIdIncremental++;
     }
     if (empty($params['contact_id']) && !empty($params['email'])) {
         $checkEmail = new CRM_Core_BAO_Email();
         $checkEmail->email = $params['email'];
         $checkEmail->find(TRUE);
         if (!empty($checkEmail->contact_id)) {
             $params['contact_id'] = $checkEmail->contact_id;
         }
     }
     if (!empty($formatValues['external_identifier'])) {
         $checkCid = new CRM_Contact_DAO_Contact();
         $checkCid->external_identifier = $formatValues['external_identifier'];
         $checkCid->find(TRUE);
         if (!empty($params['contact_id']) && $params['contact_id'] != $checkCid->id) {
             array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $params['contact_id']);
             return CRM_Import_Parser::ERROR;
         }
         if (!empty($checkCid->id)) {
             $params['contact_id'] = $checkCid->id;
         }
     }
     if (empty($params['contact_id'])) {
         $error = 'Missing "contact_id" / "email" / "external_identifier" value.';
         array_unshift($values, $error);
         return CRM_Import_Parser::ERROR;
     }
     $revisionParams = $this->getEntityParams('HRJobContractRevision');
     $revisionData = array();
     foreach ($entityNames as $value) {
         if (empty($revisionParams[$value . '_revision_id'])) {
             $revisionParams[$value . '_revision_id'] = $this->_revisionIdIncremental;
         }
         $revisionData[$value] = $revisionParams[$value . '_revision_id'];
     }
     $this->_revisionIdIncremental++;
     if (empty($revisionData)) {
         $error = 'Missing Revision data.';
         array_unshift($values, $error);
         return CRM_Import_Parser::ERROR;
     }
     $revisionId = max($revisionData);
     if (empty($this->_jobContractIds[$importedJobContractId])) {
         try {
             $jobContractCreateResponse = civicrm_api3('HRJobContract', 'create', array('contact_id' => $params['contact_id']));
         } catch (CiviCRM_API3_Exception $e) {
             $error = $e->getMessage();
             array_unshift($values, $error);
             return CRM_Import_Parser::ERROR;
         }
         $this->_jobContractIds[$importedJobContractId] = (int) $jobContractCreateResponse['id'];
         $this->_previousRevision = array();
         foreach ($entityNames as $value) {
             $this->_previousRevision['imported'][$value] = null;
             $this->_previousRevision['local'][$value] = null;
         }
         $this->_previousRevision['imported']['id'] = null;
         $this->_previousRevision['local']['id'] = null;
         $this->_revisionIds = array();
         $this->_revisionEntityMap = array();
     }
     $localJobContractId = $this->_jobContractIds[$importedJobContractId];
     $newRevisionInstance = null;
     if ($this->_previousRevision['imported']['id'] !== $revisionId) {
         // create new Revision:
         $newRevisionParams = $revisionParams;
         unset($newRevisionParams['id']);
         foreach ($entityNames as $value) {
             unset($newRevisionParams[$value . '_revision_id']);
         }
         $newRevisionParams['jobcontract_id'] = $localJobContractId;
         $newRevisionParams = $this->validateFields('HRJobContractRevision', $newRevisionParams);
         $newRevisionInstance = CRM_Hrjobcontract_BAO_HRJobContractRevision::create($newRevisionParams);
         if (!empty($this->_previousRevision['imported']['id'])) {
             foreach ($entityNames as $value) {
                 $field = $value . '_revision_id';
                 $newRevisionInstance->{$field} = $this->_previousRevision['local'][$value];
             }
             $newRevisionInstance->save();
         }
     }
     try {
         foreach ($this->_entity as $entity) {
             if (in_array($entity, array('HRJobContract', 'HRJobContractRevision'))) {
                 continue;
             }
             $entityClass = 'CRM_Hrjobcontract_BAO_' . $entity;
             $tableName = _civicrm_get_table_name($entity);
             if (empty($revisionParams[$tableName . '_revision_id'])) {
                 continue;
             }
             $params = $this->getEntityParams($entity);
             $params['jobcontract_id'] = $localJobContractId;
             foreach ($params as $key => $value) {
                 $params[$key] = $ei->import($tableName, $key, $value);
             }
             $params = $this->validateFields($entity, $params);
             $params['import'] = 1;
             if ($revisionParams[$tableName . '_revision_id'] === $revisionId) {
                 if ($tableName === 'leave' || $this->_previousRevision['imported'][$tableName] !== $revisionId) {
                     if (!empty($newRevisionInstance)) {
                         $params['jobcontract_revision_id'] = $newRevisionInstance->id;
                     } else {
                         $params['jobcontract_revision_id'] = $this->_previousRevision['local'][$tableName];
                     }
                     if ($tableName === 'leave') {
                         foreach ($params['leave_amount'] as $leaveTypeId => $leaveAmount) {
                             $params['leave_type'] = $leaveTypeId;
                             $params['leave_amount'] = $leaveAmount;
                             $entityInstance = $entityClass::create($params);
                         }
                     } else {
                         $entityInstance = $entityClass::create($params);
                     }
                     $this->_previousRevision['local'][$tableName] = $entityInstance->jobcontract_revision_id;
                 }
             }
             $this->_previousRevision['imported'][$tableName] = $revisionParams[$tableName . '_revision_id'];
         }
     } catch (CiviCRM_API3_Exception $e) {
         $error = $e->getMessage();
         array_unshift($values, $error);
         return CRM_Import_Parser::ERROR;
     }
     if (!empty($newRevisionInstance)) {
         foreach ($entityNames as $value) {
             $field = $value . '_revision_id';
             $newRevisionInstance->{$field} = $this->_previousRevision['local'][$value];
         }
         $newRevisionInstance->save();
     }
     $this->_previousRevision['imported']['id'] = $revisionId;
 }
 /**
  * Collect CiviCRM data into temporary working table.
  */
 static function syncCollectCiviCRM($listID)
 {
     CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Form_Sync syncCollectCiviCRM $listID= ', $listID);
     // Nb. these are temporary tables but we don't use TEMPORARY table because they are
     // needed over multiple sessions because of queue.
     CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS tmp_mailchimp_push_c;");
     $dao = CRM_Core_DAO::executeQuery("CREATE TABLE tmp_mailchimp_push_c (\n        contact_id INT(10) UNSIGNED NOT NULL,\n        email_id INT(10) UNSIGNED NOT NULL,\n        email VARCHAR(200),\n        first_name VARCHAR(100),\n        last_name VARCHAR(100),\n        hash CHAR(32),\n        groupings VARCHAR(4096),\n        PRIMARY KEY (email_id, email, hash)\n        );");
     // Cheekily access the database directly to obtain a prepared statement.
     $db = $dao->getDatabaseConnection();
     $insert = $db->prepare('INSERT INTO tmp_mailchimp_push_c VALUES(?, ?, ?, ?, ?, ?, ?)');
     //create table for mailchim civicrm syn errors
     $dao = CRM_Core_DAO::executeQuery("CREATE TABLE IF NOT EXISTS mailchimp_civicrm_syn_errors (\n        id int(11) NOT NULL AUTO_INCREMENT,\n        email VARCHAR(200),\n        error VARCHAR(200),\n        error_count int(10),\n        group_id int(20),\n        list_id VARCHAR(20),\n        PRIMARY KEY (id)\n        );");
     // We need to know what groupings we have maps to.
     // We only care about CiviCRM groups that are mapped to this MC List:
     $mapped_groups = CRM_Mailchimp_Utils::getGroupsToSync(array(), $listID);
     // First, get all subscribers from the membership group for this list.
     // ... Find CiviCRM group id for the membership group.
     // ... And while we're at it, build an SQL-safe array of groupIds for groups mapped to groupings.
     //     (we use that later)
     $membership_group_id = FALSE;
     $grouping_group_ids = array('normal' => array(), 'smart' => array());
     $default_info = array();
     foreach ($mapped_groups as $group_id => $details) {
         CRM_Contact_BAO_GroupContactCache::loadAll($group_id);
         if (!$details['grouping_id']) {
             $membership_group_id = $group_id;
         } else {
             $grouping_group_ids[$details['civigroup_uses_cache'] ? 'smart' : 'normal'][] = (int) $group_id;
             $default_info[$details['grouping_id']][$details['group_id']] = FALSE;
         }
     }
     $grouping_group_ids['smart'] = implode(',', $grouping_group_ids['smart']);
     $grouping_group_ids['normal'] = implode(',', $grouping_group_ids['normal']);
     if (!$membership_group_id) {
         throw new Exception("No CiviCRM group is mapped to determine membership of Mailchimp list {$listID}");
     }
     // ... Load all subscribers in $groupContact object
     if (!($groupContact = CRM_Mailchimp_Utils::getGroupContactObject($membership_group_id))) {
         CRM_Mailchimp_Utils::checkDebug('get group contact= ', $groupContact);
         throw new Exception("No CiviCRM group is mapped to determine membership of Mailchimp list {$listID}. CiviCRM group {$membership_group_id} failed to load");
     }
     // Now we iterate through the subscribers, collecting data about the other mapped groups
     // This is pretty inefficient :-(
     while ($groupContact->fetch()) {
         // Find the contact, for the name fields
         $contact = new CRM_Contact_BAO_Contact();
         $contact->id = $groupContact->contact_id;
         $contact->is_deleted = 0;
         if (!$contact->find(TRUE)) {
             continue;
         }
         // Find their primary (bulk) email
         $email = new CRM_Core_BAO_Email();
         $email->contact_id = $groupContact->contact_id;
         $email->is_primary = TRUE;
         if (!$email->find(TRUE)) {
             continue;
         }
         // If no email, it's like they're not there.
         if (!$email->email || $email->on_hold || $contact->is_opt_out || $contact->do_not_email) {
             //@todo update stats.
             continue;
         }
         // Find out if they're in any groups that we care about.
         // Start off as not in the groups...
         $info = $default_info;
         // We can do this with two queries, one for normal groups, one for smart groups.
         // Normal groups.
         if ($grouping_group_ids['normal']) {
             $groupContact2 = new CRM_Contact_BAO_GroupContact();
             $groupContact2->contact_id = $groupContact->contact_id;
             $groupContact2->whereAdd("status = 'Added'");
             $groupContact2->whereAdd("group_id IN ({$grouping_group_ids['normal']})");
             $groupContact2->find();
             while ($groupContact2->fetch()) {
                 // need MC grouping_id and group_id
                 $details = $mapped_groups[$groupContact2->group_id];
                 $info[$details['grouping_id']][$details['group_id']] = TRUE;
             }
             unset($groupContact2);
         }
         // Smart groups
         if ($grouping_group_ids['smart']) {
             $groupContactCache = new CRM_Contact_BAO_GroupContactCache();
             $groupContactCache->contact_id = $groupContact->contact_id;
             $groupContactCache->whereAdd("group_id IN ({$grouping_group_ids['smart']})");
             $groupContactCache->find();
             while ($groupContactCache->fetch()) {
                 // need MC grouping_id and group_id
                 $details = $mapped_groups[$groupContactCache->group_id];
                 $info[$details['grouping_id']][$details['group_id']] = TRUE;
             }
             unset($groupContactCache);
         }
         // OK we should now have all the info we need.
         // Serialize the grouping array for SQL storage - this is the fastest way.
         $info = serialize($info);
         // we're ready to store this but we need a hash that contains all the info
         // for comparison with the hash created from the CiviCRM data (elsewhere).
         //          email,           first name,      last name,      groupings
         $hash = md5($email->email . $contact->first_name . $contact->last_name . $info);
         // run insert prepared statement
         $db->execute($insert, array($contact->id, $email->id, $email->email, $contact->first_name, $contact->last_name, $hash, $info));
     }
     // Tidy up.
     $db->freePrepared($insert);
     // count
     $dao = CRM_Core_DAO::executeQuery("SELECT COUNT(*) c  FROM tmp_mailchimp_push_c");
     $dao->fetch();
     CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Form_Sync syncCollectCiviCRM $listID= ', $listID);
     return $dao->c;
 }
 /**
  * Get an Email DAO object for a given email id.
  */
 static function getEmailbyId($email_id)
 {
     $email = new CRM_Core_BAO_Email();
     $email->id = $email_id;
     if (!$email->find(TRUE)) {
         throw new CRM_CiviMailchimp_Exception("Could not find Email record with ID {$email_id}");
     }
     return $email;
 }
 public function getContactByLookup($data)
 {
     $contactId = null;
     // external_identifier:
     if (!empty($data['external_identifier']) && !$contactId) {
         $checkCid = new CRM_Contact_DAO_Contact();
         $checkCid->external_identifier = $data['external_identifier'];
         $checkCid->find(TRUE);
         if (!empty($checkCid->id)) {
             $contactId = $checkCid->id;
         }
     }
     // email:
     if (!empty($data['email']) && !$contactId) {
         $checkEmail = new CRM_Core_BAO_Email();
         $checkEmail->email = $data['email'];
         $checkEmail->find(TRUE);
         if (!empty($checkEmail->contact_id)) {
             $contactId = $checkEmail->contact_id;
         }
     }
     // id:
     if (!empty($data['id']) && !$contactId) {
         $checkId = new CRM_Contact_DAO_Contact();
         $checkId->id = $data['id'];
         $checkId->find(TRUE);
         if (!empty($checkId->id)) {
             $contactId = $checkId->id;
         }
     }
     return $contactId;
 }