/**
  * build all the data structures needed to build the form
  *
  * @return void
  * @access public
  */
 function preProcess()
 {
     // reset action from the session
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'update');
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $rcid = CRM_Utils_Request::retrieve('rcid', 'Positive', $this);
     $rcid = $rcid ? "&id={$rcid}" : '';
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext(CRM_Utils_System::url('civicrm/user', "reset=1{$rcid}"));
     if ($this->_contactId) {
         $contact = new CRM_Contact_DAO_Contact();
         $contact->id = $this->_contactId;
         if (!$contact->find(TRUE)) {
             CRM_Core_Error::statusBounce(ts('contact does not exist: %1', array(1 => $this->_contactId)));
         }
         $this->_contactType = $contact->contact_type;
         // check for permissions
         if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) {
             CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
         }
         list($displayName, $contactImage) = CRM_Contact_BAO_Contact::getDisplayAndImage($this->_contactId);
         CRM_Utils_System::setTitle($displayName, $contactImage . ' ' . $displayName);
     } else {
         CRM_Core_Error::statusBounce(ts('Could not get a contact_id and/or contact_type'));
     }
 }
Example #2
0
 function validateData(&$input, &$ids, &$objects, $required = true)
 {
     // make sure contact exists and is valid
     require_once 'CRM/Contact/DAO/Contact.php';
     $contact = new CRM_Contact_DAO_Contact();
     $contact->id = $ids['contact'];
     if (!$contact->find(true)) {
         CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']}");
         echo "Failure: Could not find contact record: {$ids['contact']}<p>";
         return false;
     }
     // make sure contribution exists and is valid
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->id = $ids['contribution'];
     if (!$contribution->find(true)) {
         CRM_Core_Error::debug_log_message("Could not find contribution record: {$contributionID}");
         echo "Failure: Could not find contribution record for {$contributionID}<p>";
         return false;
     }
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $objects['contact'] =& $contact;
     $objects['contribution'] =& $contribution;
     if (!$this->loadObjects($input, $ids, $objects, $required)) {
         return false;
     }
     return true;
 }
 function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL)
 {
     // make sure contact exists and is valid
     $contact = new CRM_Contact_DAO_Contact();
     $contact->id = $ids['contact'];
     if (!$contact->find(TRUE)) {
         CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']}");
         echo "Failure: Could not find contact record: {$ids['contact']}<p>";
         return FALSE;
     }
     // make sure contribution exists and is valid
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->id = $ids['contribution'];
     if (!$contribution->find(TRUE)) {
         CRM_Core_Error::debug_log_message("Could not find contribution record: " . $contribution->id);
         echo "Failure: Could not find contribution record for {$contribution->id}<p>";
         return FALSE;
     }
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $objects['contact'] =& $contact;
     $objects['contribution'] =& $contribution;
     if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
         return FALSE;
     }
     return TRUE;
 }
 /**
  * Both testDummy1 and testDummy2 have been created at some point (as part of the test runs),
  * but all the data was rolled-back
  *
  * @throws \Exception
  */
 public static function tearDownAfterClass()
 {
     if (!is_numeric(self::$contactIds['testDummy1'])) {
         throw new \Exception("Uh oh! The static \$contactIds does not include testDummy1! Did the test fail to execute?");
     }
     if (!is_numeric(self::$contactIds['testDummy2'])) {
         throw new \Exception("Uh oh! The static \$contactIds does not include testDummy2! Did the test fail to execute?");
     }
     $dao = new \CRM_Contact_DAO_Contact();
     $dao->id = self::$contactIds['testDummy1'];
     if ($dao->find()) {
         throw new \Exception("Uh oh! testDummy1 still exists!");
     }
     $dao = new \CRM_Contact_DAO_Contact();
     $dao->id = self::$contactIds['testDummy2'];
     if ($dao->find()) {
         throw new \Exception("Uh oh! testDummy2 still exists!");
     }
 }
 /**
  * Get a list of Commendations matching the params, where each param key is:
  *  1. the key of a field in civicrm_activity, except for activity_type_id
  *  2. the key of a custom field on the activity (volunteer_project_id)
  *  3. the key of a field in civicrm_contact
  *
  * @param array $params
  * @return array of CRM_Volunteer_BAO_Project objects
  */
 public static function retrieve(array $params)
 {
     $activity_fields = CRM_Activity_DAO_Activity::fields();
     $contact_fields = CRM_Contact_DAO_Contact::fields();
     $custom_fields = self::getCustomFields();
     // This is the "real" id
     $activity_fields['id'] = $activity_fields['activity_id'];
     unset($activity_fields['activity_id']);
     // enforce restrictions on parameters
     $allowed_params = array_flip(array_merge(array_keys($activity_fields), array_keys($contact_fields), array_keys($custom_fields)));
     unset($allowed_params['activity_type_id']);
     $filtered_params = array_intersect_key($params, $allowed_params);
     $custom_group = self::getCustomGroup();
     $customTableName = $custom_group['table_name'];
     foreach ($custom_fields as $name => $field) {
         $selectClause[] = "{$customTableName}.{$field['column_name']} AS {$name}";
     }
     $customSelect = implode(', ', $selectClause);
     $activityContactTypes = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContactTypes);
     $placeholders = array(1 => array($targetID, 'Integer'), 2 => array(self::getActivityTypeId(), 'Integer'));
     $i = count($placeholders) + 1;
     $where = array();
     $whereClause = NULL;
     foreach ($filtered_params as $key => $value) {
         if (CRM_Utils_Array::value($key, $activity_fields)) {
             $dataType = CRM_Utils_Type::typeToString($activity_fields[$key]['type']);
             $fieldName = $activity_fields[$key]['name'];
             $tableName = CRM_Activity_DAO_Activity::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $contact_fields)) {
             $dataType = CRM_Utils_Type::typeToString($contact_fields[$key]['type']);
             $fieldName = $contact_fields[$key]['name'];
             $tableName = CRM_Contact_DAO_Contact::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $custom_fields)) {
             $dataType = $custom_fields[$key]['data_type'];
             $fieldName = $custom_fields[$key]['column_name'];
             $tableName = $customTableName;
         }
         $where[] = "{$tableName}.{$fieldName} = %{$i}";
         $placeholders[$i] = array($value, $dataType);
         $i++;
     }
     if (count($where)) {
         $whereClause = 'AND ' . implode("\nAND ", $where);
     }
     $query = "\n      SELECT\n        civicrm_activity.*,\n        {$customSelect},\n        activityContact.contact_id AS volunteer_contact_id,\n        volunteer_contact.sort_name AS volunteer_sort_name,\n        volunteer_contact.display_name AS volunteer_display_name\n      FROM civicrm_activity\n      INNER JOIN civicrm_activity_contact activityContact\n        ON (\n          activityContact.activity_id = civicrm_activity.id\n          AND activityContact.record_type_id = %1\n        )\n      INNER JOIN civicrm_contact volunteer_contact\n        ON activityContact.contact_id = volunteer_contact.id\n      INNER JOIN {$customTableName}\n        ON ({$customTableName}.entity_id = civicrm_activity.id)\n      WHERE civicrm_activity.activity_type_id = %2\n      {$whereClause}\n    ";
     $dao = CRM_Core_DAO::executeQuery($query, $placeholders);
     $rows = array();
     while ($dao->fetch()) {
         $rows[$dao->id] = $dao->toArray();
     }
     return $rows;
 }
Example #6
0
 /**
  * This function is called when action is browse
  *
  * return null
  * @access public
  */
 function browse()
 {
     $note =& new CRM_Core_DAO_Note();
     $note->entity_table = 'civicrm_contact';
     $note->entity_id = $this->_contactId;
     $note->orderBy('modified_date desc');
     $values = array();
     $links =& CRM_Contact_Page_View_Note::links();
     $action = array_sum(array_keys($links)) & CRM_Core_Action::mask($this->_permission);
     $note->find();
     while ($note->fetch()) {
         $values[$note->id] = array();
         CRM_Core_DAO::storeValues($note, $values[$note->id]);
         $values[$note->id]['action'] = CRM_Core_Action::formLink($links, $action, array('id' => $note->id, 'cid' => $this->_contactId));
         $contact = new CRM_Contact_DAO_Contact();
         $contact->id = $note->contact_id;
         $contact->find();
         $contact->fetch();
         $values[$note->id]['createdBy'] = $contact->display_name;
     }
     $this->assign('notes', $values);
 }
Example #7
0
 /**
  * This is a contructor of the class.
  */
 public function __construct()
 {
     parent::__construct();
 }
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 function preProcess()
 {
     $this->_cdType = CRM_Utils_Array::value('type', $_GET);
     $this->assign('cdType', FALSE);
     if ($this->_cdType) {
         $this->assign('cdType', TRUE);
         return CRM_Custom_Form_CustomData::preProcess($this);
     }
     $this->_caseId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $this->_currentlyViewedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     if ($this->_action & CRM_Core_Action::ADD && !$this->_currentlyViewedContactId) {
         // check for add contacts permissions
         if (!CRM_Core_Permission::check('add contacts')) {
             CRM_Utils_System::permissionDenied();
             return;
         }
     }
     //CRM-4418
     if (!CRM_Core_Permission::checkActionPermission('CiviCase', $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
     }
     if ($this->_action & CRM_Core_Action::DELETE || $this->_action & CRM_Core_Action::RENEW) {
         return TRUE;
     }
     if (!$this->_caseId) {
         $caseAttributes = array('case_type' => CRM_Case_PseudoConstant::caseType(), 'case_status' => CRM_Case_PseudoConstant::caseStatus(), 'encounter_medium' => CRM_Case_PseudoConstant::encounterMedium());
         foreach ($caseAttributes as $key => $values) {
             if (empty($values)) {
                 CRM_Core_Error::fatal(ts('You do not have any active %1', array(1 => str_replace('_', ' ', $key))));
                 break;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::ADD) {
         $this->_activityTypeId = CRM_Core_OptionGroup::getValue('activity_type', 'Open Case', 'name');
         if (!$this->_activityTypeId) {
             CRM_Core_Error::fatal(ts('The Open Case activity type is missing or disabled. Please have your site administrator check Administer > Option Lists > Activity Types for the CiviCase component.'));
         }
     }
     //check for case permissions.
     if (!CRM_Case_BAO_Case::accessCiviCase()) {
         CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
     }
     if ($this->_action & CRM_Core_Action::ADD && (!CRM_Core_Permission::check('access all cases and activities') && !CRM_Core_Permission::check('add cases'))) {
         CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
     }
     if ($this->_activityTypeFile = CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, 'Case')) {
         $this->assign('activityTypeFile', $this->_activityTypeFile);
     }
     $details = CRM_Case_PseudoConstant::caseActivityType(FALSE);
     CRM_Utils_System::setTitle($details[$this->_activityTypeId]['label']);
     $this->assign('activityType', $details[$this->_activityTypeId]['label']);
     $this->assign('activityTypeDescription', $details[$this->_activityTypeId]['description']);
     if (isset($this->_currentlyViewedContactId)) {
         $contact = new CRM_Contact_DAO_Contact();
         $contact->id = $this->_currentlyViewedContactId;
         if (!$contact->find(TRUE)) {
             CRM_Core_Error::statusBounce(ts('Client contact does not exist: %1', array(1 => $this->_currentlyViewedContactId)));
         }
         $this->assign('clientName', $contact->display_name);
     }
     $session = CRM_Core_Session::singleton();
     $this->_currentUserId = $session->get('userID');
     //when custom data is included in this page
     CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_activityTypeId, 1, 'Activity');
     eval("CRM_Case_Form_Activity_{$this->_activityTypeFile}::preProcess( \$this );");
     $activityGroupTree = $this->_groupTree;
     // for case custom fields to populate with defaults
     if (CRM_Utils_Array::value('hidden_custom', $_POST)) {
         CRM_Custom_Form_CustomData::preProcess($this);
         CRM_Custom_Form_CustomData::buildQuickForm($this);
     }
     // so that grouptree is not populated with case fields, since the grouptree is used
     // for populating activity custom fields.
     $this->_groupTree = $activityGroupTree;
 }
Example #9
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, $doGeocodeAddress = false)
 {
     $config =& CRM_Core_Config::singleton();
     $this->_unparsedStreetAddressContacts = array();
     if (!$doGeocodeAddress) {
         // CRM-5854, reset the geocode method to null to prevent geocoding
         $config->geocodeMethod = null;
     }
     // first make sure this is a valid line
     //$this->_updateWithId = false;
     $response = $this->summary($values);
     $statusFieldName = $this->_statusFieldName;
     if ($response != CRM_Import_Parser::VALID) {
         $importRecordParams = array($statusFieldName => 'INVALID', "{$statusFieldName}Msg" => "Invalid (Error Code: {$response})");
         $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('contact_type' => $this->_contactType);
     static $contactFields = null;
     if ($contactFields == null) {
         require_once "CRM/Contact/DAO/Contact.php";
         $contactFields =& CRM_Contact_DAO_Contact::import();
     }
     //check if external identifier exists in database
     if (CRM_Utils_Array::value('external_identifier', $params) && (CRM_Utils_Array::value('id', $params) || in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_SKIP, CRM_Import_Parser::DUPLICATE_NOCHECK)))) {
         require_once "CRM/Contact/BAO/Contact.php";
         if ($internalCid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
             if ($internalCid != CRM_Utils_Array::value('id', $params)) {
                 $errorMessage = ts('External Identifier already exists in database.');
                 array_unshift($values, $errorMessage);
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) {
         if (CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType, false, 'label')) {
             $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($this->_contactType, false, null);
             $params['contact_sub_type'] = array_search($subType, $subTypes);
         } elseif (!CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType)) {
             $message = "Mismatched or Invalid Contact SubType.";
             array_unshift($values, $message);
             return CRM_Import_Parser::NO_MATCH;
         }
     }
     //get contact id to format common data in update/fill mode,
     //if external identifier is present, CRM-4423
     if ($this->_updateWithId && !CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
         if ($cid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
             $formatted['id'] = $cid;
         }
     }
     //format common data, CRM-4062
     $this->formatCommonData($params, $formatted, $contactFields);
     $relationship = false;
     $createNewContact = true;
     // Support Match and Update Via Contact ID
     if ($this->_updateWithId) {
         $createNewContact = false;
         if (!CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
             if ($cid) {
                 $params['id'] = $cid;
             } else {
                 //update contact if dedupe found contact id, CRM-4148
                 $dedupeParams = $formatted;
                 //special case to check dedupe if external id present.
                 //if we send external id dedupe will stop.
                 unset($dedupeParams['external_identifier']);
                 $checkDedupe = _civicrm_duplicate_formatted_contact($dedupeParams);
                 if (civicrm_duplicate($checkDedupe)) {
                     $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
                     if (count($matchingContactIds) == 1) {
                         $params['id'] = array_pop($matchingContactIds);
                     } else {
                         $message = "More than one matching contact found for given criteria.";
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 } else {
                     $createNewContact = true;
                 }
             }
         }
         $error = _civicrm_duplicate_formatted_contact($formatted);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 $updateflag = true;
                 foreach ($matchedIDs as $contactId) {
                     if ($params['id'] == $contactId) {
                         $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
                         if ($formatted['contact_type'] == $contactType) {
                             //validation of subtype for update mode
                             //CRM-5125
                             $contactSubType = null;
                             if (CRM_Utils_Array::value('contact_sub_type', $params)) {
                                 $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
                             }
                             if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
                                 $message = "Mismatched contact SubTypes :";
                                 array_unshift($values, $message);
                                 $updateflag = false;
                                 $this->_retCode = CRM_Import_Parser::NO_MATCH;
                             } else {
                                 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId, false);
                                 $updateflag = false;
                                 $this->_retCode = CRM_Import_Parser::VALID;
                             }
                         } else {
                             $message = "Mismatched contact Types :";
                             array_unshift($values, $message);
                             $updateflag = false;
                             $this->_retCode = CRM_Import_Parser::NO_MATCH;
                         }
                     }
                 }
                 if ($updateflag) {
                     $message = "Mismatched contact IDs OR Mismatched contact Types :";
                     array_unshift($values, $message);
                     $this->_retCode = CRM_Import_Parser::NO_MATCH;
                 }
             }
         } else {
             $contactType = null;
             if (CRM_Utils_Array::value('id', $params)) {
                 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
                 if ($contactType) {
                     if ($formatted['contact_type'] == $contactType) {
                         //validation of subtype for update mode
                         //CRM-5125
                         $contactSubType = null;
                         if (CRM_Utils_Array::value('contact_sub_type', $params)) {
                             $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
                         }
                         if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
                             $message = "Mismatched contact SubTypes :";
                             array_unshift($values, $message);
                             $this->_retCode = CRM_Import_Parser::NO_MATCH;
                         } else {
                             $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $params['id'], false);
                             $this->_retCode = CRM_Import_Parser::VALID;
                         }
                     } else {
                         $message = "Mismatched contact Types :";
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 } else {
                     // we should avoid multiple errors for single record
                     // since we have already retCode and we trying to force again.
                     if ($this->_retCode != CRM_Import_Parser::NO_MATCH) {
                         $message = "No contact found for this contact ID:" . $params['id'];
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 }
             } else {
                 //CRM-4148
                 //now we want to create new contact on update/fill also.
                 $createNewContact = true;
             }
         }
         if (is_a($newContact, 'CRM_Contact_BAO_Contact')) {
             $relationship = true;
         } else {
             if (is_a($error, 'CRM_Core_Error')) {
                 $newContact = $error;
                 $relationship = true;
             }
         }
     }
     //fixed CRM-4148
     //now we create new contact in update/fill mode also.
     if ($createNewContact) {
         //CRM-4430, don't carry if not submitted.
         foreach (array('prefix', 'suffix', 'gender') as $name) {
             if (array_key_exists($name, $formatted)) {
                 if (in_array($name, array('prefix', 'suffix'))) {
                     $formattedName = "individual_{$name}";
                     $formatted[$formattedName] = CRM_Core_OptionGroup::getValue($formattedName, (string) $formatted[$name]);
                 } else {
                     $formatted[$name] = CRM_Core_OptionGroup::getValue($name, (string) $formatted[$name]);
                 }
             }
         }
         $newContact = $this->createContact($formatted, $contactFields, $onDuplicate);
     }
     if (is_object($newContact) || $newContact instanceof CRM_Contact_BAO_Contact) {
         $relationship = true;
         $newContact = clone $newContact;
         $this->_newContacts[] = $newContact->id;
         //get return code if we create new contact in update mode, CRM-4148
         if ($this->_updateWithId) {
             $this->_retCode = CRM_Import_Parser::VALID;
         }
     } else {
         if (civicrm_duplicate($newContact)) {
             $relationship = true;
             $contactID = $newContact['error_message']['params'][0];
             if (!in_array($contactID, $this->_newContacts)) {
                 $this->_newContacts[] = $contactID;
             }
         }
     }
     if ($relationship) {
         $primaryContactId = null;
         if (civicrm_duplicate($newContact)) {
             if (CRM_Utils_Rule::integer($newContact['error_message']['params'][0])) {
                 $primaryContactId = $newContact['error_message']['params'][0];
             }
         } else {
             $primaryContactId = $newContact->id;
         }
         if ((civicrm_duplicate($newContact) || is_a($newContact, 'CRM_Contact_BAO_Contact')) && $primaryContactId) {
             //relationship contact insert
             foreach ($params as $key => $field) {
                 list($id, $first, $second) = CRM_Utils_System::explode('_', $key, 3);
                 if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) {
                     continue;
                 }
                 $relationType = new CRM_Contact_DAO_RelationshipType();
                 $relationType->id = $id;
                 $relationType->find(true);
                 $direction = "contact_sub_type_{$second}";
                 $formatting = array('contact_type' => $params[$key]['contact_type']);
                 //set subtype for related contact CRM-5125
                 if (isset($relationType->{$direction})) {
                     //validation of related contact subtype for update mode
                     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $params[$key]) && $relCsType != $relationType->{$direction}) {
                         $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact");
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         $formatting['contact_sub_type'] = $relationType->{$direction};
                     }
                 }
                 $relationType->free();
                 $contactFields = null;
                 $contactFields = CRM_Contact_DAO_Contact::import();
                 //Relation on the basis of External Identifier.
                 if (!CRM_Utils_Array::value('id', $params[$key]) && isset($params[$key]['external_identifier'])) {
                     $params[$key]['id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['external_identifier'], 'id', 'external_identifier');
                 }
                 // check for valid related contact id in update/fill mode, CRM-4424
                 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL)) && CRM_Utils_Array::value('id', $params[$key])) {
                     $relatedContactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_type');
                     if (!$relatedContactType) {
                         $errorMessage = ts("No contact found for this related contact ID: %1", array(1 => $params[$key]['id']));
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         //validation of related contact subtype for update mode
                         //CRM-5125
                         $relatedCsType = null;
                         if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
                             $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_sub_type');
                         }
                         if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params[$key]['id'], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
                             $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact ID: %1", array(1 => $params[$key]['id']));
                             array_unshift($values, $errorMessage);
                             return CRM_Import_Parser::NO_MATCH;
                         } else {
                             // get related contact id to format data in update/fill mode,
                             //if external identifier is present, CRM-4423
                             $formatting['id'] = $params[$key]['id'];
                         }
                     }
                 }
                 //format common data, CRM-4062
                 $this->formatCommonData($field, $formatting, $contactFields);
                 //fixed for CRM-4148
                 if ($params[$key]['id']) {
                     $contact = array('contact_id' => $params[$key]['id']);
                     $defaults = array();
                     $relatedNewContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
                 } else {
                     $relatedNewContact = $this->createContact($formatting, $contactFields, $onDuplicate, null, false);
                 }
                 if (is_object($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) {
                     $relatedNewContact = clone $relatedNewContact;
                 }
                 $matchedIDs = array();
                 // To update/fill contact, get the matching contact Ids if duplicate contact found
                 // otherwise get contact Id from object of related contact
                 if (is_array($relatedNewContact) && civicrm_error($relatedNewContact)) {
                     if (civicrm_duplicate($relatedNewContact)) {
                         $matchedIDs = explode(',', $relatedNewContact['error_message']['params'][0]);
                     } else {
                         $errorMessage = $relatedNewContact['error_message'];
                         array_unshift($values, $errorMessage);
                         $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                         $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                         return CRM_Import_Parser::ERROR;
                     }
                 } else {
                     $matchedIDs[] = $relatedNewContact->id;
                 }
                 // update/fill related contact after getting matching Contact Ids, CRM-4424
                 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) {
                     //validation of related contact subtype for update mode
                     //CRM-5125
                     $relatedCsType = null;
                     if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
                         $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $matchedIDs[0], 'contact_sub_type');
                     }
                     if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($matchedIDs[0], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
                         $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.");
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         $updatedContact = $this->createContact($formatting, $contactFields, $onDuplicate, $matchedIDs[0]);
                     }
                 }
                 static $relativeContact = array();
                 if (civicrm_duplicate($relatedNewContact)) {
                     if (count($matchedIDs) >= 1) {
                         $relContactId = $matchedIDs[0];
                         //add relative contact to count during update & fill mode.
                         //logic to make count distinct by contact id.
                         if ($this->_newRelatedContacts || !empty($relativeContact)) {
                             $reContact = array_keys($relativeContact, $relContactId);
                             if (empty($reContact)) {
                                 $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                             }
                         } else {
                             $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                         }
                     }
                 } else {
                     $relContactId = $relatedNewContact->id;
                     $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                 }
                 if (civicrm_duplicate($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) {
                     //fix for CRM-1993.Checks for duplicate related contacts
                     if (count($matchedIDs) >= 1) {
                         //if more than one duplicate contact
                         //found, create relationship with first contact
                         // now create the relationship record
                         $relationParams = array();
                         $relationParams = array('relationship_type_id' => $key, 'contact_check' => array($relContactId => 1), 'is_active' => 1, 'skipRecentView' => true);
                         // we only handle related contact success, we ignore failures for now
                         // at some point wold be nice to have related counts as separate
                         $relationIds = array('contact' => $primaryContactId);
                         list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
                         CRM_Contact_BAO_Relationship::relatedMemberships($primaryContactId, $relationParams, $relationIds);
                         //handle current employer, CRM-3532
                         if ($valid) {
                             require_once 'CRM/Core/PseudoConstant.php';
                             $allRelationships = CRM_Core_PseudoConstant::relationshipType('name');
                             $relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $key);
                             $relationshipType = str_replace($relationshipTypeId . '_', '', $key);
                             $orgId = $individualId = null;
                             if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employee of') {
                                 $orgId = $relContactId;
                                 $individualId = $primaryContactId;
                             } else {
                                 if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') {
                                     $orgId = $primaryContactId;
                                     $individualId = $relContactId;
                                 }
                             }
                             if ($orgId && $individualId) {
                                 $currentEmpParams[$individualId] = $orgId;
                                 require_once 'CRM/Contact/BAO/Contact/Utils.php';
                                 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($this->_updateWithId) {
         //return warning if street address is unparsed, CRM-5886
         return $this->processMessage($values, $statusFieldName, $this->_retCode);
     }
     //dupe checking
     if (is_array($newContact) && civicrm_error($newContact)) {
         $code = null;
         if (($code = CRM_Utils_Array::value('code', $newContact['error_message'])) && $code == CRM_Core_Error::DUPLICATE_CONTACT) {
             $urls = array();
             // need to fix at some stage and decide if the error will return an
             // array or string, crude hack for now
             if (is_array($newContact['error_message']['params'][0])) {
                 $cids = $newContact['error_message']['params'][0];
             } else {
                 $cids = explode(',', $newContact['error_message']['params'][0]);
             }
             foreach ($cids as $cid) {
                 $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, true);
             }
             $url_string = implode("\n", $urls);
             // If we duplicate more than one record, skip no matter what
             if (count($cids) > 1) {
                 $errorMessage = ts('Record duplicates multiple contacts');
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 //combine error msg to avoid mismatch between error file columns.
                 $errorMessage .= "\n" . $url_string;
                 array_unshift($values, $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
             // Params only had one id, so shift it out
             $contactId = array_shift($cids);
             $cid = null;
             $vals = array('contact_id' => $contactId);
             if ($onDuplicate == CRM_Import_Parser::DUPLICATE_REPLACE) {
                 $result = civicrm_replace_contact_formatted($contactId, $formatted, $contactFields);
                 $cid = $result['result'];
             } else {
                 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
                     $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
                 } else {
                     if ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
                         $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
                     }
                 }
             }
             // else skip does nothing and just returns an error code.
             if ($cid) {
                 $contact = array('contact_id' => $cid);
                 $defaults = array();
                 $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
             }
             if (civicrm_error($newContact)) {
                 $contactID = $newContact['error_message']['params'][0];
                 if (!in_array($contactID, $this->_newContacts)) {
                     $this->_newContacts[] = $contactID;
                 }
             }
             //CRM-262 No Duplicate Checking
             if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
                 array_unshift($values, $url_string);
                 $importRecordParams = array($statusFieldName => 'DUPLICATE', "{$statusFieldName}Msg" => "Skipping duplicate record");
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::DUPLICATE;
             }
             $importRecordParams = array($statusFieldName => 'IMPORTED');
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             //return warning if street address is not parsed, CRM-5886
             return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
         } else {
             // Not a dupe, so we had an error
             $errorMessage = $newContact['error_message'];
             array_unshift($values, $errorMessage);
             $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             return CRM_Import_Parser::ERROR;
         }
     }
     // sleep(3);
     return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
 }
Example #10
0
 /**
  * Delete current employer relationship.
  *
  * @param int $id
  * @param int $action
  *
  * @return CRM_Contact_DAO_Relationship
  */
 public static function clearCurrentEmployer($id, $action)
 {
     $relationship = new CRM_Contact_DAO_Relationship();
     $relationship->id = $id;
     $relationship->find(TRUE);
     //to delete relationship between household and individual                                                                                          \
     //or between individual and organization
     if ($action & CRM_Core_Action::DISABLE || $action & CRM_Core_Action::DELETE) {
         $relTypes = CRM_Utils_Array::index(array('name_a_b'), CRM_Core_PseudoConstant::relationshipType('name'));
         if (isset($relTypes['Employee of']) && $relationship->relationship_type_id == $relTypes['Employee of']['id'] || isset($relTypes['Household Member of']) && $relationship->relationship_type_id == $relTypes['Household Member of']['id']) {
             $sharedContact = new CRM_Contact_DAO_Contact();
             $sharedContact->id = $relationship->contact_id_a;
             $sharedContact->find(TRUE);
             // CRM-15881 UPDATES
             // changed FROM "...relationship->relationship_type_id == 4..." TO "...relationship->relationship_type_id == 5..."
             // As the system should be looking for type "employer of" (id 5) and not "sibling of" (id 4)
             // As suggested by @davecivicrm, the employee relationship type id is fetched using the CRM_Core_DAO::getFieldValue() class and method, since these ids differ from system to system.
             $employerRelTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
             if ($relationship->relationship_type_id == $employerRelTypeId && $relationship->contact_id_b == $sharedContact->employer_id) {
                 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
             }
         }
     }
     return $relationship;
 }
 /**
  * Construct a WHERE clause to handle permissions to $object_*
  *
  * @param array ref $tables -   Any tables that may be needed in the FROM
  * @param string $operation -   The operation being attempted
  * @param string $object_table -    The table of the object in question
  * @param int $object_id    -   The ID of the object in question
  * @param int $acl_id   -       If it's a grant/revoke operation, the ACL ID
  * @param boolean $acl_role -  For grant operations, this flag determines if we're granting a single acl (false) or an entire group.
  *
  * @return string           -   The WHERE clause, or 0 on failure
  * @access public
  * @static
  */
 public static function permissionClause(&$tables, $operation, $object_table = NULL, $object_id = NULL, $acl_id = NULL, $acl_role = FALSE)
 {
     $dao = new CRM_ACL_DAO_ACL();
     $t = array('ACL' => self::getTableName(), 'ACLRole' => 'civicrm_acl_role', 'ACLEntityRole' => CRM_ACL_DAO_EntityRole::getTableName(), 'Contact' => CRM_Contact_DAO_Contact::getTableName(), 'Group' => CRM_Contact_DAO_Group::getTableName(), 'GroupContact' => CRM_Contact_DAO_GroupContact::getTableName());
     $session = CRM_Core_Session::singleton();
     $contact_id = $session->get('userID');
     $where = " {$t['ACL']}.operation = '" . CRM_Utils_Type::escape($operation, 'String') . "'";
     /* Include clause if we're looking for a specific table/id permission */
     if (!empty($object_table)) {
         $where .= " AND ( {$t['ACL']}.object_table IS null\n                         OR ({$t['ACL']}.object_table   = '" . CRM_Utils_Type::escape($object_table, 'String') . "'";
         if (!empty($object_id)) {
             $where .= " AND ({$t['ACL']}.object_id IS null\n                            OR {$t['ACL']}.object_id = " . CRM_Utils_Type::escape($object_id, 'Integer') . ')';
         }
         $where .= '))';
     }
     /* Include clause if we're granting an ACL or ACL Role */
     if (!empty($acl_id)) {
         $where .= " AND ({$t['ACL']}.acl_id IS null\n                        OR {$t['ACL']}.acl_id   = " . CRM_Utils_Type::escape($acl_id, 'Integer') . ')';
         if ($acl_role) {
             $where .= " AND {$t['ACL']}.acl_table = '{$t['ACLRole']}'";
         } else {
             $where .= " AND {$t['ACL']}.acl_table = '{$t['ACL']}'";
         }
     }
     $query = array();
     /* Query for permissions granted to all contacts in the domain */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    WHERE       {$t['ACL']}.entity_table    = '{$t['Domain']}'\n                            AND ({$where})";
     /* Query for permissions granted to all contacts through an ACL group */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['ACLEntityRole']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['ACLEntityRole']}.acl_role_id)\n\n                    INNER JOIN  {$t['ACLRole']}\n                            ON      {$t['ACL']}.entity_id =\n                                    {$t['ACLRole']}.id\n\n                    WHERE       {$t['ACLEntityRole']}.entity_table =\n                                    '{$t['Domain']}'\n                            AND {$t['ACLRole']}.is_active      = 1\n                            AND ({$where})";
     /* Query for permissions granted directly to the contact */
     $query[] = "SELECT      {$t['ACL']}.*, 1 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['Contact']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['Contact']}'\n                            AND     {$t['ACL']}.entity_id = {$t['Contact']}.id)\n\n                    WHERE       {$t['Contact']}.id          = {$contact_id}\n                            AND ({$where})";
     /* Query for permissions granted to the contact through an ACL group */
     $query[] = "SELECT      {$t['ACL']}.*, 1 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['ACLEntityRole']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['ACLEntityRole']}.acl_role_id)\n\n                    INNER JOIN  {$t['ACLRole']}\n                            ON  {$t['ACL']}.entity_id = {$t['ACLRole']}.id\n\n                    WHERE       {$t['ACLEntityRole']}.entity_table =\n                                    '{$t['Contact']}'\n                        AND     {$t['ACLRole']}.is_active      = 1\n                        AND     {$t['ACLEntityRole']}.entity_id  = {$contact_id}\n                        AND     ({$where})";
     /* Query for permissions granted to the contact through a group */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['GroupContact']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['Group']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['GroupContact']}.group_id)\n\n                    WHERE       ({$where})\n                        AND     {$t['GroupContact']}.contact_id = {$contact_id}\n                        AND     {$t['GroupContact']}.status     = 'Added')";
     /* Query for permissions granted through an ACL group to a Contact
      * group */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['ACLEntityRole']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['ACLEntityRole']}.acl_role_id)\n\n                    INNER JOIN  {$t['ACLRole']}\n                            ON  {$t['ACL']}.entity_id = {$t['ACLRole']}.id\n\n                    INNER JOIN  {$t['GroupContact']}\n                            ON  ({$t['ACLEntityRole']}.entity_table =\n                                    '{$t['Group']}'\n                            AND     {$t['ACLEntityRole']}.entity_id =\n                                    {$t['GroupContact']}.group_id)\n\n                    WHERE       ({$where})\n                        AND     {$t['ACLRole']}.is_active      = 1\n                        AND     {$t['GroupContact']}.contact_id = {$contact_id}\n                        AND     {$t['GroupContact']}.status     = 'Added'";
     $union = '(' . implode(') UNION DISTINCT (', $query) . ')';
     $dao->query($union);
     $allow = array(0);
     $deny = array(0);
     $override = array();
     while ($dao->fetch()) {
         /* Instant bypass for the following cases:
          * 1) the rule governs all tables
          * 2) the rule governs all objects in the table in question
          * 3) the rule governs the specific object we want
          */
         if (empty($dao->object_table) || $dao->object_table == $object_table && (empty($dao->object_id) || $dao->object_id == $object_id)) {
             $clause = 1;
         } else {
             /* Otherwise try to generate a clause for this rule */
             $clause = self::getClause($dao->object_table, $dao->object_id, $tables);
             /* If the clause returned is null, then the rule is a blanket
              * (id is null) on a table other than the one we're interested
              * in.  So skip it. */
             if (empty($clause)) {
                 continue;
             }
         }
         /* Now we figure out if this is an allow or deny rule, and possibly
          * a contact-level override */
         if ($dao->deny) {
             $deny[] = $clause;
         } else {
             $allow[] = $clause;
             if ($dao->override) {
                 $override[] = $clause;
             }
         }
     }
     $allows = '(' . implode(' OR ', $allow) . ')';
     $denies = '(' . implode(' OR ', $deny) . ')';
     if (!empty($override)) {
         $denies = '(NOT (' . implode(' OR ', $override) . ") AND {$denies})";
     }
     return "({$allows} AND NOT {$denies})";
 }
 /**
  * This function sets the default values for the form. Relationship that in edit/view mode
  * the default values are retrieved from the database
  * 
  * @access public
  * @return None
  */
 function setDefaultValues()
 {
     if ($this->_cdType) {
         return CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     $defaults = array();
     if ($this->_action & CRM_Core_Action::UPDATE) {
         if (!empty($this->_values)) {
             $defaults['relationship_type_id'] = $this->_rtypeId;
             if (CRM_Utils_Array::value('start_date', $this->_values)) {
                 list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($this->_values['start_date']);
             }
             if (CRM_Utils_Array::value('end_date', $this->_values)) {
                 list($defaults['end_date']) = CRM_Utils_Date::setDateDefaults($this->_values['end_date']);
             }
             $defaults['description'] = CRM_Utils_Array::value('description', $this->_values);
             $defaults['is_active'] = CRM_Utils_Array::value('is_active', $this->_values);
             $defaults['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $this->_values);
             $defaults['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $this->_values);
             $contact = new CRM_Contact_DAO_Contact();
             if ($this->_rtype == 'a_b' && $this->_values['contact_id_a'] == $this->_contactId) {
                 $contact->id = $this->_values['contact_id_b'];
             } else {
                 $contact->id = $this->_values['contact_id_a'];
             }
             if ($contact->find(true)) {
                 $this->_display_name_b = $contact->display_name;
                 $this->assign('sort_name_b', $this->_display_name_b);
                 //is current employee/employer.
                 if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employee of' && $contact->id == CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'employer_id')) {
                     $defaults['is_current_employer'] = 1;
                     $this->_values['current_employee_id'] = $this->_contactId;
                     $this->_values['current_employer_id'] = $contact->id;
                 } else {
                     if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employer of' && $this->_contactId == $contact->employer_id) {
                         $defaults['is_current_employer'] = 1;
                         $this->_values['current_employee_id'] = $contact->id;
                         $this->_values['current_employer_id'] = $this->_contactId;
                     }
                 }
             }
             $relationshipID = $this->_values['id'];
             $query = "SELECT id, note FROM civicrm_note where entity_table = 'civicrm_relationship' and entity_id = {$relationshipID}  order by modified_date desc";
             $dao = new CRM_Core_DAO();
             $dao->query($query);
             if ($dao->fetch($query)) {
                 $defaults['note'] = $dao->note;
             }
         }
     } else {
         $defaults['is_active'] = 1;
         $defaults['relationship_type_id'] = $this->_rtypeId;
     }
     return $defaults;
 }
Example #13
0
 /**
  * Generate a random contact of type $cType.
  *
  * @param  string  Contact Type, default as 'Individual'
  * @return int     Contact ID of created contact
  */
 private function randomContact($cType = 'Individual')
 {
     $contact = new CRM_Contact_DAO_Contact();
     //TODO : in future if we need cType as 'Organization'
     //Generate contact of type individual randomly
     $contact->contact_type = $cType;
     if ($cType == 'Individual') {
         list($gender_id, $gender) = $this->randomKeyValue($this->gender);
         $contact->gender_id = $gender_id;
         $contact->first_name = $this->randomItem($gender . '_name');
         $contact->middle_name = $this->probability(0.5) ? '' : ucfirst($this->randomChar());
         $contact->last_name = $this->randomItem('last_name');
         $contact->sort_name = $contact->last_name . ', ' . $contact->first_name;
         $contact->display_name = $contact->first_name . ' ' . $contact->last_name;
     }
     $contact->save();
     $email = $this->_individualEmail($contact);
     $this->_addEmail($contact->id, $email, self::WORK);
     return $contact->id;
 }
Example #14
0
 /**
  * Returns the list of fields that can be exported
  *
  * @param bool $prefix
  *
  * @return array
  */
 static function &export($prefix = false)
 {
     if (!self::$_export) {
         self::$_export = array();
         $fields = self::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     self::$_export['contact'] =& $fields[$name];
                 } else {
                     self::$_export[$name] =& $fields[$name];
                 }
             }
         }
     }
     return self::$_export;
 }
 function addMembership()
 {
     $contact = new CRM_Contact_DAO_Contact();
     $contact->query("SELECT id FROM civicrm_contact where contact_type = 'Individual'");
     while ($contact->fetch()) {
         $contacts[] = $contact->id;
     }
     shuffle($contacts);
     $randomContacts = array_slice($contacts, 0, 350);
     $sources = array('Payment', 'Donation', 'Check');
     $membershipTypes = array(2, 1);
     $membershipTypeNames = array('Student', 'General');
     $statuses = array(3, 4);
     $membership = "\n INSERT INTO civicrm_membership\n        (contact_id, membership_type_id, join_date, start_date, end_date, source, status_id)\nVALUES\n ";
     $activity = "\nINSERT INTO civicrm_activity\n        (source_contact_id, source_record_id, activity_type_id, subject, activity_date_time, duration, location, phone_id, phone_number, details, priority_id,parent_id, is_test, status_id)\nVALUES\n";
     foreach ($randomContacts as $count => $dontCare) {
         $source = self::_getRandomElement($sources);
         $acititySourceId = $count + 1;
         if (($count + 1) % 11 == 0) {
             // lifetime membership, status can be anything
             $startDate = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - $count, date('Y')));
             $membership .= "( {$randomContacts[$count]}, 3, '{$startDate}', '{$startDate}', null, '{$source}', 1)";
             $activity .= "( {$randomContacts[$count]}, {$acititySourceId}, 7, 'Lifetime', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
         } elseif (($count + 1) % 5 == 0) {
             // Grace or expired, memberhsip type is random of 1 & 2
             $randId = array_rand($membershipTypes);
             $membershipType = self::_getRandomElement($membershipTypes);
             $startDate = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - $count * ($randId + 1) * ($randId + 1) * ($randId + 1), date('Y') - ($randId + 1)));
             $partOfDate = explode('-', $startDate);
             $endDate = date('Y-m-d', mktime(0, 0, 0, $partOfDate[1], $partOfDate[2] - 1, $partOfDate[0] + ($randId + 1)));
             $membership .= "( {$randomContacts[$count]}, {$membershipType}, '{$startDate}', '{$startDate}', '{$endDate}', '{$source}', {$statuses[$randId]})";
             $activity .= "( {$randomContacts[$count]}, {$acititySourceId}, 7, '{$membershipTypeNames[$randId]}', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
         } elseif (($count + 1) % 2 == 0) {
             // membership type 2
             $startDate = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - $count, date('Y')));
             $endDate = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - $count, date('Y') + 1));
             $membership .= "( {$randomContacts[$count]}, 2, '{$startDate}', '{$startDate}', '{$endDate}', '{$source}', 1)";
             $activity .= "( {$randomContacts[$count]}, {$acititySourceId}, 7, 'Student', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
         } else {
             // membership type 1
             $startDate = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - $count, date('Y')));
             $endDate = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - $count, date('Y') + 2));
             $membership .= "( {$randomContacts[$count]}, 1, '{$startDate}', '{$startDate}', '{$endDate}', '{$source}', 1)";
             $activity .= "( {$randomContacts[$count]}, {$acititySourceId}, 7, 'General', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
         }
         if ($count != 349) {
             $membership .= ",";
             $activity .= ",";
         }
     }
     CRM_Core_DAO::executeQuery($membership, CRM_Core_DAO::$_nullArray);
     CRM_Core_DAO::executeQuery($activity, CRM_Core_DAO::$_nullArray);
 }
Example #16
0
 /**
  * Function to create navigation for CiviCRM Admin Menu
  *
  * @param int $contactID contact id
  *
  * @return string $navigation returns navigation html
  * @static
  */
 static function createNavigation($contactID)
 {
     $config = CRM_Core_Config::singleton();
     // if on frontend, do not create navigation menu items, CRM-5349
     if ($config->userFrameworkFrontend) {
         return "<!-- {$config->lcMessages} -->";
     }
     $navParams = array('contact_id' => $contactID);
     $navigation = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME, 'navigation', NULL, NULL, $contactID);
     // FIXME: hack for CRM-5027: we need to prepend the navigation string with
     // (HTML-commented-out) locale info so that we rebuild menu on locale changes
     if (!$navigation || substr($navigation, 0, 14) != "<!-- {$config->lcMessages} -->") {
         //retrieve navigation if it's not cached.
         $navigation = self::buildNavigation();
         //add additional navigation items
         $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1');
         $appendSring = "<li id=\"menu-logout\" class=\"menumain\"><a href=\"{$logoutURL}\">" . ts('Logout') . "</a></li>";
         // get home menu from db
         $homeParams = array('name' => 'Home');
         $homeNav = array();
         self::retrieve($homeParams, $homeNav);
         if ($homeNav) {
             list($path, $q) = explode('&', $homeNav['url']);
             $homeURL = CRM_Utils_System::url($path, $q);
             $homeLabel = $homeNav['label'];
             // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
             if ($homeLabel == 'Home') {
                 $homeLabel = ts('Home');
             }
         } else {
             $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
             $homeLabel = ts('Home');
         }
         if ($config->userSystem->is_drupal && (module_exists('toolbar') && user_access('access toolbar') || module_exists('admin_menu') && user_access('access administration menu'))) {
             $prepandString = "<li class=\"menumain crm-link-home\">" . $homeLabel . "<ul id=\"civicrm-home\"><li><a href=\"{$homeURL}\">" . $homeLabel . "</a></li><li><a href=\"#\" onclick=\"cj.Menu.closeAll( );cj('#civicrm-menu').toggle( );\">" . ts('Drupal Menu') . "</a></li></ul>";
         } elseif ($config->userSystem->is_wordpress) {
             $prepandString = "<li class=\"menumain crm-link-home\">" . $homeLabel . "<ul id=\"civicrm-home\"><li><a href=\"{$homeURL}\">" . $homeLabel . "</a></li><li><a href=\"#\" onclick=\"cj.Menu.closeAll( );cj('#civicrm-menu').toggle( );\">" . ts('WordPress Menu') . "</a></li></ul>";
         } else {
             $prepandString = "<li class=\"menumain crm-link-home\"><a href=\"{$homeURL}\" title=\"" . $homeLabel . "\">" . $homeLabel . "</a>";
         }
         // prepend the navigation with locale info for CRM-5027
         $navigation = "<!-- {$config->lcMessages} -->" . $prepandString . $navigation . $appendSring;
         // before inserting check if contact id exists in db
         // this is to handle wierd case when contact id is in session but not in db
         $contact = new CRM_Contact_DAO_Contact();
         $contact->id = $contactID;
         if ($contact->find(TRUE)) {
             CRM_Core_BAO_Setting::setItem($navigation, CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME, 'navigation', NULL, $contactID, $contactID);
         }
     }
     return $navigation;
 }
Example #17
0
 /**
  * @return array
  *   Array of field names which will be compared, so everything except ID.
  */
 public static function getContactFields()
 {
     $contactFields = CRM_Contact_DAO_Contact::fields();
     $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date', 'primary_contact_id', 'sort_name', 'user_unique_id');
     foreach ($contactFields as $field => $value) {
         if (in_array($field, $invalidFields)) {
             unset($contactFields[$field]);
         }
     }
     return array_keys($contactFields);
 }
/**
 *
 * @param array $params
 *
 * @return array
 *   <type>
 */
function _civicrm_api3_deprecated_duplicate_formatted_contact($params)
{
    $id = CRM_Utils_Array::value('id', $params);
    $externalId = CRM_Utils_Array::value('external_identifier', $params);
    if ($id || $externalId) {
        $contact = new CRM_Contact_DAO_Contact();
        $contact->id = $id;
        $contact->external_identifier = $externalId;
        if ($contact->find(TRUE)) {
            if ($params['contact_type'] != $contact->contact_type) {
                return civicrm_api3_create_error("Mismatched contact IDs OR Mismatched contact Types");
            }
            $error = CRM_Core_Error::createError("Found matching contacts: {$contact->id}", CRM_Core_Error::DUPLICATE_CONTACT, 'Fatal', $contact->id);
            return civicrm_api3_create_error($error->pop());
        }
    } else {
        require_once 'CRM/Dedupe/Finder.php';
        $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
        $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised');
        if (!empty($ids)) {
            $ids = implode(',', $ids);
            $error = CRM_Core_Error::createError("Found matching contacts: {$ids}", CRM_Core_Error::DUPLICATE_CONTACT, 'Fatal', $ids);
            return civicrm_api3_create_error($error->pop());
        }
    }
    return civicrm_api3_create_success(TRUE);
}
Example #19
0
 /**
  * Send a reponse email informing the contact of the groups from which he
  * has been unsubscribed.
  *
  * @param string $queue_id      The queue event ID
  * @param array $groups         List of group IDs
  * @param bool $is_domain       Is this domain-level?
  * @param int $job              The job ID
  * @return void
  * @access public
  * @static
  */
 public static function send_unsub_response($queue_id, $groups, $is_domain = false, $job)
 {
     $config =& CRM_Core_Config::singleton();
     $domain =& CRM_Core_BAO_Domain::getDomain();
     $jobTable = CRM_Mailing_BAO_Job::getTableName();
     $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
     $contacts = CRM_Contact_DAO_Contact::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $dao =& new CRM_Mailing_BAO_Mailing();
     $dao->query("   SELECT * FROM {$mailingTable} \n                        INNER JOIN {$jobTable} ON\n                            {$jobTable}.mailing_id = {$mailingTable}.id \n                        WHERE {$jobTable}.id = {$job}");
     $dao->fetch();
     $component =& new CRM_Mailing_BAO_Component();
     if ($is_domain) {
         $component->id = $dao->optout_id;
     } else {
         $component->id = $dao->unsubscribe_id;
     }
     $component->find(true);
     $html = $component->body_html;
     if ($component->body_text) {
         $text = $component->body_text;
     } else {
         $text = CRM_Utils_String::htmlToText($component->body_html);
     }
     $eq =& new CRM_Core_DAO();
     $eq->query("SELECT     {$contacts}.preferred_mail_format as format,\n                    {$contacts}.id as contact_id,\n                    {$email}.email as email,\n                    {$queue}.hash as hash\n        FROM        {$contacts}\n        INNER JOIN  {$queue} ON {$queue}.contact_id = {$contacts}.id\n        INNER JOIN  {$email} ON {$queue}.email_id = {$email}.id\n        WHERE       {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer'));
     $eq->fetch();
     if ($groups) {
         foreach ($groups as $key => $value) {
             if (!$value) {
                 unset($groups[$key]);
             }
         }
     }
     $message =& new Mail_Mime("\n");
     list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email);
     $bao =& new CRM_Mailing_BAO_Mailing();
     $bao->body_text = $text;
     $bao->body_html = $html;
     $tokens = $bao->getTokens();
     require_once 'CRM/Utils/Token.php';
     if ($eq->format == 'HTML' || $eq->format == 'Both') {
         $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']);
         $html = CRM_Utils_Token::replaceUnsubscribeTokens($html, $domain, $groups, true, $eq->contact_id, $eq->hash);
         $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, true, $tokens['html']);
         $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, null, $tokens['html']);
         $message->setHTMLBody($html);
     }
     if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
         $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']);
         $text = CRM_Utils_Token::replaceUnsubscribeTokens($text, $domain, $groups, false, $eq->contact_id, $eq->hash);
         $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, false, $tokens['text']);
         $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, null, $tokens['text']);
         $message->setTxtBody($text);
     }
     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' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}");
     $b =& CRM_Utils_Mail::setMimeParams($message);
     $h =& $message->headers($headers);
     $mailer =& $config->getMailer();
     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler'));
     if (is_object($mailer)) {
         $mailer->send($eq->email, $h, $b);
         CRM_Core_Error::setCallback();
     }
 }
Example #20
0
 /**
  * Recursive function to get all descendent notes of the note with given ID.
  *
  * @param int $parentId
  *   ID of the note to start from.
  * @param int $maxDepth
  *   Maximum number of levels to descend into the tree; if not given, will include all descendents.
  * @param bool $snippet
  *   If TRUE, returned values will be pre-formatted for display in a table of notes.
  * @param array $tree
  *   (Reference) Variable to store all found descendents.
  * @param int $depth
  *   Depth of current iteration within the descendent tree (used for comparison against maxDepth).
  *
  * @return array
  *   Nested associative array beginning with direct children of given note.
  */
 private static function buildNoteTree($parentId, $maxDepth = 0, $snippet = FALSE, &$tree = array(), $depth = 0)
 {
     if ($maxDepth && $depth > $maxDepth) {
         return FALSE;
     }
     // get direct children of given parentId note
     $note = new CRM_Core_DAO_Note();
     $note->entity_table = 'civicrm_note';
     $note->entity_id = $parentId;
     $note->orderBy('modified_date asc');
     $note->find();
     while ($note->fetch()) {
         // foreach child, call this function, unless the child is private/hidden
         if (!self::getNotePrivacyHidden($note)) {
             CRM_Core_DAO::storeValues($note, $tree[$note->id]);
             // get name of user that created this note
             $contact = new CRM_Contact_DAO_Contact();
             $createdById = $note->contact_id;
             $contact->id = $createdById;
             $contact->find();
             $contact->fetch();
             $tree[$note->id]['createdBy'] = $contact->display_name;
             $tree[$note->id]['createdById'] = $createdById;
             $tree[$note->id]['modified_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
             // paper icon view for attachments part
             $paperIconAttachmentInfo = CRM_Core_BAO_File::paperIconAttachment('civicrm_note', $note->id);
             $tree[$note->id]['attachment'] = $paperIconAttachmentInfo ? implode('', $paperIconAttachmentInfo) : '';
             if ($snippet) {
                 $tree[$note->id]['note'] = nl2br($tree[$note->id]['note']);
                 $tree[$note->id]['note'] = smarty_modifier_mb_truncate($tree[$note->id]['note'], 80, '...', TRUE);
                 CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
             }
             self::buildNoteTree($note->id, $maxDepth, $snippet, $tree[$note->id]['child'], $depth + 1);
         }
     }
     return $tree;
 }
Example #21
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 bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array('version' => 3);
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'participant_register_date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
                 $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
             }
         }
     }
     if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
         if (!empty($params['event_id'])) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $indieFields = CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant');
             if ($dao->find(TRUE)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $participantValues = array();
                 //@todo calling api functions directly is not supported
                 $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Import_Parser::ERROR;
                 }
                 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
                 if (!empty($formatted['fee_level'])) {
                     $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id);
                     CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
                 }
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Import_Parser::VALID;
             } else {
                 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $formatValues['version'] = 3;
         $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $formatted['version'] = 3;
                     $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = '';
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($formatValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Import_Parser::DUPLICATE;
             } elseif ($newParticipant['error_message']) {
                 array_unshift($values, $newParticipant['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
             return CRM_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
     }
     return CRM_Import_Parser::VALID;
 }
Example #22
0
 /**
  * Get a list of Assignments matching the params, where each param key is:
  *  1. the key of a field in civicrm_activity
  *     except for activity_type_id and activity_duration
  *  2. the key of a custom field on the activity
  *     (volunteer_need_id, time_scheduled, time_completed)
  *  3. the key of a field in civicrm_contact
  *  4. project_id
  *
  * @param array $params
  * @return array of CRM_Volunteer_BAO_Project objects
  */
 static function retrieve(array $params)
 {
     $activity_fields = CRM_Activity_DAO_Activity::fields();
     $contact_fields = CRM_Contact_DAO_Contact::fields();
     $custom_fields = self::getCustomFields();
     $foreign_fields = array('project_id', 'target_contact_id');
     // This is the "real" id
     $activity_fields['id'] = $activity_fields['activity_id'];
     unset($activity_fields['activity_id']);
     // enforce restrictions on parameters
     $allowed_params = array_flip(array_merge(array_keys($activity_fields), array_keys($contact_fields), array_keys($custom_fields), $foreign_fields));
     unset($allowed_params['activity_type_id']);
     unset($allowed_params['activity_duration']);
     $filtered_params = array_intersect_key($params, $allowed_params);
     $custom_group = self::getCustomGroup();
     $customTableName = $custom_group['table_name'];
     foreach ($custom_fields as $name => $field) {
         $selectClause[] = "{$customTableName}.{$field['column_name']} AS {$name}";
     }
     $customSelect = implode(', ', $selectClause);
     $activityContactTypes = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContactTypes);
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContactTypes);
     $volunteerStatus = CRM_Activity_BAO_Activity::buildOptions('status_id', 'validate');
     $available = CRM_Utils_Array::key('Available', $volunteerStatus);
     $scheduled = CRM_Utils_Array::key('Scheduled', $volunteerStatus);
     $placeholders = array(1 => array($assigneeID, 'Integer'), 2 => array(self::volunteerActivityTypeId(), 'Integer'), 3 => array($scheduled, 'Integer'), 4 => array($available, 'Integer'), 5 => array($targetID, 'Integer'));
     $i = count($placeholders) + 1;
     $where = array();
     $whereClause = NULL;
     foreach ($filtered_params as $key => $value) {
         if (CRM_Utils_Array::value($key, $activity_fields)) {
             $dataType = CRM_Utils_Type::typeToString($activity_fields[$key]['type']);
             $fieldName = $activity_fields[$key]['name'];
             $tableName = CRM_Activity_DAO_Activity::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $contact_fields)) {
             $dataType = CRM_Utils_Type::typeToString($contact_fields[$key]['type']);
             $fieldName = $contact_fields[$key]['name'];
             $tableName = CRM_Contact_DAO_Contact::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $custom_fields)) {
             $dataType = $custom_fields[$key]['data_type'];
             $fieldName = $custom_fields[$key]['column_name'];
             $tableName = $customTableName;
         } elseif ($key == 'project_id') {
             $dataType = 'Int';
             $fieldName = 'id';
             $tableName = CRM_Volunteer_DAO_Project::$_tableName;
         } elseif ($key == 'target_contact_id') {
             $dataType = 'Int';
             $fieldName = 'contact_id';
             $tableName = 'tgt';
             // this is an alias for civicrm_activity_contact
         }
         $where[] = "{$tableName}.{$fieldName} = %{$i}";
         $placeholders[$i] = array($value, $dataType);
         $i++;
     }
     if (count($where)) {
         $whereClause = 'AND ' . implode("\nAND ", $where);
     }
     $query = "\n      SELECT\n        civicrm_activity.*,\n        assignee.contact_id AS assignee_contact_id,\n        {$customSelect},\n        civicrm_volunteer_need.start_time,\n        civicrm_volunteer_need.is_flexible,\n        civicrm_volunteer_need.role_id,\n        assignee_contact.sort_name AS assignee_sort_name,\n        assignee_contact.display_name AS assignee_display_name,\n        assignee_phone.phone AS assignee_phone,\n        assignee_phone.phone_ext AS assignee_phone_ext,\n        assignee_email.email AS assignee_email,\n        -- begin target contact fields\n        tgt.contact_id AS target_contact_id,\n        tgt_contact.sort_name AS target_sort_name,\n        tgt_contact.display_name AS target_display_name,\n        tgt_phone.phone AS target_phone,\n        tgt_phone.phone_ext AS target_phone_ext,\n        tgt_email.email AS target_email\n        -- end target contact fields\n      FROM civicrm_activity\n      INNER JOIN civicrm_activity_contact assignee\n        ON (\n          assignee.activity_id = civicrm_activity.id\n          AND assignee.record_type_id = %1\n        )\n      INNER JOIN civicrm_contact assignee_contact\n        ON assignee.contact_id = assignee_contact.id\n      LEFT JOIN civicrm_email assignee_email\n        ON assignee_email.contact_id = assignee_contact.id AND assignee_email.is_primary = 1\n      LEFT JOIN civicrm_phone assignee_phone\n        ON assignee_phone.contact_id = assignee_contact.id AND assignee_phone.is_primary = 1\n      -- begin target contact joins\n      LEFT JOIN civicrm_activity_contact tgt\n        ON (\n          tgt.activity_id = civicrm_activity.id\n          AND tgt.record_type_id = %5\n        )\n      LEFT JOIN civicrm_contact tgt_contact\n        ON tgt.contact_id = tgt_contact.id\n      LEFT JOIN civicrm_email tgt_email\n        ON tgt_email.contact_id = tgt_contact.id AND tgt_email.is_primary = 1\n      LEFT JOIN civicrm_phone tgt_phone\n        ON tgt_phone.contact_id = tgt_contact.id AND tgt_phone.is_primary = 1\n      -- end target contact joins\n      INNER JOIN {$customTableName}\n        ON ({$customTableName}.entity_id = civicrm_activity.id)\n      INNER JOIN civicrm_volunteer_need\n        ON (civicrm_volunteer_need.id = {$customTableName}.{$custom_fields['volunteer_need_id']['column_name']})\n      INNER JOIN civicrm_volunteer_project\n        ON (civicrm_volunteer_project.id = civicrm_volunteer_need.project_id)\n      WHERE civicrm_activity.activity_type_id = %2\n      AND civicrm_activity.status_id IN (%3, %4 )\n      {$whereClause}\n    ";
     $dao = CRM_Core_DAO::executeQuery($query, $placeholders);
     $rows = array();
     while ($dao->fetch()) {
         $rows[$dao->id] = $dao->toArray();
     }
     /*
      * For clarity we want the fields associated with each contact prefixed with
      * the contact type (e.g., target_phone). For backwards compatibility,
      * however, we want the fields associated with each assignee contact to be
      * accessible sans prefix. Eventually we should deprecate the non-prefixed
      * field names.
      */
     foreach ($rows as $id => $fields) {
         foreach ($fields as $key => $value) {
             if (substr($key, 0, 9) == 'assignee_') {
                 $rows[$id][substr($key, 9)] = $value;
             }
         }
     }
     return $rows;
 }
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 function buildQuickForm()
 {
     if ($this->_action & CRM_CORE_ACTION_DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     $this->addElement('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId));
     $this->addElement('text', 'name', ts('Find Target Contact'));
     $this->addElement('date', 'start_date', ts('Start Date'), CRM_Core_SelectValues::date('relative'));
     $this->addElement('date', 'end_date', ts('End Date'), CRM_Core_SelectValues::date('relative'));
     $searchRows = $this->get('searchRows');
     $searchCount = $this->get('searchCount');
     $duplicateRelationship = $this->get('duplicateRelationship');
     if ($searchRows) {
         $checkBoxes = array();
         foreach ($searchRows as $id => $row) {
             $checkBoxes[$id] = $this->createElement('checkbox', $id, null, '');
         }
         $this->addGroup($checkBoxes, 'contact_check');
         $this->assign('searchRows', $searchRows);
     }
     $this->assign('duplicateRelationship', $duplicateRelationship);
     $this->assign('searchCount', $searchCount);
     $this->assign('searchDone', $this->get('searchDone'));
     if ($this->get('contact_type')) {
         $this->assign('contact_type', $this->get('contact_type'));
         $this->assign('contact_type_display', CRM_Contact_DAO_Contact::tsEnum('contact_type', $this->get('contact_type')));
     }
     $this->addElement('submit', $this->getButtonName('refresh'), ts('Search'), array('class' => 'form-submit'));
     $this->addElement('submit', $this->getButtonName('cancel'), ts('Cancel'), array('class' => 'form-submit'));
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save Relationship'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
 }
 /**
  * Combine all the exportable fields from the lower levels object.
  *
  * Currently we are using importable fields as exportable fields
  *
  * @param int|string $contactType contact Type
  * @param bool $status
  *   True while exporting primary contacts.
  * @param bool $export
  *   True when used during export.
  * @param bool $search
  *   True when used during search, might conflict with export param?.
  *
  * @param bool $withMultiRecord
  *
  * @return array
  *   array of exportable Fields
  */
 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE)
 {
     if (empty($contactType)) {
         $contactType = 'All';
     }
     $cacheKeyString = "exportableFields {$contactType}";
     $cacheKeyString .= $export ? '_1' : '_0';
     $cacheKeyString .= $status ? '_1' : '_0';
     $cacheKeyString .= $search ? '_1' : '_0';
     //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
     //calculates custom fields takes into account the logged in user & caches that for all users
     //as an interim fix we will cache the fields by contact
     $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
     if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
         if (!self::$_exportableFields) {
             self::$_exportableFields = array();
         }
         // check if we can retrieve from database cache
         $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
         if (!$fields) {
             $fields = CRM_Contact_DAO_Contact::export();
             // The fields are meant for contact types.
             if (in_array($contactType, array('Individual', 'Household', 'Organization', 'All'))) {
                 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
             }
             // add current employer for individuals
             $fields = array_merge($fields, array('current_employer' => array('name' => 'organization_name', 'title' => ts('Current Employer'))));
             $locationType = array('location_type' => array('name' => 'location_type', 'where' => 'civicrm_location_type.name', 'title' => ts('Location Type')));
             $IMProvider = array('im_provider' => array('name' => 'im_provider', 'where' => 'civicrm_im.provider_id', 'title' => ts('IM Provider')));
             $locationFields = array_merge($locationType, CRM_Core_DAO_Address::export(), CRM_Core_DAO_Phone::export(), CRM_Core_DAO_Email::export(), $IMProvider, CRM_Core_DAO_IM::export(TRUE), CRM_Core_DAO_OpenID::export());
             $locationFields = array_merge($locationFields, CRM_Core_BAO_CustomField::getFieldsForImport('Address'));
             foreach ($locationFields as $key => $field) {
                 $locationFields[$key]['hasLocationType'] = TRUE;
             }
             $fields = array_merge($fields, $locationFields);
             //add world region
             $fields = array_merge($fields, CRM_Core_DAO_Worldregion::export());
             $fields = array_merge($fields, CRM_Contact_DAO_Contact::export());
             //website fields
             $fields = array_merge($fields, CRM_Core_DAO_Website::export());
             if ($contactType != 'All') {
                 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord));
             } else {
                 foreach (array('Individual', 'Household', 'Organization') as $type) {
                     $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord));
                 }
             }
             //fix for CRM-791
             if ($export) {
                 $fields = array_merge($fields, array('groups' => array('title' => ts('Group(s)'), 'name' => 'groups'), 'tags' => array('title' => ts('Tag(s)'), 'name' => 'tags'), 'notes' => array('title' => ts('Note(s)'), 'name' => 'notes')));
             } else {
                 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'), 'name' => 'group'), 'tag' => array('title' => ts('Tag(s)'), 'name' => 'tag'), 'note' => array('title' => ts('Note(s)'), 'name' => 'note')));
             }
             //Sorting fields in alphabetical order(CRM-1507)
             foreach ($fields as $k => $v) {
                 $sortArray[$k] = CRM_Utils_Array::value('title', $v);
             }
             $fields = array_merge($sortArray, $fields);
             //unset the field which are not related to their contact type.
             if ($contactType != 'All') {
                 $commonValues = array('Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom'), 'Household' => array('first_name', 'middle_name', 'last_name', 'formal_title', 'job_title', 'gender_id', 'prefix_id', 'suffix_id', 'birth_date', 'organization_name', 'legal_name', 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased', 'deceased_date', 'current_employer', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'prefix_id', 'suffix_id'), 'Organization' => array('first_name', 'middle_name', 'last_name', 'formal_title', 'job_title', 'gender_id', 'prefix_id', 'suffix_id', 'birth_date', 'household_name', 'email_greeting_custom', 'postal_greeting_custom', 'prefix_id', 'suffix_id', 'gender_id', 'addressee_custom', 'is_deceased', 'deceased_date', 'current_employer'));
                 foreach ($commonValues[$contactType] as $value) {
                     unset($fields[$value]);
                 }
             }
             CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
         }
         self::$_exportableFields[$cacheKeyString] = $fields;
     }
     if (!$status) {
         $fields = self::$_exportableFields[$cacheKeyString];
     } else {
         $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))), self::$_exportableFields[$cacheKeyString]);
     }
     return $fields;
 }
 private function addParticipant()
 {
     $contact = new CRM_Contact_DAO_Contact();
     $contact->query("SELECT id FROM civicrm_contact");
     while ($contact->fetch()) {
         $contacts[] = $contact->id;
     }
     shuffle($contacts);
     $randomContacts = array_slice($contacts, 20, 50);
     $participant = "\nINSERT INTO civicrm_participant\n        (contact_id, event_id, status_id, role_id, register_date, source, fee_level, is_test, fee_amount, fee_currency)\nVALUES\n        ( " . $randomContacts[0] . ", 1, 1, 1, '2009-01-21', 'Check', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[1] . ", 2, 2, 2, '2008-05-07', 'Credit Card', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[2] . ", 3, 3, 3, '2008-05-05', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD') ,\n        ( " . $randomContacts[3] . ", 1, 4, 4, '2008-10-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[4] . ", 2, 1, 1, '2008-01-10', 'Check', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[5] . ", 3, 2, 2, '2008-03-05', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[6] . ", 1, 3, 3, '2009-07-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[7] . ", 2, 4, 4, '2009-03-07', 'Credit Card', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[8] . ", 3, 1, 1, '2008-02-05', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[9] . ", 1, 2, 2, '2008-02-01', 'Check', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[10] . ", 2, 3, 3, '2009-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[11] . ", 3, 4, 4, '2009-03-06', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[12] . ", 1, 1, 2, '2008-06-04', 'Credit Card', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[13] . ", 2, 2, 3, '2008-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[14] . ", 3, 4, 1, '2008-07-04', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[15] . ", 1, 4, 2, '2009-01-21', 'Credit Card', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[16] . ", 2, 2, 3, '2008-01-10', 'Credit Card', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[17] . ", 3, 3, 1, '2009-03-05', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[18] . ", 1, 2, 1, '2008-10-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[19] . ", 2, 4, 1, '2009-01-10', 'Credit Card', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[20] . ", 3, 1, 4, '2008-03-25', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[21] . ", 1, 2, 3, '2009-10-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[22] . ", 2, 4, 1, '2008-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[23] . ", 3, 3, 1, '2008-03-11', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[24] . ", 3, 2, 2, '2008-04-05', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[25] . ", 1, 1, 1, '2009-01-21', 'Check', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[26] . ", 2, 2, 2, '2008-05-07', 'Credit Card', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[27] . ", 3, 3, 3, '2009-12-12', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[28] . ", 1, 4, 4, '2009-12-13', 'Credit Card', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[29] . ", 2, 1, 1, '2009-12-14', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[30] . ", 3, 2, 2, '2009-12-15', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[31] . ", 1, 3, 3, '2009-07-21', 'Check', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[32] . ", 2, 4, 4, '2009-03-07', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[33] . ", 3, 1, 1, '2009-12-15', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[34] . ", 1, 2, 2, '2009-12-13', 'Direct Transfer', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[35] . ", 2, 3, 3, '2009-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[36] . ", 3, 4, 4, '2009-03-06', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[37] . ", 1, 1, 2, '2009-12-13', 'Direct Transfer', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[38] . ", 2, 2, 3, '2008-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[39] . ", 3, 4, 1, '2009-12-14', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[40] . ", 1, 4, 2, '2009-01-21', 'Credit Card', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[41] . ", 2, 2, 3, '2009-12-15', 'Credit Card', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[42] . ", 3, 3, 1, '2009-03-05', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[43] . ", 1, 2, 1, '2009-12-13', 'Direct Transfer', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[44] . ", 2, 4, 1, '2009-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[45] . ", 3, 1, 4, '2009-12-13', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[46] . ", 1, 2, 3, '2009-10-21', 'Credit Card', 'Single', 0, 50, 'USD'),\n        ( " . $randomContacts[47] . ", 2, 4, 1, '2009-12-10', 'Credit Card', 'Soprano', 0, 50, 'USD'),\n        ( " . $randomContacts[48] . ", 3, 3, 1, '2009-03-11', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),\n        ( " . $randomContacts[49] . ", 3, 2, 2, '2009-04-05', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD');\n";
     $this->_query($participant);
     $query = "\nINSERT INTO civicrm_activity\n    (source_record_id, activity_type_id, subject, activity_date_time, duration, location, phone_id, phone_number, details, priority_id,parent_id, is_test, status_id)\nVALUES\n    (01, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (02, 5, 'NULL', '2008-05-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (03, 5, 'NULL', '2008-05-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (04, 5, 'NULL', '2008-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (05, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (06, 5, 'NULL', '2008-03-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (07, 5, 'NULL', '2009-07-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (08, 5, 'NULL', '2009-03-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (09, 5, 'NULL', '2008-02-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (10, 5, 'NULL', '2008-02-01 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (11, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (12, 5, 'NULL', '2009-03-06 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (13, 5, 'NULL', '2008-06-04 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (14, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (15, 5, 'NULL', '2008-07-04 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (16, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (17, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (18, 5, 'NULL', '2009-03-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (19, 5, 'NULL', '2008-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (20, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (21, 5, 'NULL', '2008-03-25 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (22, 5, 'NULL', '2009-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (23, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (24, 5, 'NULL', '2008-03-11 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (25, 5, 'NULL', '2008-04-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (26, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (27, 5, 'NULL', '2008-05-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (28, 5, 'NULL', '2009-12-12 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (29, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (30, 5, 'NULL', '2009-12-14 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (31, 5, 'NULL', '2009-12-15 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (32, 5, 'NULL', '2009-07-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (33, 5, 'NULL', '2009-03-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (34, 5, 'NULL', '2009-12-15 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (35, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (36, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (37, 5, 'NULL', '2009-03-06 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (38, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (39, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (40, 5, 'NULL', '2009-12-14 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (41, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (42, 5, 'NULL', '2009-12-15 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (43, 5, 'NULL', '2009-03-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (44, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (45, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (46, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (47, 5, 'NULL', '2009-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (48, 5, 'NULL', '2009-12-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (49, 5, 'NULL', '2009-03-11 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),\n    (50, 5, 'NULL', '2009-04-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )\n    ";
     $this->_query($query);
     $activityContact = "\nINSERT INTO civicrm_activity_contact\n  (contact_id, activity_id, record_type_id)\nVALUES\n";
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $currentActivityID = CRM_Core_DAO::singleValueQuery("SELECT MAX(id) FROM civicrm_activity");
     $currentActivityID -= 50;
     $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
     for ($i = 0; $i < 50; $i++) {
         $currentActivityID++;
         $activityContact .= "({$randomContacts[$i]}, {$currentActivityID}, {$sourceID})";
         if ($i != 49) {
             $activityContact .= ", ";
         }
     }
     $this->_query($activityContact);
 }
Example #26
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)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Member_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     //assign join date equal to start date if join date is not provided
     if (!$params['join_date'] && $params['membership_start_date']) {
         $params['join_date'] = $params['membership_start_date'];
     }
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'join_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage);
                     }
                     break;
                 case 'membership_start_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                     }
                     break;
                 case 'membership_end_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage);
                     }
                     break;
                 case 'is_override':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID][2] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID][2] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Member/DAO/Membership.php';
         $tempIndieFields =& CRM_Member_DAO_Membership::import();
         $indieFields = $tempIndieFields;
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_membership_formatted_param($formatValues, $formatted, true);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Member_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Member_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Membership');
     } else {
         //fix for CRM-2219 Update Membership
         // onDuplicate == CRM_Member_Import_Parser::DUPLICATE_UPDATE
         if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
             array_unshift($values, "Required parameter missing: Status");
             return CRM_Member_Import_Parser::ERROR;
         }
         if ($formatValues['membership_id']) {
             require_once 'CRM/Member/BAO/Membership.php';
             $dao = new CRM_Member_BAO_Membership();
             $dao->id = $formatValues['membership_id'];
             $dates = array('join_date', 'start_date', 'end_date');
             foreach ($dates as $v) {
                 if (!$formatted[$v]) {
                     $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                 }
             }
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
             if ($dao->find(true)) {
                 $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                 $newMembership =& CRM_Member_BAO_Membership::create($formatted, $ids, true);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['is_error'] . " for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     $this->_newMemberships[] = $newMembership->id;
                     return CRM_Member_Import_Parser::VALID;
                 }
             } else {
                 array_unshift($values, "Matching Membership record not found for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
     }
     //Format dates
     $startDate = CRM_Utils_Date::customFormat($formatted['start_date'], '%Y-%m-%d');
     $endDate = CRM_Utils_Date::customFormat($formatted['end_date'], '%Y-%m-%d');
     $joinDate = CRM_Utils_Date::customFormat($formatted['join_date'], '%Y-%m-%d');
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The membership was not imported");
                 return CRM_Member_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 //fix for CRM-1924
                 require_once 'CRM/Member/BAO/MembershipStatus.php';
                 require_once 'CRM/Member/BAO/MembershipType.php';
                 require_once 'CRM/Member/PseudoConstant.php';
                 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                 self::formattedDates($calcDates, $formatted);
                 //fix for CRM-3570, exclude the statuses those having is_admin = 1
                 //now user can import is_admin if is override is true.
                 $excludeIsAdmin = false;
                 if (!CRM_Utils_Array::value('is_override', $formatted)) {
                     $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
                 }
                 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
                 if (!$formatted['status_id']) {
                     $formatted['status_id'] = $calcStatus['id'];
                 } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                     if (empty($calcStatus)) {
                         array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported.");
                         return CRM_Member_Import_Parser::ERROR;
                     } else {
                         if ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported.");
                             return CRM_Member_Import_Parser::ERROR;
                         }
                     }
                 }
                 $newMembership = civicrm_contact_membership_create($formatted);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['error_message']);
                     return CRM_Member_Import_Parser::ERROR;
                 }
                 $this->_newMemberships[] = $newMembership['id'];
                 return CRM_Member_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Member_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
         //to calculate dates
         require_once 'CRM/Member/BAO/MembershipType.php';
         $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
         self::formattedDates($calcDates, $formatted);
         //end of date calculation part
         //fix for CRM-3570, exclude the statuses those having is_admin = 1
         //now user can import is_admin if is override is true.
         $excludeIsAdmin = false;
         if (!CRM_Utils_Array::value('is_override', $formatted)) {
             $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
         }
         require_once 'CRM/Member/BAO/MembershipStatus.php';
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
         if (!$formatted['status_id']) {
             $formatted['status_id'] = $calcStatus['id'];
         } else {
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     if ($formatted['status_id'] != $calcStatus['id']) {
                         //Status Hold" is either NOT mapped or is FALSE
                         array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported.");
                         return CRM_Member_Import_Parser::ERROR;
                     }
                 }
             }
         }
         $newMembership = civicrm_contact_membership_create($formatted);
         if (civicrm_error($newMembership)) {
             array_unshift($values, $newMembership['error_message']);
             return CRM_Member_Import_Parser::ERROR;
         }
         $this->_newMemberships[] = $newMembership['id'];
         return CRM_Member_Import_Parser::VALID;
     }
 }
Example #27
0
 /**
  * Updates contacts affected by the option value passed.
  *
  * @param int $optionValueId
  *   The option value id.
  * @param int $action
  *   The action describing whether prefix/suffix was UPDATED or DELETED.
  *
  * @return bool
  */
 public static function updateRecords(&$optionValueId, $action)
 {
     //finding group name
     $optionValue = new CRM_Core_DAO_OptionValue();
     $optionValue->id = $optionValueId;
     $optionValue->find(TRUE);
     $optionGroup = new CRM_Core_DAO_OptionGroup();
     $optionGroup->id = $optionValue->option_group_id;
     $optionGroup->find(TRUE);
     // group name
     $gName = $optionGroup->name;
     // value
     $value = $optionValue->value;
     // get the proper group name & affected field name
     // todo: this may no longer be needed for individuals - check inputs
     $individuals = array('gender' => 'gender_id', 'individual_prefix' => 'prefix_id', 'individual_suffix' => 'suffix_id', 'communication_style' => 'communication_style_id');
     $contributions = array('payment_instrument' => 'payment_instrument_id');
     $activities = array('activity_type' => 'activity_type_id');
     $participant = array('participant_role' => 'role_id');
     $eventType = array('event_type' => 'event_type_id');
     $aclRole = array('acl_role' => 'acl_role_id');
     $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
     $fieldName = '';
     foreach ($all as $name => $id) {
         if ($gName == $name) {
             $fieldName = $id;
         }
     }
     if ($fieldName == '') {
         return TRUE;
     }
     if (array_key_exists($gName, $individuals)) {
         $contactDAO = new CRM_Contact_DAO_Contact();
         $contactDAO->{$fieldName} = $value;
         $contactDAO->find();
         while ($contactDAO->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contact = new CRM_Contact_DAO_Contact();
                 $contact->id = $contactDAO->id;
                 $contact->find(TRUE);
                 // make sure dates doesn't get reset
                 $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
                 $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
                 $contact->{$fieldName} = 'NULL';
                 $contact->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $contributions)) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->{$fieldName} = $value;
         $contribution->find();
         while ($contribution->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contribution->{$fieldName} = 'NULL';
                 $contribution->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $activities)) {
         $activity = new CRM_Activity_DAO_Activity();
         $activity->{$fieldName} = $value;
         $activity->find();
         while ($activity->fetch()) {
             $activity->delete();
         }
         return TRUE;
     }
     //delete participant role, type and event type option value
     if (array_key_exists($gName, $participant)) {
         $participantValue = new CRM_Event_DAO_Participant();
         $participantValue->{$fieldName} = $value;
         if ($participantValue->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete event type option value
     if (array_key_exists($gName, $eventType)) {
         $event = new CRM_Event_DAO_Event();
         $event->{$fieldName} = $value;
         if ($event->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete acl_role option value
     if (array_key_exists($gName, $aclRole)) {
         $entityRole = new CRM_ACL_DAO_EntityRole();
         $entityRole->{$fieldName} = $value;
         $aclDAO = new CRM_ACL_DAO_ACL();
         $aclDAO->entity_id = $value;
         if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
 }
 /**
  * note that $job_id is used only as a variable in the temp table construction
  * and does not play a role in the queries generated
  * @param int $job_id
  *   (misnomer) a nonce value used to name temporary tables.
  * @param int $mailing_id
  * @param bool $storeRecipients
  * @param bool $dedupeEmail
  * @param null $mode
  *
  * @return CRM_Mailing_Event_BAO_Queue|string
  */
 public static function getRecipients($job_id, $mailing_id = NULL, $storeRecipients = FALSE, $dedupeEmail = FALSE, $mode = NULL)
 {
     $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $mg = CRM_Mailing_DAO_MailingGroup::getTableName();
     $eq = CRM_Mailing_Event_DAO_Queue::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     if ($mode == 'sms') {
         $phone = CRM_Core_DAO_Phone::getTableName();
     }
     $contact = CRM_Contact_DAO_Contact::getTableName();
     $group = CRM_Contact_DAO_Group::getTableName();
     $g2contact = CRM_Contact_DAO_GroupContact::getTableName();
     $m = new CRM_Mailing_DAO_Mailing();
     $m->id = $mailing_id;
     $m->find(TRUE);
     $email_selection_method = $m->email_selection_method;
     $location_type_id = $m->location_type_id;
     // Note: When determining the ORDER that results are returned, it's
     // the record that comes last that counts. That's because we are
     // INSERT'ing INTO a table with a primary id so that last record
     // over writes any previous record.
     switch ($email_selection_method) {
         case 'location-exclude':
             $location_filter = "({$email}.location_type_id != {$location_type_id})";
             // If there is more than one email that doesn't match the location,
             // prefer the one marked is_bulkmail, followed by is_primary.
             $order_by = "ORDER BY {$email}.is_bulkmail, {$email}.is_primary";
             break;
         case 'location-only':
             $location_filter = "({$email}.location_type_id = {$location_type_id})";
             // If there is more than one email of the desired location, prefer
             // the one marked is_bulkmail, followed by is_primary.
             $order_by = "ORDER BY {$email}.is_bulkmail, {$email}.is_primary";
             break;
         case 'location-prefer':
             $location_filter = "({$email}.is_bulkmail = 1 OR {$email}.is_primary = 1 OR {$email}.location_type_id = {$location_type_id})";
             // ORDER BY is more complicated because we have to set an arbitrary
             // order that prefers the location that we want. We do that using
             // the FIELD function. For more info, see:
             // https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
             // We assign the location type we want the value "1" by putting it
             // in the first position after we name the field. All other location
             // types are left out, so they will be assigned the value 0. That
             // means, they will all be equally tied for first place, with our
             // location being last.
             $order_by = "ORDER BY FIELD({$email}.location_type_id, {$location_type_id}), {$email}.is_bulkmail, {$email}.is_primary";
             break;
         case 'automatic':
             // fall through to default
         // fall through to default
         default:
             $location_filter = "({$email}.is_bulkmail = 1 OR {$email}.is_primary = 1)";
             $order_by = "ORDER BY {$email}.is_bulkmail";
     }
     /* Create a temp table for contact exclusion */
     $mailingGroup->query("CREATE TEMPORARY TABLE X_{$job_id}\n            (contact_id int primary key)\n            ENGINE=HEAP");
     /* Add all the members of groups excluded from this mailing to the temp
      * table */
     $excludeSubGroup = "INSERT INTO        X_{$job_id} (contact_id)\n                    SELECT  DISTINCT    {$g2contact}.contact_id\n                    FROM                {$g2contact}\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id AND {$mg}.entity_table = '{$group}'\n                    WHERE\n                                        {$mg}.mailing_id = {$mailing_id}\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$mg}.group_type = 'Exclude'";
     $mailingGroup->query($excludeSubGroup);
     /* Add all unsubscribe members of base group from this mailing to the temp
      * table */
     $unSubscribeBaseGroup = "INSERT INTO        X_{$job_id} (contact_id)\n                    SELECT  DISTINCT    {$g2contact}.contact_id\n                    FROM                {$g2contact}\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id AND {$mg}.entity_table = '{$group}'\n                    WHERE\n                                        {$mg}.mailing_id = {$mailing_id}\n                        AND             {$g2contact}.status = 'Removed'\n                        AND             {$mg}.group_type = 'Base'";
     $mailingGroup->query($unSubscribeBaseGroup);
     /* Add all the (intended) recipients of an excluded prior mailing to
      * the temp table */
     $excludeSubMailing = "INSERT IGNORE INTO X_{$job_id} (contact_id)\n                    SELECT  DISTINCT    {$eq}.contact_id\n                    FROM                {$eq}\n                    INNER JOIN          {$job}\n                            ON          {$eq}.job_id = {$job}.id\n                    INNER JOIN          {$mg}\n                            ON          {$job}.mailing_id = {$mg}.entity_id AND {$mg}.entity_table = '{$mailing}'\n                    WHERE\n                                        {$mg}.mailing_id = {$mailing_id}\n                        AND             {$mg}.group_type = 'Exclude'";
     $mailingGroup->query($excludeSubMailing);
     // get all the saved searches AND hierarchical groups
     // and load them in the cache
     $sql = "\nSELECT     {$group}.id, {$group}.cache_date, {$group}.saved_search_id, {$group}.children\nFROM       {$group}\nINNER JOIN {$mg} ON {$mg}.entity_id = {$group}.id\nWHERE      {$mg}.entity_table = '{$group}'\n  AND      {$mg}.group_type = 'Exclude'\n  AND      {$mg}.mailing_id = {$mailing_id}\n  AND      ( saved_search_id != 0\n   OR        saved_search_id IS NOT NULL\n   OR        children IS NOT NULL )\n";
     $groupDAO = CRM_Core_DAO::executeQuery($sql);
     while ($groupDAO->fetch()) {
         if ($groupDAO->cache_date == NULL) {
             CRM_Contact_BAO_GroupContactCache::load($groupDAO);
         }
         $smartGroupExclude = "\nINSERT IGNORE INTO X_{$job_id} (contact_id)\nSELECT c.contact_id\nFROM   civicrm_group_contact_cache c\nWHERE  c.group_id = {$groupDAO->id}\n";
         $mailingGroup->query($smartGroupExclude);
     }
     $tempColumn = 'email_id';
     if ($mode == 'sms') {
         $tempColumn = 'phone_id';
     }
     /* Get all the group contacts we want to include */
     $mailingGroup->query("CREATE TEMPORARY TABLE I_{$job_id}\n            ({$tempColumn} int, contact_id int primary key)\n            ENGINE=HEAP");
     /* Get the group contacts, but only those which are not in the
      * exclusion temp table */
     $query = "REPLACE INTO       I_{$job_id} (email_id, contact_id)\n\n                    SELECT DISTINCT     {$email}.id as email_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$email}\n                    INNER JOIN          {$contact}\n                            ON          {$email}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                                AND     {$mg}.entity_table = '{$group}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$mg}.search_id IS NULL\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_email = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$location_filter}\n                        AND             {$email}.email IS NOT NULL\n                        AND             {$email}.email != ''\n                        AND             {$email}.on_hold = 0\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null\n                    {$order_by}";
     if ($mode == 'sms') {
         $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
         $query = "REPLACE INTO       I_{$job_id} (phone_id, contact_id)\n\n                    SELECT DISTINCT     {$phone}.id as phone_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$phone}\n                    INNER JOIN          {$contact}\n                            ON          {$phone}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                                AND     {$mg}.entity_table = '{$group}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$mg}.search_id IS NULL\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_sms = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$phone}.phone_type_id = {$phoneTypes['Mobile']}\n                        AND             {$phone}.phone IS NOT NULL\n                        AND             {$phone}.phone != ''\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null";
     }
     $mailingGroup->query($query);
     /* Query prior mailings */
     $query = "REPLACE INTO       I_{$job_id} (email_id, contact_id)\n                    SELECT DISTINCT     {$email}.id as email_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$email}\n                    INNER JOIN          {$contact}\n                            ON          {$email}.contact_id = {$contact}.id\n                    INNER JOIN          {$eq}\n                            ON          {$eq}.contact_id = {$contact}.id\n                    INNER JOIN          {$job}\n                            ON          {$eq}.job_id = {$job}.id\n                    INNER JOIN          {$mg}\n                            ON          {$job}.mailing_id = {$mg}.entity_id AND {$mg}.entity_table = '{$mailing}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$contact}.do_not_email = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$location_filter}\n                        AND             {$email}.on_hold = 0\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null\n                    {$order_by}";
     if ($mode == 'sms') {
         $query = "REPLACE INTO       I_{$job_id} (phone_id, contact_id)\n                    SELECT DISTINCT     {$phone}.id as phone_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$phone}\n                    INNER JOIN          {$contact}\n                            ON          {$phone}.contact_id = {$contact}.id\n                    INNER JOIN          {$eq}\n                            ON          {$eq}.contact_id = {$contact}.id\n                    INNER JOIN          {$job}\n                            ON          {$eq}.job_id = {$job}.id\n                    INNER JOIN          {$mg}\n                            ON          {$job}.mailing_id = {$mg}.entity_id AND {$mg}.entity_table = '{$mailing}'\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                       ({$mg}.group_type = 'Include')\n                        AND             {$contact}.do_not_sms = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$phone}.phone_type_id = {$phoneTypes['Mobile']}\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null";
     }
     $mailingGroup->query($query);
     $sql = "\nSELECT     {$group}.id, {$group}.cache_date, {$group}.saved_search_id, {$group}.children\nFROM       {$group}\nINNER JOIN {$mg} ON {$mg}.entity_id = {$group}.id\nWHERE      {$mg}.entity_table = '{$group}'\n  AND      {$mg}.group_type = 'Include'\n  AND      {$mg}.search_id IS NULL\n  AND      {$mg}.mailing_id = {$mailing_id}\n  AND      ( saved_search_id != 0\n   OR        saved_search_id IS NOT NULL\n   OR        children IS NOT NULL )\n";
     $groupDAO = CRM_Core_DAO::executeQuery($sql);
     while ($groupDAO->fetch()) {
         if ($groupDAO->cache_date == NULL) {
             CRM_Contact_BAO_GroupContactCache::load($groupDAO);
         }
         $smartGroupInclude = "\nREPLACE INTO I_{$job_id} (email_id, contact_id)\nSELECT     civicrm_email.id as email_id, c.id as contact_id\nFROM       civicrm_contact c\nINNER JOIN civicrm_email                ON civicrm_email.contact_id         = c.id\nINNER JOIN civicrm_group_contact_cache gc ON gc.contact_id        = c.id\nLEFT  JOIN X_{$job_id}                      ON X_{$job_id}.contact_id = c.id\nWHERE      gc.group_id = {$groupDAO->id}\n  AND      c.do_not_email = 0\n  AND      c.is_opt_out = 0\n  AND      c.is_deceased <> 1\n  AND      {$location_filter}\n  AND      civicrm_email.on_hold = 0\n  AND      X_{$job_id}.contact_id IS null\n{$order_by}\n";
         if ($mode == 'sms') {
             $smartGroupInclude = "\nREPLACE INTO I_{$job_id} (phone_id, contact_id)\nSELECT     p.id as phone_id, c.id as contact_id\nFROM       civicrm_contact c\nINNER JOIN civicrm_phone p                ON p.contact_id         = c.id\nINNER JOIN civicrm_group_contact_cache gc ON gc.contact_id        = c.id\nLEFT  JOIN X_{$job_id}                      ON X_{$job_id}.contact_id = c.id\nWHERE      gc.group_id = {$groupDAO->id}\n  AND      c.do_not_sms = 0\n  AND      c.is_opt_out = 0\n  AND      c.is_deceased <> 1\n  AND      p.phone_type_id = {$phoneTypes['Mobile']}\n  AND      X_{$job_id}.contact_id IS null";
         }
         $mailingGroup->query($smartGroupInclude);
     }
     /**
      * Construct the filtered search queries
      */
     $query = "\nSELECT search_id, search_args, entity_id\nFROM   {$mg}\nWHERE  {$mg}.search_id IS NOT NULL\nAND    {$mg}.mailing_id = {$mailing_id}\n";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $customSQL = CRM_Contact_BAO_SearchCustom::civiMailSQL($dao->search_id, $dao->search_args, $dao->entity_id);
         $query = "REPLACE INTO       I_{$job_id} ({$tempColumn}, contact_id)\n                         {$customSQL}";
         $mailingGroup->query($query);
     }
     /* Get the emails with only location override */
     $query = "REPLACE INTO       I_{$job_id} (email_id, contact_id)\n                    SELECT DISTINCT     {$email}.id as local_email_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$email}\n                    INNER JOIN          {$contact}\n                            ON          {$email}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                        {$mg}.entity_table = '{$group}'\n                        AND             {$mg}.group_type = 'Include'\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_email = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$location_filter}\n                        AND             {$email}.on_hold = 0\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null\n                    {$order_by}";
     if ($mode == "sms") {
         $query = "REPLACE INTO       I_{$job_id} (phone_id, contact_id)\n                    SELECT DISTINCT     {$phone}.id as phone_id,\n                                        {$contact}.id as contact_id\n                    FROM                {$phone}\n                    INNER JOIN          {$contact}\n                            ON          {$phone}.contact_id = {$contact}.id\n                    INNER JOIN          {$g2contact}\n                            ON          {$contact}.id = {$g2contact}.contact_id\n                    INNER JOIN          {$mg}\n                            ON          {$g2contact}.group_id = {$mg}.entity_id\n                    LEFT JOIN           X_{$job_id}\n                            ON          {$contact}.id = X_{$job_id}.contact_id\n                    WHERE\n                                        {$mg}.entity_table = '{$group}'\n                        AND             {$mg}.group_type = 'Include'\n                        AND             {$g2contact}.status = 'Added'\n                        AND             {$contact}.do_not_sms = 0\n                        AND             {$contact}.is_opt_out = 0\n                        AND             {$contact}.is_deceased <> 1\n                        AND             {$phone}.phone_type_id = {$phoneTypes['Mobile']}\n                        AND             {$mg}.mailing_id = {$mailing_id}\n                        AND             X_{$job_id}.contact_id IS null";
     }
     $mailingGroup->query($query);
     $eq = new CRM_Mailing_Event_BAO_Queue();
     list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause();
     $aclWhere = $aclWhere ? "WHERE {$aclWhere}" : '';
     if ($storeRecipients && $mailing_id) {
         $sql = "\nDELETE\nFROM   civicrm_mailing_recipients\nWHERE  mailing_id = %1\n";
         $params = array(1 => array($mailing_id, 'Integer'));
         CRM_Core_DAO::executeQuery($sql, $params);
         // CRM-3975
         $groupBy = $groupJoin = '';
         if ($dedupeEmail) {
             $groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
             $groupBy = " GROUP BY e.email ";
         }
         $sql = "\nINSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )\nSELECT %1, i.contact_id, i.{$tempColumn}\nFROM       civicrm_contact contact_a\nINNER JOIN I_{$job_id} i ON contact_a.id = i.contact_id\n           {$groupJoin}\n           {$aclFrom}\n           {$aclWhere}\n           {$groupBy}\nORDER BY   i.contact_id, i.{$tempColumn}\n";
         CRM_Core_DAO::executeQuery($sql, $params);
         // if we need to add all emails marked bulk, do it as a post filter
         // on the mailing recipients table
         if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
             self::addMultipleEmails($mailing_id);
         }
     }
     /* Delete the temp table */
     $mailingGroup->reset();
     $mailingGroup->query("DROP TEMPORARY TABLE X_{$job_id}");
     $mailingGroup->query("DROP TEMPORARY TABLE I_{$job_id}");
     return $eq;
 }
 /**
  * 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)
 {
     try {
         // first make sure this is a valid line
         $response = $this->summary($values);
         if ($response != CRM_Import_Parser::VALID) {
             return $response;
         }
         $params =& $this->getActiveFieldParams();
         //assign join date equal to start date if join date is not provided
         if (!CRM_Utils_Array::value('join_date', $params) && CRM_Utils_Array::value('membership_start_date', $params)) {
             $params['join_date'] = $params['membership_start_date'];
         }
         $session = CRM_Core_Session::singleton();
         $dateType = $session->get('dateTypes');
         $formatted = array();
         $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
         // don't add to recent items, CRM-4399
         $formatted['skipRecentView'] = TRUE;
         $dateLabels = array('join_date' => ts('Member Since'), 'membership_start_date' => ts('Start Date'), 'membership_end_date' => ts('End Date'));
         foreach ($params as $key => $val) {
             if ($val) {
                 switch ($key) {
                     case 'join_date':
                     case 'membership_start_date':
                     case 'membership_end_date':
                         if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                             if (!CRM_Utils_Rule::date($params[$key])) {
                                 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                             }
                         } else {
                             CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                         }
                         break;
                     case 'membership_type_id':
                         if (!is_numeric($val)) {
                             unset($params['membership_type_id']);
                             $params['membership_type'] = $val;
                         }
                         break;
                     case 'status_id':
                         if (!is_numeric($val)) {
                             unset($params['status_id']);
                             $params['membership_status'] = $val;
                         }
                         break;
                     case 'is_override':
                         $params[$key] = CRM_Utils_String::strtobool($val);
                         break;
                 }
                 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                     if ($customFields[$customFieldID]['data_type'] == 'Date') {
                         CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                         unset($params[$key]);
                     } else {
                         if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                             $params[$key] = CRM_Utils_String::strtoboolstr($val);
                         }
                     }
                 }
             }
         }
         //date-Format part ends
         static $indieFields = NULL;
         if ($indieFields == NULL) {
             $tempIndieFields = CRM_Member_DAO_Membership::import();
             $indieFields = $tempIndieFields;
         }
         $formatValues = array();
         foreach ($params as $key => $field) {
             if ($field == NULL || $field === '') {
                 continue;
             }
             $formatValues[$key] = $field;
         }
         //format params to meet api v2 requirements.
         //@todo find a way to test removing this formatting
         $formatError = $this->membership_format_params($formatValues, $formatted, TRUE);
         if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Membership');
         } else {
             //fix for CRM-2219 Update Membership
             // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
             if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
                 array_unshift($values, 'Required parameter missing: Status');
                 return CRM_Import_Parser::ERROR;
             }
             if (!empty($formatValues['membership_id'])) {
                 $dao = new CRM_Member_BAO_Membership();
                 $dao->id = $formatValues['membership_id'];
                 $dates = array('join_date', 'start_date', 'end_date');
                 foreach ($dates as $v) {
                     if (!CRM_Utils_Array::value($v, $formatted)) {
                         $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                     }
                 }
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
                 if ($dao->find(TRUE)) {
                     $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                     $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE);
                     if (civicrm_error($newMembership)) {
                         array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                         return CRM_Import_Parser::ERROR;
                     } else {
                         $this->_newMemberships[] = $newMembership->id;
                         return CRM_Import_Parser::VALID;
                     }
                 } else {
                     array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
         }
         //Format dates
         $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d');
         $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d');
         $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d');
         if ($this->_contactIdIndex < 0) {
             //retrieve contact id using contact dedupe rule
             $formatValues['contact_type'] = $this->_contactType;
             $formatValues['version'] = 3;
             require_once 'CRM/Utils/DeprecatedUtils.php';
             $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
             if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
                 $matchedIDs = explode(',', $error['error_message']['params'][0]);
                 if (count($matchedIDs) > 1) {
                     array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported');
                     return CRM_Import_Parser::ERROR;
                 } else {
                     $cid = $matchedIDs[0];
                     $formatted['contact_id'] = $cid;
                     //fix for CRM-1924
                     $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                     self::formattedDates($calcDates, $formatted);
                     //fix for CRM-3570, exclude the statuses those having is_admin = 1
                     //now user can import is_admin if is override is true.
                     $excludeIsAdmin = FALSE;
                     if (!CRM_Utils_Array::value('is_override', $formatted)) {
                         $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
                     }
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
                     if (!CRM_Utils_Array::value('status_id', $formatted)) {
                         $formatted['status_id'] = $calcStatus['id'];
                     } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                         if (empty($calcStatus)) {
                             array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
                             return CRM_Import_Parser::ERROR;
                         } elseif ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
                             return CRM_Import_Parser::ERROR;
                         }
                     }
                     $newMembership = civicrm_api3('membership', 'create', $formatted);
                     $this->_newMemberships[] = $newMembership['id'];
                     return CRM_Import_Parser::VALID;
                 }
             } else {
                 // Using new Dedupe rule.
                 $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
                 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
                 $disp = '';
                 foreach ($fieldsArray as $value) {
                     if (array_key_exists(trim($value), $params)) {
                         $paramValue = $params[trim($value)];
                         if (is_array($paramValue)) {
                             $disp .= $params[trim($value)][0][trim($value)] . " ";
                         } else {
                             $disp .= $params[trim($value)] . " ";
                         }
                     }
                 }
                 if (CRM_Utils_Array::value('external_identifier', $params)) {
                     if ($disp) {
                         $disp .= "AND {$params['external_identifier']}";
                     } else {
                         $disp = $params['external_identifier'];
                     }
                 }
                 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
                 return CRM_Import_Parser::ERROR;
             }
         } else {
             if (CRM_Utils_Array::value('external_identifier', $formatValues)) {
                 $checkCid = new CRM_Contact_DAO_Contact();
                 $checkCid->external_identifier = $formatValues['external_identifier'];
                 $checkCid->find(TRUE);
                 if ($checkCid->id != $formatted['contact_id']) {
                     array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                     return CRM_Import_Parser::ERROR;
                 }
             }
             //to calculate dates
             $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
             self::formattedDates($calcDates, $formatted);
             //end of date calculation part
             //fix for CRM-3570, exclude the statuses those having is_admin = 1
             //now user can import is_admin if is override is true.
             $excludeIsAdmin = FALSE;
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
             }
             $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
             if (!CRM_Utils_Array::value('status_id', $formatted)) {
                 $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
             } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
                     return CRM_Import_Parser::ERROR;
                 } elseif ($formatted['status_id'] != $calcStatus['id']) {
                     //Status Hold" is either NOT mapped or is FALSE
                     array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
             $newMembership = civicrm_api3('membership', 'create', $formatted);
             $this->_newMemberships[] = $newMembership['id'];
             return CRM_Import_Parser::VALID;
         }
     } catch (Exception $e) {
         array_unshift($values, $e->getMessage());
         return CRM_Import_Parser::ERROR;
     }
 }
Example #30
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 bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('version' => 3);
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     //for date-Formats
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution';
     $customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
     //CRM-10994
     if (isset($params['total_amount']) && $params['total_amount'] == 0) {
         $params['total_amount'] = '0.00';
     }
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'receive_date':
                 case 'cancel_date':
                 case 'receipt_date':
                 case 'thankyou_date':
                     $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType);
                     break;
                 case 'pledge_payment':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $tempIndieFields = CRM_Contribute_DAO_Contribution::import();
         $indieFields = $tempIndieFields;
     }
     $paramValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $paramValues[$key] = $field;
     }
     //import contribution record according to select contact type
     if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP && (!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && (!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (!empty($params['soft_credit'])) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (!empty($paramValues['pledge_payment'])) {
         $paramValues['contact_type'] = $this->_contactType;
     }
     //need to pass $onDuplicate to check import mode.
     if (!empty($paramValues['pledge_payment'])) {
         $paramValues['onDuplicate'] = $onDuplicate;
     }
     require_once 'CRM/Utils/DeprecatedUtils.php';
     $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR;
         } elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') {
             return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR;
         }
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Contribution');
     } else {
         //fix for CRM-2219 - Update Contribution
         // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
         if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) {
             $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues));
             $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds);
             if ($ids['contribution']) {
                 $formatted['id'] = $ids['contribution'];
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatted['id'], 'Contribution');
                 //process note
                 if (!empty($paramValues['note'])) {
                     $noteID = array();
                     $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
                     $daoNote = new CRM_Core_BAO_Note();
                     $daoNote->entity_table = 'civicrm_contribution';
                     $daoNote->entity_id = $ids['contribution'];
                     if ($daoNote->find(TRUE)) {
                         $noteID['id'] = $daoNote->id;
                     }
                     $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID);
                     CRM_Core_BAO_Note::add($noteParams, $noteID);
                     unset($formatted['note']);
                 }
                 //need to check existing soft credit contribution, CRM-3968
                 if (!empty($formatted['soft_credit'])) {
                     $dupeSoftCredit = array('contact_id' => $formatted['soft_credit'], 'contribution_id' => $ids['contribution']);
                     //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null
                     $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']);
                     if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) {
                         foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) {
                             if (!empty($existingSoftCreditValues['soft_credit_id'])) {
                                 $deleteParams = array('id' => $existingSoftCreditValues['soft_credit_id'], 'pcp_id' => NULL);
                                 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
                             }
                         }
                     }
                 }
                 $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids);
                 $this->_newContributions[] = $newContribution->id;
                 //return soft valid since we need to show how soft credits were added
                 if (!empty($formatted['soft_credit'])) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Import_Parser::VALID;
             } else {
                 $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID');
                 foreach ($dupeIds as $k => $v) {
                     if ($v) {
                         $errorMsg[] = "{$labels[$k]} {$v}";
                     }
                 }
                 $errorMsg = implode(' AND ', $errorMsg);
                 array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         // set the contact type if its not set
         if (!isset($paramValues['contact_type'])) {
             $paramValues['contact_type'] = $this->_contactType;
         }
         $paramValues['version'] = 3;
         //retrieve contact id using contact dedupe rule
         require_once 'CRM/Utils/DeprecatedUtils.php';
         $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported');
                 return CRM_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 $newContribution = civicrm_api('contribution', 'create', $formatted);
                 if (civicrm_error($newContribution)) {
                     if (is_array($newContribution['error_message'])) {
                         array_unshift($values, $newContribution['error_message']['message']);
                         if ($newContribution['error_message']['params'][0]) {
                             return CRM_Import_Parser::DUPLICATE;
                         }
                     } else {
                         array_unshift($values, $newContribution['error_message']);
                         return CRM_Import_Parser::ERROR;
                     }
                 }
                 $this->_newContributions[] = $newContribution['id'];
                 $formatted['contribution_id'] = $newContribution['id'];
                 //return soft valid since we need to show how soft credits were added
                 if (!empty($formatted['soft_credit'])) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = NULL;
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($paramValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $paramValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newContribution = civicrm_api('contribution', 'create', $formatted);
         if (civicrm_error($newContribution)) {
             if (is_array($newContribution['error_message'])) {
                 array_unshift($values, $newContribution['error_message']['message']);
                 if ($newContribution['error_message']['params'][0]) {
                     return CRM_Import_Parser::DUPLICATE;
                 }
             } else {
                 array_unshift($values, $newContribution['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $this->_newContributions[] = $newContribution['id'];
         $formatted['contribution_id'] = $newContribution['id'];
         //return soft valid since we need to show how soft credits were added
         if (!empty($formatted['soft_credit'])) {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT;
         }
         // process pledge payment assoc w/ the contribution
         return self::processPledgePayments($formatted);
         return CRM_Import_Parser::VALID;
     }
 }