/**
  * Returns the value of the field for the condition
  * For example: I want to check if age > 50, this function would return the 50
  *
  * @param object CRM_Civirules_TriggerData_TriggerData $triggerData
  * @return
  * @access protected
  * @abstract
  */
 protected function getFieldValue(CRM_Civirules_TriggerData_TriggerData $triggerData)
 {
     $entity = $this->conditionParams['entity'];
     $field = $this->conditionParams['field'];
     $data = $triggerData->getEntityData($entity);
     if (isset($data[$field])) {
         return $this->normalizeValue($data[$field]);
     }
     if (strpos($field, 'custom_') === 0) {
         $custom_field_id = str_replace("custom_", "", $field);
         try {
             $params['entityID'] = $data['id'];
             $params[$field] = 1;
             $values = CRM_Core_BAO_CustomValueTable::getValues($params);
             if (!empty($values[$field])) {
                 return $this->normalizeValue($values[$field]);
             } elseif (!empty($values['error_message'])) {
                 $custom_values = $triggerData->getCustomFieldValues($custom_field_id);
                 if (!empty($custom_values)) {
                     return $this->normalizeValue(reset($custom_values));
                 }
             }
         } catch (Exception $e) {
             //do nothing
         }
     }
     return null;
 }
 public function testCustomGroupMultipleOldFormat()
 {
     $contactID = $this->individualCreate();
     $customGroup = $this->customGroupCreate(array('is_multiple' => 1));
     $fields = array('custom_group_id' => $customGroup['id'], 'dataType' => 'String', 'htmlType' => 'Text');
     $customField = $this->customFieldCreate($fields);
     $params = array('entityID' => $contactID, "custom_{$customField['id']}" => 'First String');
     CRM_Core_BAO_CustomValueTable::setValues($params);
     $newParams = array('entityID' => $contactID, "custom_{$customField['id']}" => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($newParams);
     $this->assertEquals($params["custom_{$customField['id']}"], $result["custom_{$customField['id']}_1"]);
     $this->assertEquals($params['entityID'], $result['entityID']);
     $this->customFieldDelete($customField['id']);
     $this->customGroupDelete($customGroup['id']);
     $this->contactDelete($contactID);
 }
 public function testCustomGroupMultipleOldFormate()
 {
     $params = array();
     $contactID = Contact::createIndividual();
     $customGroup = Custom::createGroup($params, 'Individual', TRUE);
     $fields = array('groupId' => $customGroup->id, 'dataType' => 'String', 'htmlType' => 'Text');
     $customField = Custom::createField($params, $fields);
     $params = array('entityID' => $contactID, "custom_{$customField->id}" => 'First String');
     $error = CRM_Core_BAO_CustomValueTable::setValues($params);
     $newParams = array('entityID' => $contactID, "custom_{$customField->id}" => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($newParams);
     $this->assertEquals($params["custom_{$customField->id}"], $result["custom_{$customField->id}_1"]);
     $this->assertEquals($params['entityID'], $result['entityID']);
     Custom::deleteField($customField);
     Custom::deleteGroup($customGroup);
     Contact::delete($contactID);
 }
예제 #4
0
 /**
  * Create() method with custom data.
  */
 public function testCreateWithCustomData()
 {
     $contactId = $this->individualCreate();
     //create custom data
     $customGroup = $this->customGroupCreate(array('extends' => 'Contribution'));
     $customGroupID = $customGroup['id'];
     $customGroup = $customGroup['values'][$customGroupID];
     $fields = array('label' => 'testFld', 'data_type' => 'String', 'html_type' => 'Text', 'is_active' => 1, 'custom_group_id' => $customGroupID);
     $customField = CRM_Core_BAO_CustomField::create($fields);
     $params = array('contact_id' => $contactId, 'currency' => 'USD', 'financial_type_id' => 1, 'contribution_status_id' => 1, 'payment_instrument_id' => 1, 'source' => 'STUDENT', 'receive_date' => '20080522000000', 'receipt_date' => '20080522000000', 'id' => NULL, 'non_deductible_amount' => 0.0, 'total_amount' => 200.0, 'fee_amount' => 5, 'net_amount' => 195, 'trxn_id' => '22ereerwww322323', 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70', 'thankyou_date' => '20080522');
     $params['custom'] = array($customField->id => array(-1 => array('value' => 'Test custom value', 'type' => 'String', 'custom_field_id' => $customField->id, 'custom_group_id' => $customGroupID, 'table_name' => $customGroup['table_name'], 'column_name' => $customField->column_name, 'file_id' => NULL)));
     $contribution = CRM_Contribute_BAO_Contribution::create($params);
     // Check that the custom field value is saved
     $customValueParams = array('entityID' => $contribution->id, 'custom_' . $customField->id => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($customValueParams);
     $this->assertEquals('Test custom value', $values['custom_' . $customField->id], 'Check the custom field value');
     $this->assertEquals($params['trxn_id'], $contribution->trxn_id, 'Check for transcation id creation.');
     $this->assertEquals($contactId, $contribution->contact_id, 'Check for contact id for Conribution.');
 }
 /**
  * Returns the value of the field for the condition
  * For example: I want to check if age > 50, this function would return the 50
  *
  * @param object CRM_Civirules_TriggerData_TriggerData $triggerData
  * @return
  * @access protected
  * @abstract
  */
 protected function getFieldValue(CRM_Civirules_TriggerData_TriggerData $triggerData)
 {
     $entity = $this->conditionParams['entity'];
     $field = $this->conditionParams['field'];
     $data = $triggerData->getEntityData($entity);
     if (isset($data[$field])) {
         return $this->normalizeValue($data[$field]);
     }
     if ($this->isRelativeDate($field)) {
         $relativeDate = $this->parseRelativeDate($field);
         $field = $relativeDate['field'];
         $interval = $relativeDate['interval'];
         if (isset($data[$field])) {
             $date = new DateTime($data[$field]);
             $today = new DateTime("now");
             $diff = $date->diff($today);
             return $this->normalizeValue($diff->format('%' . $interval));
         }
     }
     if (strpos($field, 'custom_') === 0) {
         $custom_field_id = str_replace("custom_", "", $field);
         try {
             $params['entityID'] = $data['id'];
             $params[$field] = 1;
             $values = CRM_Core_BAO_CustomValueTable::getValues($params);
             $value = null;
             if (!empty($values[$field])) {
                 $value = $this->normalizeValue($values[$field]);
             } elseif (!empty($values['error_message'])) {
                 $value = $triggerData->getCustomFieldValue($custom_field_id);
             }
             if ($value !== null) {
                 $value = $this->convertMultiselectCustomfieldToArray($custom_field_id, $value);
                 return $this->normalizeValue($value);
             }
         } catch (Exception $e) {
             //do nothing
         }
     }
     return null;
 }
 /**
  * Test setValues() and getValues() methods with custom field YesNo(Boolean) Radio
  */
 public function testSetGetValuesYesNoRadio()
 {
     $contactID = $this->individualCreate();
     $customGroup = $this->customGroupCreate(array('is_multiple' => 1));
     //create Custom Field of type YesNo(Boolean) Radio
     $fields = array('custom_group_id' => $customGroup['id'], 'data_type' => 'Boolean', 'html_type' => 'Radio', 'default_value' => '');
     $customField = $this->customFieldCreate($fields);
     // Retrieve the field ID for sample custom field 'test_Boolean'
     $params = array('label' => 'test_Boolean');
     $field = array();
     //get field Id
     CRM_Core_BAO_CustomField::retrieve($params, $field);
     $fieldID = $customField['id'];
     // valid boolean value '1' for Boolean Radio
     $yesNo = '1';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $yesNo);
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     $this->assertEquals($result['is_error'], 0, 'Verify that is_error = 0 (success).');
     // Check that the YesNo radio value is stored
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).');
     $this->assertEquals($values["custom_{$fieldID}_1"], $yesNo, 'Verify that the boolean value is stored for contact ' . $contactID);
     // Now set YesNo radio to an invalid boolean value and try to reset
     $badYesNo = '20';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $badYesNo);
     CRM_Core_TemporaryErrorScope::useException();
     $message = NULL;
     try {
         CRM_Core_BAO_CustomValueTable::setValues($params);
     } catch (Exception $e) {
         $message = $e->getMessage();
     }
     $errorScope = NULL;
     // Check that an exception has been thrown
     $this->assertNotNull($message, 'Verify than an exception is thrown when bad boolean is passed');
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values["custom_{$fieldID}_1"], $yesNo, 'Verify that the date value has NOT been updated for contact ' . $contactID);
     // Cleanup
     $this->customFieldDelete($customField['id']);
     $this->customGroupDelete($customGroup['id']);
     $this->contactDelete($contactID);
 }
예제 #7
0
/**
 * Use this API to get existing custom values for an entity.
 *
 * @param array $params
 *   Array specifying the entity_id.
 *   Optionally include entity_type param, i.e. 'entity_type' => 'Activity'
 *   If no entity_type is supplied, it will be determined based on the fields you request.
 *   If no entity_type is supplied and no fields are specified, 'Contact' will be assumed.
 *   Optionally include the desired custom data to be fetched (or else all custom data for this entity will be returned)
 *   Example: 'entity_id' => 123, 'return.custom_6' => 1, 'return.custom_33' => 1
 *   If you do not know the ID, you may use group name : field name, for example 'return.foo_stuff:my_field' => 1
 *
 * @throws API_Exception
 * @return array
 */
function civicrm_api3_custom_value_get($params)
{
    $getParams = array('entityID' => $params['entity_id'], 'entityType' => CRM_Utils_Array::value('entity_table', $params, ''));
    if (strstr($getParams['entityType'], 'civicrm_')) {
        $getParams['entityType'] = ucfirst(substr($getParams['entityType'], 8));
    }
    unset($params['entity_id'], $params['entity_table']);
    foreach ($params as $id => $param) {
        if ($param && substr($id, 0, 6) == 'return') {
            $id = substr($id, 7);
            list($c, $i) = CRM_Utils_System::explode('_', $id, 2);
            if ($c == 'custom' && is_numeric($i)) {
                $names['custom_' . $i] = 'custom_' . $i;
                $id = $i;
            } else {
                // Lookup names if ID was not supplied
                list($group, $field) = CRM_Utils_System::explode(':', $id, 2);
                $id = CRM_Core_BAO_CustomField::getCustomFieldID($field, $group);
                if (!$id) {
                    continue;
                }
                $names['custom_' . $id] = 'custom_' . $i;
            }
            $getParams['custom_' . $id] = 1;
        }
    }
    $result = CRM_Core_BAO_CustomValueTable::getValues($getParams);
    if ($result['is_error']) {
        if ($result['error_message'] == "No values found for the specified entity ID and custom field(s).") {
            $values = array();
            return civicrm_api3_create_success($values, $params, 'CustomValue');
        } else {
            throw new API_Exception($result['error_message']);
        }
    } else {
        $entity_id = $result['entityID'];
        unset($result['is_error'], $result['entityID']);
        // Convert multi-value strings to arrays
        $sp = CRM_Core_DAO::VALUE_SEPARATOR;
        foreach ($result as $id => $value) {
            if (strpos($value, $sp) !== FALSE) {
                $value = explode($sp, trim($value, $sp));
            }
            $idArray = explode('_', $id);
            if ($idArray[0] != 'custom') {
                continue;
            }
            $fieldNumber = $idArray[1];
            $customFieldInfo = CRM_Core_BAO_CustomField::getNameFromID($fieldNumber);
            $info = array_pop($customFieldInfo);
            // id is the index for returned results
            if (empty($idArray[2])) {
                $n = 0;
                $id = $fieldNumber;
            } else {
                $n = $idArray[2];
                $id = $fieldNumber . "." . $idArray[2];
            }
            if (!empty($params['format.field_names'])) {
                $id = $info['field_name'];
            } else {
                $id = $fieldNumber;
            }
            $values[$id]['entity_id'] = $getParams['entityID'];
            if (!empty($getParams['entityType'])) {
                $values[$id]['entity_table'] = $getParams['entityType'];
            }
            //set 'latest' -useful for multi fields but set for single for consistency
            $values[$id]['latest'] = $value;
            $values[$id]['id'] = $id;
            $values[$id][$n] = $value;
        }
        return civicrm_api3_create_success($values, $params, 'CustomValue');
    }
}
예제 #8
0
 /**
  * Based on the provided two contact_ids and a set of tables, move the belongings of the
  * other contact to the main one - be it Location / CustomFields or Contact .. related info.
  * A superset of moveContactBelongings() function.
  *
  * @param int $mainId
  *   Main contact with whom merge has to happen.
  * @param int $otherId
  *   Duplicate contact which would be deleted after merge operation.
  *
  * @param $migrationInfo
  *
  * @return bool
  */
 public static function moveAllBelongings($mainId, $otherId, $migrationInfo)
 {
     if (empty($migrationInfo)) {
         return FALSE;
     }
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     $relTables = CRM_Dedupe_Merger::relTables();
     $moveTables = $locBlocks = $tableOperations = array();
     foreach ($migrationInfo as $key => $value) {
         if ($value == $qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) || substr($key, 0, 12) == 'move_custom_') && $value != NULL) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
             $locField = explode('_', $key);
             $fieldName = $locField[2];
             $fieldCount = $locField[3];
             $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
             // default operation is overwrite.
             if (!$operation) {
                 $operation = 2;
             }
             $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
             $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
             if (array_key_exists('operation', $migrationInfo)) {
                 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
                     if (array_key_exists($key, $migrationInfo['operation'])) {
                         $tableOperations[$table] = $migrationInfo['operation'][$key];
                     }
                 }
             }
         }
     }
     // **** Do location related migration:
     if (!empty($locBlocks)) {
         $locComponent = array('email' => 'Email', 'phone' => 'Phone', 'im' => 'IM', 'openid' => 'OpenID', 'address' => 'Address');
         $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
         $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
         foreach ($locBlocks as $name => $block) {
             if (!is_array($block) || CRM_Utils_System::isNull($block)) {
                 continue;
             }
             $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
             $primaryDAOId = array_key_exists($name, $primaryBlockIds) ? array_pop($primaryBlockIds[$name]) : NULL;
             $billingDAOId = array_key_exists($name, $billingBlockIds) ? array_pop($billingBlockIds[$name]) : NULL;
             foreach ($block as $blkCount => $values) {
                 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
                 $operation = CRM_Utils_Array::value('operation', $values, 2);
                 $otherBlockId = CRM_Utils_Array::value($blkCount, $migrationInfo['other_details']['loc_block_ids'][$name]);
                 // keep 1-1 mapping for address - loc type.
                 $idKey = $blkCount;
                 if (array_key_exists($name, $locComponent)) {
                     $idKey = $locTypeId;
                 }
                 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
                     $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
                 }
                 if (!$otherBlockId) {
                     continue;
                 }
                 // for the block which belongs to other-contact, link the contact to main-contact
                 $otherBlockDAO = new $daoName();
                 $otherBlockDAO->id = $otherBlockId;
                 $otherBlockDAO->contact_id = $mainId;
                 $otherBlockDAO->location_type_id = $locTypeId;
                 // if main contact already has primary & billing, set the flags to 0.
                 if ($primaryDAOId) {
                     $otherBlockDAO->is_primary = 0;
                 }
                 if ($billingDAOId) {
                     $otherBlockDAO->is_billing = 0;
                 }
                 // overwrite - need to delete block which belongs to main-contact.
                 if (isset($mainBlockId) && $mainBlockId && $operation == 2) {
                     $deleteDAO = new $daoName();
                     $deleteDAO->id = $mainBlockId;
                     $deleteDAO->find(TRUE);
                     // if we about to delete a primary / billing block, set the flags for new block
                     // that we going to assign to main-contact
                     if ($primaryDAOId && $primaryDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_primary = 1;
                     }
                     if ($billingDAOId && $billingDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_billing = 1;
                     }
                     $deleteDAO->delete();
                     $deleteDAO->free();
                 }
                 $otherBlockDAO->update();
                 $otherBlockDAO->free();
             }
         }
     }
     // **** Do tables related migrations
     if (!empty($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
         unset($moveTables, $tableOperations);
     }
     // **** Do contact related migrations
     CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
     // fix custom fields so they're edible by createProfileContact()
     static $treeCache = array();
     if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
         $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], CRM_Core_DAO::$_nullObject, NULL, -1);
     }
     $cgTree =& $treeCache[$migrationInfo['main_details']['contact_type']];
     $cFields = array();
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             if (empty($cFields[$fid])) {
                 continue;
             }
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     $customParams = array('entityID' => $mainId, $key => TRUE);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (!empty($customfieldValues[$key])) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value) {
                                 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             }
                             //hack to remove null and duplicate values from array.
                             foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                 if ($v != '' && !in_array($v, $mergeValue)) {
                                     $mergeValue[] = $v;
                                 }
                             }
                             //keep state and country as array format.
                             //for checkbox and m-select format w/ VALUE_SEPARATOR
                             if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $mergeValue) . CRM_Core_DAO::VALUE_SEPARATOR;
                             } else {
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     } elseif (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                         //we require submitted values should be in array format
                         if ($value) {
                             $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             //hack to remove null values from array.
                             $mergeValue = array();
                             foreach ($mergeValueArray as $k => $v) {
                                 if ($v != '') {
                                     $mergeValue[] = $v;
                                 }
                             }
                             $submitted[$key] = $mergeValue;
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // **** Do file custom fields related migrations
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
     // like, delete a file...
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
         $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         if (!empty($fileIds[$mainId])) {
             CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
         }
         // move the other contact's file to main contact
         //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
         if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
             $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
         } else {
             $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         if (CRM_Core_DAO::singleValueQuery("\n        SELECT id\n        FROM civicrm_entity_file\n        WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")) {
             $sql = "\n          UPDATE civicrm_entity_file\n          SET entity_id = {$mainId}\n          WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
         } else {
             $sql = "\n          INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )\n          VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     }
     // move view only custom fields CRM-5362
     $viewOnlyCustomFields = array();
     foreach ($submitted as $key => $value) {
         $fid = (int) substr($key, 7);
         if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
             $viewOnlyCustomFields[$key] = $value;
         }
     }
     // special case to set values for view only, CRM-5362
     if (!empty($viewOnlyCustomFields)) {
         $viewOnlyCustomFields['entityID'] = $mainId;
         CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
     }
     // **** Delete other contact & update prev-next caching
     $otherParams = array('contact_id' => $otherId, 'id' => $otherId, 'version' => 3);
     if (CRM_Core_Permission::check('merge duplicate contacts') && CRM_Core_Permission::check('delete contacts')) {
         // if ext id is submitted then set it null for contact to be deleted
         if (!empty($submitted['external_identifier'])) {
             $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
             CRM_Core_DAO::executeQuery($query);
         }
         civicrm_api('contact', 'delete', $otherParams);
         CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
     }
     // FIXME: else part
     /*         else { */
     /*             CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
     /*         } */
     // CRM-15681 merge sub_types
     if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
         if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
             $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
         } else {
             $submitted['contact_sub_type'] = $other_sub_types;
         }
     }
     // **** Update contact related info for the main contact
     if (!empty($submitted)) {
         $submitted['contact_id'] = $mainId;
         //update current employer field
         if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
             if (!CRM_Utils_System::isNull($currentEmloyerId)) {
                 $submitted['current_employer'] = $submitted['current_employer_id'];
             } else {
                 $submitted['current_employer'] = '';
             }
             unset($submitted['current_employer_id']);
         }
         //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
         if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
             $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
         }
         if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
             $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
         }
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
         unset($submitted);
     }
     CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
     return TRUE;
 }
예제 #9
0
 /**
  * This function is to get Vacancy ID from Application ID
  *
  * @param int $caseID - Case ID of type Application
  *
  * @return int
  * @access public
  */
 public static function getVacancyIDByCase($caseID)
 {
     $vacancyID = NULL;
     $applCaseID = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_CustomField', 'custom_group_id', 'application_case');
     $cgID = array('custom_group_id' => $applCaseID);
     CRM_Core_BAO_CustomField::retrieve($cgID, $cfID);
     $params = array("entityID" => $caseID, "custom_{$cfID['id']}" => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($params);
     if (array_key_exists("custom_{$cfID['id']}", $result)) {
         $vacancyID = $result["custom_{$cfID['id']}"];
     }
     return $vacancyID;
 }
예제 #10
0
파일: Merge.php 프로젝트: ksecor/civicrm
 public function postProcess()
 {
     $formValues = $this->exportValues();
     // user can't choose to move cases without activities (CRM-3778)
     if ($formValues['move_rel_table_cases'] == '1' && array_key_exists('move_rel_table_activities', $formValues)) {
         $formValues['move_rel_table_activities'] = '1';
     }
     // reset all selected contact ids from session
     // when we came from search context, CRM-3526
     $session =& CRM_Core_Session::singleton();
     if ($session->get('selectedSearchContactIds')) {
         $session->resetScope('selectedSearchContactIds');
     }
     $relTables =& CRM_Dedupe_Merger::relTables();
     $moveTables = $locBlocks = array();
     foreach ($formValues as $key => $value) {
         if ($value == $this->_qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::$validFields) or substr($key, 0, 12) == 'move_custom_') and $value != null) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != null) {
             $locField = explode('_', $key);
             $fieldName = $locField[2];
             $fieldCount = $locField[3];
             $operation = CRM_Utils_Array::value('operation', $formValues['location'][$fieldName][$fieldCount]);
             // default operation is overwrite.
             if (!$operation) {
                 $operation = 2;
             }
             $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
             $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $formValues['location'][$fieldName][$fieldCount]);
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
         }
     }
     // process location blocks.
     if (!empty($locBlocks)) {
         $locComponent = array('email' => 'Email', 'phone' => 'Phone', 'im' => 'IM', 'openid' => 'OpenID', 'address' => 'Address');
         require_once 'CRM/Contact/BAO/Contact.php';
         $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($this->_cid, array('is_primary' => 1));
         $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($this->_cid, array('is_billing' => 1));
         foreach ($locBlocks as $name => $block) {
             if (!is_array($block) || CRM_Utils_System::isNull($block)) {
                 continue;
             }
             $daoName = $locComponent[$name];
             $primaryDAOId = array_key_exists($name, $primaryBlockIds) ? array_pop($primaryBlockIds[$name]) : null;
             $billingDAOId = array_key_exists($name, $billingBlockIds) ? array_pop($billingBlockIds[$name]) : null;
             foreach ($block as $blkCount => $values) {
                 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
                 $operation = CRM_Utils_Array::value('operation', $values, 2);
                 $updateBlockId = CRM_Utils_Array::value($blkCount, $this->_locBlockIds['other'][$name]);
                 // keep 1-1 mapping for address - loc type.
                 $idKey = $blkCount;
                 if ($name == 'address') {
                     $idKey = $locTypeId;
                 }
                 $deleteBlockId = CRM_Utils_Array::value($idKey, $this->_locBlockIds['main'][$name]);
                 if (!$updateBlockId) {
                     continue;
                 }
                 require_once "CRM/Core/DAO/{$daoName}.php";
                 eval("\$updateDAO =& new CRM_Core_DAO_{$daoName}();");
                 $updateDAO->id = $updateBlockId;
                 $updateDAO->contact_id = $this->_cid;
                 $updateDAO->location_type_id = $locTypeId;
                 // contact having primary block.
                 if ($primaryDAOId) {
                     $updateDAO->is_primary = 0;
                 }
                 if ($billingDAOId) {
                     $updateDAO->is_billing = 0;
                 }
                 // overwrite - need to delete block from main contact.
                 if ($deleteBlockId && $operation == 2) {
                     eval("\$deleteDAO =& new CRM_Core_DAO_{$daoName}();");
                     $deleteDAO->id = $deleteBlockId;
                     $deleteDAO->find(true);
                     // since we overwrite primary block.
                     if ($primaryDAOId && $primaryDAOId == $deleteDAO->id) {
                         $updateDAO->is_primary = 1;
                     }
                     if ($billingDAOId && $billingDAOId == $deleteDAO->id) {
                         $updateDAO->is_billing = 1;
                     }
                     $deleteDAO->delete();
                     $deleteDAO->free();
                 }
                 $updateDAO->update();
                 $updateDAO->free();
             }
         }
     }
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, true);
     // FIXME: fix custom fields so they're edible by createProfileContact()
     $cgTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, null, -1);
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     require_once 'CRM/Core/BAO/CustomValueTable.php';
                     $customParams = array('entityID' => $this->_cid, $key => true);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (CRM_Utils_array::value($key, $customfieldValues)) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value) {
                                 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             }
                             //hack to remove null and duplicate values from array.
                             foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                 if ($v != '' && !in_array($v, $mergeValue)) {
                                     $mergeValue[] = $v;
                                 }
                             }
                             //keep state and country as array format.
                             //for checkbox and m-select format w/ VALUE_SEPERATOR
                             if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                 $submitted[$key] = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $mergeValue) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                             } else {
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     } else {
                         if (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                             //we require submitted values should be in array format
                             if ($value) {
                                 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                                 //hack to remove null values from array.
                                 $mergeValue = array();
                                 foreach ($mergeValueArray as $k => $v) {
                                     if ($v != '') {
                                         $mergeValue[] = $v;
                                     }
                                 }
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // handle the related tables
     if (isset($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($this->_cid, $this->_oid, $moveTables);
     }
     // move file custom fields
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::delete() shouldn't actually,
     // like, delete a file...
     require_once 'CRM/Core/BAO/File.php';
     require_once 'CRM/Core/DAO/CustomField.php';
     require_once 'CRM/Core/DAO/CustomGroup.php';
     require_once 'CRM/Core/DAO/EntityFile.php';
     require_once 'CRM/Core/Config.php';
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$this->_cid}, {$this->_oid})";
         $dao =& CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         CRM_Core_BAO_File::delete($fileIds[$this->_cid], $this->_cid, $customId);
         // move the other contact's file to main contact
         $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$this->_oid]} WHERE entity_id = {$this->_cid}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         $sql = "UPDATE civicrm_entity_file SET entity_id = {$this->_cid} WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$this->_oid]}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     }
     // move other's belongings and delete the other contact
     CRM_Dedupe_Merger::moveContactBelongings($this->_cid, $this->_oid);
     $otherParams = array('contact_id' => $this->_oid);
     if (CRM_Core_Permission::check('delete contacts')) {
         civicrm_contact_delete($otherParams);
     } else {
         CRM_Core_Session::setStatus(ts('Do not have sufficient permission to delete duplicate contact.'));
     }
     if (isset($submitted)) {
         $submitted['contact_id'] = $this->_cid;
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $this->_cid);
     }
     CRM_Core_Session::setStatus(ts('The contacts have been merged.'));
     $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
     CRM_Utils_System::redirect($url);
 }
예제 #11
0
파일: Export.php 프로젝트: ksecor/civicrm
 /**
  * Function to get the list the export fields
  *
  * @param int    $selectAll user preference while export
  * @param array  $ids  contact ids
  * @param array  $params associated array of fields
  * @param string $order order by clause
  * @param array  $associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null)
 {
     $headerRows = array();
     $primary = false;
     $returnProperties = array();
     $origFields = $fields;
     $queryMode = null;
     $paymentFields = false;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = null;
             $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 1;
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($relIMProviderId) {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                         } else {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                         }
                     }
                     $relPhoneTypeId = $relIMProviderId = null;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 1;
                         }
                     }
                 }
             }
         }
     } else {
         $primary = true;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', true, true);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = false;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = true;
                 $paymentTableId = "participant_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = true;
                 $paymentTableId = "membership_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset groups, tags, notes for components
             foreach (array('groups', 'tags', 'notes') as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (CRM_Utils_Array::value('groups', $returnProperties)) {
         $oldClause = "contact_a.id = civicrm_group_contact.contact_id";
         $newClause = " ( {$oldClause} AND civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) ";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where}";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $queryString .= " GROUP BY contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray);
     $header = false;
     $addPaymentHeader = false;
     if ($paymentFields) {
         $addPaymentHeader = true;
         //special return properties for event and members
         $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
     }
     $componentDetails = $headerRows = array();
     $setHeader = true;
     while ($dao->fetch()) {
         $row = array();
         //first loop through returnproperties so that we return what is required, and in same order.
         $relationshipField = 0;
         foreach ($returnProperties as $field => $value) {
             //we should set header only once
             if ($setHeader) {
                 if (isset($query->_fields[$field]['title'])) {
                     $headerRows[] = $query->_fields[$field]['title'];
                 } else {
                     if ($field == 'phone_type_id') {
                         $headerRows[] = 'Phone Type';
                     } else {
                         if ($field == 'provider_id') {
                             $headerRows[] = 'Im Service Provider';
                         } else {
                             if (is_array($value) && $field == 'location') {
                                 // fix header for location type case
                                 foreach ($value as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                         if (CRM_Utils_Array::value(1, $type)) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } else {
                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                 }
                                             }
                                         }
                                         $headerRows[] = $hdr;
                                     }
                                 }
                             } else {
                                 if (substr($field, 0, 5) == 'case_') {
                                     if ($query->_fields['case'][$field]['title']) {
                                         $headerRows[] = $query->_fields['case'][$field]['title'];
                                     } else {
                                         if ($query->_fields['activity'][$field]['title']) {
                                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                                         }
                                     }
                                 } else {
                                     if (array_key_exists($field, $contactRelationshipTypes)) {
                                         foreach ($value as $relationField => $relationValue) {
                                             if (is_array($relationValue)) {
                                                 foreach ($relationValue as $locType => $locValue) {
                                                     if ($relationField == 'location') {
                                                         foreach ($locValue as $locKey => $dont) {
                                                             list($serviceProvider, $serviceProviderID) = explode('-', $locKey);
                                                             if ($serviceProvider == 'phone') {
                                                                 $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $phoneTypes, 'Primary');
                                                             } else {
                                                                 if ($serviceProvider == 'im') {
                                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $imProviders, 'Primary');
                                                                 } else {
                                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $query->_fields[$locKey]['title'];
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             } else {
                                                 if ($query->_fields[$relationField]['title']) {
                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $query->_fields[$relationField]['title'];
                                                 } else {
                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $relationField;
                                                 }
                                             }
                                         }
                                     } else {
                                         $headerRows[] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             //build row values (data)
             if (property_exists($dao, $field)) {
                 $fieldValue = $dao->{$field};
                 // to get phone type from phone type id
                 if ($field == 'phone_type_id') {
                     $fieldValue = $phoneTypes[$fieldValue];
                 } else {
                     if ($field == 'provider_id') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     }
                 }
             } else {
                 $fieldValue = '';
             }
             if ($field == 'id') {
                 $row[$field] = $dao->contact_id;
             } else {
                 if ($field == 'pledge_balance_amount') {
                     //special case for calculated field
                     $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                 } else {
                     if ($field == 'pledge_next_pay_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                     } else {
                         if (is_array($value) && $field == 'location') {
                             // fix header for location type case
                             foreach ($value as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (CRM_Utils_Array::value(1, $type)) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     $row[$fldValue] = $dao->{$fldValue};
                                 }
                             }
                         } else {
                             if (array_key_exists($field, $contactRelationshipTypes)) {
                                 list($id, $direction) = explode('_', $field, 2);
                                 require_once 'api/v2/Relationship.php';
                                 require_once 'CRM/Contact/BAO/Contact.php';
                                 require_once 'CRM/Core/BAO/CustomValueTable.php';
                                 require_once 'CRM/Core/BAO/CustomQuery.php';
                                 $params['relationship_type_id'] = $contactRelationshipTypes[$field];
                                 $contact_id['contact_id'] = $dao->contact_id;
                                 //Get relationships
                                 $val = civicrm_contact_relationship_get($contact_id, null, $params);
                                 if (is_array($val['result'])) {
                                     asort($val['result']);
                                 }
                                 $is_valid = null;
                                 $data = null;
                                 if ($val['result']) {
                                     foreach ($val['result'] as $k => $v) {
                                         //consider only active relationships
                                         if ($v['is_active'] && $v['rtype'] == $direction) {
                                             $cID['contact_id'] = $v['cid'];
                                             if ($cID) {
                                                 //Get Contact Details
                                                 $data = CRM_Contact_BAO_Contact::retrieve($cID, $defaults);
                                             }
                                             $is_valid = true;
                                             break;
                                         }
                                     }
                                 }
                                 $relCustomIDs = array();
                                 foreach ($value as $relationkey => $relationvalue) {
                                     if ($val['result'] && ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey))) {
                                         foreach ($val['result'] as $k1 => $v1) {
                                             $contID = $v1['cid'];
                                             $param1 = array('entityID' => $contID, $relationkey => 1);
                                             $getcustomValue = CRM_Core_BAO_CustomValueTable::getValues($param1);
                                             $custom_ID = CRM_Core_BAO_CustomField::getKeyID($relationkey);
                                             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey)) {
                                                 if (empty($query->_options)) {
                                                     $relCustomIDs[$cfID] = array();
                                                     $relQuery = new CRM_Core_BAO_CustomQuery($relCustomIDs);
                                                     $relQuery->query();
                                                     $relOptions = $relQuery->_options;
                                                 } else {
                                                     $relOptions = $query->_options;
                                                 }
                                                 $custom_data = CRM_Core_BAO_CustomField::getDisplayValue($getcustomValue[$relationkey], $cfID, $relOptions);
                                             } else {
                                                 $custom_data = '';
                                             }
                                         }
                                     }
                                     //Get all relationships type custom fields
                                     list($id, $atype, $btype) = explode('_', $field);
                                     $relCustomData = CRM_Core_BAO_CustomField::getFields('Relationship', null, null, $id, null, null);
                                     $tmpArray = array_keys($relCustomData);
                                     $customIDs = array();
                                     foreach ($tmpArray as $customID) {
                                         $customIDs[$customID] = array();
                                     }
                                     require_once 'CRM/Core/BAO/CustomQuery.php';
                                     $customQuery = new CRM_Core_BAO_CustomQuery($customIDs);
                                     $customQuery->query();
                                     $options = $customQuery->_options;
                                     foreach ($relCustomData as $id => $customdatavalue) {
                                         if (in_array($relationkey, $customdatavalue)) {
                                             $customkey = "custom_{$id}";
                                             if ($val['result']) {
                                                 foreach ($val['result'] as $k => $v) {
                                                     $cid = $v['id'];
                                                     $param = array('entityID' => $cid, $customkey => 1);
                                                     //Get custom data values
                                                     $getCustomValueRel = CRM_Core_BAO_CustomValueTable::getValues($param);
                                                     if (!array_key_exists('error_message', $getCustomValueRel)) {
                                                         $customData = CRM_Core_BAO_CustomField::getDisplayValue($getCustomValueRel[$customkey], $id, $options);
                                                     } else {
                                                         $customData = '';
                                                     }
                                                     if ($customData) {
                                                         break;
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                     if (is_array($relationvalue)) {
                                         if (array_key_exists('location', $value)) {
                                             foreach ($value['location'] as $columnkey => $columnvalue) {
                                                 foreach ($columnvalue as $colkey => $colvalue) {
                                                     list($serviceProvider, $serviceProviderID) = explode('-', $colkey);
                                                     if (in_array($serviceProvider, array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'state_province', 'country'))) {
                                                         $serviceProvider = 'address';
                                                     }
                                                     $output = null;
                                                     foreach ((array) $data->{$serviceProvider} as $datakey => $datavalue) {
                                                         if ($columnkey == 'Primary') {
                                                             $columnkey = $locationTypes[$datavalue['location_type_id']];
                                                         }
                                                         if ($locationTypes[$datavalue['location_type_id']] == $columnkey) {
                                                             if (array_key_exists($colkey, $datavalue)) {
                                                                 $output = $datavalue[$colkey];
                                                             } else {
                                                                 if ($colkey == 'country') {
                                                                     $countryId = $datavalue['country_id'];
                                                                     if ($countryId) {
                                                                         require_once 'CRM/Core/PseudoConstant.php';
                                                                         $country =& CRM_Core_PseudoConstant::country($countryId);
                                                                     } else {
                                                                         $country = '';
                                                                     }
                                                                     $output = $country;
                                                                 } else {
                                                                     if ($colkey == 'state_province') {
                                                                         $stateProvinceId = $datavalue['state_province_id'];
                                                                         if ($stateProvinceId) {
                                                                             $stateProvince =& CRM_Core_PseudoConstant::stateProvince($stateProvinceId);
                                                                         } else {
                                                                             $stateProvince = '';
                                                                         }
                                                                         $output = $stateProvince;
                                                                     } else {
                                                                         if (is_numeric($serviceProviderID)) {
                                                                             if ($serviceProvider == 'phone') {
                                                                                 if (isset($datavalue['phone'])) {
                                                                                     $output = $datavalue['phone'];
                                                                                 } else {
                                                                                     $output = '';
                                                                                 }
                                                                             } else {
                                                                                 if ($serviceProvider == 'im') {
                                                                                     if (isset($datavalue['name'])) {
                                                                                         $output = $datavalue['name'];
                                                                                     } else {
                                                                                         $output = '';
                                                                                     }
                                                                                 }
                                                                             }
                                                                         } else {
                                                                             if ($datavalue['location_type_id']) {
                                                                                 if ($colkey == 'im') {
                                                                                     $output = $datavalue['name'];
                                                                                 } else {
                                                                                     $output = $datavalue[$colkey];
                                                                                 }
                                                                             } else {
                                                                                 $output = '';
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                     if ($is_valid) {
                                                         $row[] = $output;
                                                     } else {
                                                         $row[] = '';
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey) && $is_valid) {
                                             $row[] = $custom_data;
                                         } else {
                                             if ($query->_fields[$relationkey]['name'] && $is_valid) {
                                                 if ($query->_fields[$relationkey]['name'] == 'gender') {
                                                     $getGenders =& CRM_Core_PseudoConstant::gender();
                                                     $gender = array_search($data->gender_id, array_flip($getGenders));
                                                     $row[] = $gender;
                                                 } else {
                                                     if ($query->_fields[$relationkey]['name'] == 'greeting_type') {
                                                         $getgreeting =& CRM_Core_PseudoConstant::greeting();
                                                         $greeting = array_search($data->greeting_type_id, array_flip($getgreeting));
                                                         $row[] = $greeting;
                                                     } else {
                                                         $colValue = $query->_fields[$relationkey]['name'];
                                                         $row[] = $data->{$colValue};
                                                     }
                                                 }
                                             } else {
                                                 if ($customData && $is_valid) {
                                                     $row[] = $customData;
                                                 } else {
                                                     $row[] = '';
                                                 }
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if (isset($fieldValue) && $fieldValue != '') {
                                     //check for custom data
                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                                     } else {
                                         if (array_key_exists($field, $multipleSelectFields)) {
                                             //option group fixes
                                             $paramsNew = array($field => $fieldValue);
                                             if ($field == 'test_tutoring') {
                                                 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                             } else {
                                                 if (substr($field, 0, 4) == 'cmr_') {
                                                     //for  readers group
                                                     $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                                                 } else {
                                                     $name = array($field => array('newName' => $field, 'groupName' => $field));
                                                 }
                                             }
                                             CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                                             $row[$field] = $paramsNew[$field];
                                         } else {
                                             if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                 //special case for greeting replacement
                                                 $fldValue = "{$field}_display";
                                                 $row[$field] = $dao->{$fldValue};
                                             } else {
                                                 //normal fields
                                                 $row[$field] = $fieldValue;
                                             }
                                         }
                                     }
                                 } else {
                                     // if field is empty or null
                                     $row[$field] = '';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //build header only once
         $setHeader = false;
         // add payment headers if required
         if ($addPaymentHeader && $paymentFields) {
             $headerRows = array_merge($headerRows, $paymentHeaders);
             $addPaymentHeader = false;
         }
         // add payment related information
         if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
             $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
         }
         //remove organization name for individuals if it is set for current employer
         if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') {
             $row['organization_name'] = '';
         }
         // add component info
         $componentDetails[] = $row;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails);
     exit;
 }
예제 #12
0
 /**
  * Based on the provided two contact_ids and a set of tables, move the belongings of the
  * other contact to the main one - be it Location / CustomFields or Contact .. related info.
  * A superset of moveContactBelongings() function.
  *
  * @param int $mainId
  *   Main contact with whom merge has to happen.
  * @param int $otherId
  *   Duplicate contact which would be deleted after merge operation.
  *
  * @param $migrationInfo
  *
  * @param bool $checkPermissions
  *   Respect logged in user permissions.
  *
  * @return bool
  */
 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE)
 {
     if (empty($migrationInfo)) {
         return FALSE;
     }
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     $relTables = CRM_Dedupe_Merger::relTables();
     $moveTables = $locationMigrationInfo = $tableOperations = array();
     foreach ($migrationInfo as $key => $value) {
         if ($value == $qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) || substr($key, 0, 12) == 'move_custom_') && $value != NULL) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
             $locationMigrationInfo[$key] = $value;
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
             if (array_key_exists('operation', $migrationInfo)) {
                 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
                     if (array_key_exists($key, $migrationInfo['operation'])) {
                         $tableOperations[$table] = $migrationInfo['operation'][$key];
                     }
                 }
             }
         }
     }
     self::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo);
     // **** Do tables related migrations
     if (!empty($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
         unset($moveTables, $tableOperations);
     }
     // **** Do contact related migrations
     CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
     // fix custom fields so they're edible by createProfileContact()
     static $treeCache = array();
     if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
         $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], CRM_Core_DAO::$_nullObject, NULL, -1);
     }
     $cgTree =& $treeCache[$migrationInfo['main_details']['contact_type']];
     $cFields = array();
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             if (empty($cFields[$fid])) {
                 continue;
             }
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
                     break;
                 case 'Select Date':
                     if ($cFields[$fid]['attributes']['is_view']) {
                         $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
                     }
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     $customParams = array('entityID' => $mainId, $key => TRUE);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (!empty($customfieldValues[$key])) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value == 'null') {
                                 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
                                 $submitted[$key] = $value;
                             } else {
                                 if ($value) {
                                     $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                                 }
                                 //hack to remove null and duplicate values from array.
                                 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                     if ($v != '' && !in_array($v, $mergeValue)) {
                                         $mergeValue[] = $v;
                                     }
                                 }
                                 //keep state and country as array format.
                                 //for checkbox and m-select format w/ VALUE_SEPARATOR
                                 if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                     $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $mergeValue) . CRM_Core_DAO::VALUE_SEPARATOR;
                                 } else {
                                     $submitted[$key] = $mergeValue;
                                 }
                             }
                         }
                     } elseif (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                         //we require submitted values should be in array format
                         if ($value) {
                             $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             //hack to remove null values from array.
                             $mergeValue = array();
                             foreach ($mergeValueArray as $k => $v) {
                                 if ($v != '') {
                                     $mergeValue[] = $v;
                                 }
                             }
                             $submitted[$key] = $mergeValue;
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // **** Do file custom fields related migrations
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
     // like, delete a file...
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
         $dao = CRM_Core_DAO::executeQuery($sql);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         if (!empty($fileIds[$mainId])) {
             CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
         }
         // move the other contact's file to main contact
         //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
         if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
             $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
         } else {
             $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql);
         if (CRM_Core_DAO::singleValueQuery("\n        SELECT id\n        FROM civicrm_entity_file\n        WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")) {
             $sql = "\n          UPDATE civicrm_entity_file\n          SET entity_id = {$mainId}\n          WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
         } else {
             $sql = "\n          INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )\n          VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql);
     }
     // move view only custom fields CRM-5362
     $viewOnlyCustomFields = array();
     foreach ($submitted as $key => $value) {
         $fid = (int) substr($key, 7);
         if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
             $viewOnlyCustomFields[$key] = $value;
         }
     }
     // special case to set values for view only, CRM-5362
     if (!empty($viewOnlyCustomFields)) {
         $viewOnlyCustomFields['entityID'] = $mainId;
         CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
     }
     if (!$checkPermissions || CRM_Core_Permission::check('merge duplicate contacts') && CRM_Core_Permission::check('delete contacts')) {
         // if ext id is submitted then set it null for contact to be deleted
         if (!empty($submitted['external_identifier'])) {
             $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
             CRM_Core_DAO::executeQuery($query);
         }
         civicrm_api3('contact', 'delete', array('id' => $otherId));
     }
     // CRM-15681 merge sub_types
     if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
         if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
             $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
         } else {
             $submitted['contact_sub_type'] = $other_sub_types;
         }
     }
     // **** Update contact related info for the main contact
     if (!empty($submitted)) {
         $submitted['contact_id'] = $mainId;
         //update current employer field
         if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
             if (!CRM_Utils_System::isNull($currentEmloyerId)) {
                 $submitted['current_employer'] = $submitted['current_employer_id'];
             } else {
                 $submitted['current_employer'] = '';
             }
             unset($submitted['current_employer_id']);
         }
         //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
         if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
             $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
         }
         if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
             $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
         }
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
     }
     CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
     self::createMergeActivities($mainId, $otherId);
     return TRUE;
 }
예제 #13
0
 /**
  * test case for deleteContact( )
  */
 function testDeleteContact()
 {
     $contactParams = $this->contactParams();
     //create contact
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact = CRM_Contact_BAO_Contact::create($contactParams);
     $contactId = $contact->id;
     //delete contact.
     CRM_Contact_BAO_Contact::deleteContact($contactId);
     //Now check DB for location elements.
     //Now check DB for Address
     $this->assertDBNull('CRM_Core_DAO_Address', CRM_Utils_Array::value('street_address', $contactParams['address'][1]), 'id', 'street_address', 'Database check, Address deleted successfully.');
     //Now check DB for Email
     $this->assertDBNull('CRM_Core_DAO_Email', CRM_Utils_Array::value('email', $contactParams['email'][1]), 'id', 'email', 'Database check, Email deleted successfully.');
     //Now check DB for Phone
     $this->assertDBNull('CRM_Core_DAO_Phone', CRM_Utils_Array::value('phone', $contactParams['phone'][1]), 'id', 'phone', 'Database check, Phone deleted successfully.');
     //Now check DB for Mobile
     $this->assertDBNull('CRM_Core_DAO_Phone', CRM_Utils_Array::value('phone', $contactParams['phone'][2]), 'id', 'phone', 'Database check, Mobile deleted successfully.');
     //Now check DB for IM
     $this->assertDBNull('CRM_Core_DAO_IM', CRM_Utils_Array::value('name', $contactParams['im'][1]), 'id', 'name', 'Database check, IM deleted successfully.');
     //Now check DB for openId
     $this->assertDBNull('CRM_Core_DAO_OpenID', CRM_Utils_Array::value('openid', $contactParams['openid'][1]), 'id', 'name', 'Database check, openId deleted successfully.');
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     // Check that the custom field value is no longer present
     $params = array('entityID' => $contactId, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals(CRM_Utils_Array::value("custom_{$fieldID}", $values), '', 'Verify that the data value is empty for contact ' . $contactId);
     $this->assertEquals($values['is_error'], 1, 'Verify that is_error = 0 (success).');
     //Now check DB for contact.
     $this->assertDBNull('CRM_Contact_DAO_Contact', $contactParams['last_name'] . ', ' . $contactParams['first_name'], 'id', 'sort_name', 'Database check, contact deleted successfully.');
 }
예제 #14
0
/**
 * Implementation of hook_civicrm_buildForm
 *
 * @params string $formName - the name of the form
 *         object $form - reference to the form object
 * @return void
 */
function hrrecruitment_civicrm_buildForm($formName, &$form)
{
    $caseTypes = CRM_Case_PseudoConstant::caseType('name');
    $appValue = array_search('Application', $caseTypes);
    //To hide application case type from add assignment form
    if ($formName == 'CRM_Case_Form_Case') {
        if ($form->_action & CRM_Core_Action::DELETE || $form->_action & CRM_Core_Action::RENEW) {
            return;
        }
        $form->_caseType = CRM_Case_PseudoConstant::caseType();
        unset($form->_caseType[$appValue]);
        $form->add('select', 'case_type_id', ts('Assignment Type'), $form->_caseType, TRUE);
    }
    //report change
    if ($formName == 'CRM_Report_Form_Case_Summary' || $formName == 'CRM_Report_Form_Case_Detail') {
        $statuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE, 'AND filter = 1', TRUE);
        $form->case_statuses = $form->case_statuses + $statuses;
    }
    if ($formName == 'CRM_Activity_Form_Search') {
        $actId = CRM_Utils_Request::retrieve('type', 'Positive', $form);
        $form->_formValues['activity_type_id'][$actId] = $defaults['activity_type_id'][$actId] = 1;
        $form->setDefaults($defaults);
        $form->set('formValues', $form->_formValues);
        $form->preProcess();
    }
    if ($formName == 'CRM_Case_Form_CaseView') {
        $params = array('id' => $form->_caseID);
        CRM_Core_DAO::commonRetrieve('CRM_Case_BAO_Case', $params, $values, array('status_id'));
        $statuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE, 'AND (filter IN (0,1) OR filter IS NULL)', TRUE);
        $form->_caseDetails['case_status'] = $statuses[$values['case_status_id']];
        $form->assign('caseDetails', $form->_caseDetails);
    }
    if ($formName == 'CRM_Case_Form_Activity' || $formName == 'CRM_Contact_Form_Task_Email') {
        $caseId = CRM_Utils_Request::retrieve('caseid', 'String', $form);
        $vacancyID = CRM_HRRecruitment_BAO_HRVacancy::getVacancyIDByCase($caseId);
        $caseId = explode(',', $caseId);
        $aType = CRM_Utils_Request::retrieve('atype', 'Positive') ? CRM_Utils_Request::retrieve('atype', 'Positive') : CRM_Utils_Array::value('activity_type_id', $form->_defaultValues);
        $evalID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Evaluation');
        /* Check for proper permissions */
        if ($vacancyID && $aType) {
            $administerper = CRM_HRRecruitment_BAO_HRVacancyPermission::checkVacancyPermission($vacancyID, array("administer Vacancy", "administer CiviCRM", "manage Applicants"));
            $evaluateper = CRM_HRRecruitment_BAO_HRVacancyPermission::checkVacancyPermission($vacancyID, array("administer Vacancy", "administer CiviCRM", "evaluate Applicants"));
            if ($aType != $evalID && !$administerper || $aType == $evalID && !$evaluateper) {
                CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm'));
                CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to perform this action.'));
                return;
            }
        }
        /* TO set vacancy stages as case status for 'Change Case Status' activity */
        if ($aType == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Case Status')) {
            $allcase = TRUE;
            foreach ($caseId as $key => $val) {
                $caseType = CRM_Case_BAO_Case::getCaseType($val, 'id');
                if ($caseType != $appValue) {
                    $allcase = FALSE;
                }
            }
            if ($allcase) {
                $form->removeElement('case_status_id');
                $form->_caseStatus = CRM_Case_PseudoConstant::caseStatus('label', TRUE, 'AND filter = 1', TRUE);
                $form->add('select', 'case_status_id', ts('Case Status'), $form->_caseStatus, TRUE);
                if ($caseStatusId = CRM_Utils_Request::retrieve('case_status_id', 'Positive', $form)) {
                    $form->freeze('case_status_id');
                    $form->setDefaults(array('case_status_id' => $caseStatusId));
                }
            }
        }
        /* build the evaluation profile on the evaluation activity */
        //check for evaluation activity type
        if ($aType == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Evaluation')) {
            //rename label and status name for Activity Status
            $activityStatus = $form->getElement('status_id');
            $activityStatus->_options = array();
            $scheduleStatus = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled');
            $completeStatus = CRM_Core_OptionGroup::getValue('activity_status', 'Completed');
            $activityStatus->addOption('Scheduled', $scheduleStatus);
            $activityStatus->addOption('Complete Evaluation', $completeStatus);
            $activityStatus->_label = 'Evaluation Status';
            //retriev Case ID, Activity ID, Contact ID
            $caseID = CRM_Utils_Request::retrieve('caseid', 'Positive', $form);
            $activityID = CRM_Utils_Request::retrieve('id', 'Positive', $form);
            $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $form);
            //get Evaluation profile ID
            $dao = new CRM_Core_DAO_UFJoin();
            $dao->module = 'Vacancy';
            $dao->entity_id = CRM_HRRecruitment_BAO_HRVacancy::getVacancyIDByCase($caseID);
            $dao->module_data = 'evaluation_profile';
            $dao->find(TRUE);
            $profileID = $dao->uf_group_id;
            $profileFields = CRM_Core_BAO_UFGroup::getFields($profileID);
            $form->assign('fields', $profileFields);
            CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $profileFields, $def);
            $form->setDefaults($def);
            //auto populate assignee contact name with vacancy related permission
            if ($form->_action & CRM_Core_Action::ADD) {
                $evaluateContactID = CRM_HRRecruitment_BAO_HRVacancyPermission::getPermissionContact($vacancyID, 'evaluate Applicants');
                $defaults['assignee_contact_id'] = $evaluateContactID;
                $form->setDefaults($defaults);
            }
            //build evaluaiton profile fields
            foreach ($profileFields as $profileFieldKey => $profileFieldVal) {
                CRM_Core_BAO_UFGroup::buildProfile($form, $profileFieldVal, CRM_Profile_Form::MODE_EDIT, $contactID, TRUE, FALSE, NULL);
                $form->_fields[$profileFieldKey] = $profileFields[$profileFieldKey];
                $params[$profileFieldKey] = $profileFieldVal;
            }
            if (!empty($activityID)) {
                $params['entityID'] = $activityID;
                $form->addElement('hidden', 'evaluationProfile', $profileID);
                $defVal = CRM_Core_BAO_CustomValueTable::getValues($params);
                $form->setDefaults($defVal);
            }
            CRM_Core_Region::instance('case-activity-form')->add(array('template' => 'CRM/UF/Form/Block.tpl'));
        }
        //HR-373 -- set Completed status for Comment activity by default
        if ($aType == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Comment')) {
            $defaults['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed');
            $form->setDefaults($defaults);
        }
    }
    /* HR-401 Changes to Edit Evaluation and Application popups */
    if ($formName == 'CRM_Custom_Form_Field' || $formName == 'CRM_HRRecruitment_Form_HRVacancy') {
        $uncolapseAppl = $uncolapseEval = array();
        $applicationCG = civicrm_api3('CustomGroup', 'get', array('extends' => "Case", 'extends_entity_column_value' => $appValue, 'name' => 'Application'));
        foreach ($applicationCG['values'] as $k => $v) {
            $uncolapseAppl[] = $v['id'];
        }
        $evalCG = civicrm_api3('CustomGroup', 'get', array('extends' => "Activity", 'extends_entity_column_value' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Evaluation')));
        foreach ($evalCG['values'] as $k => $v) {
            $uncolapseEval[$k] = $v['id'];
        }
        CRM_Core_Resources::singleton()->addSetting(array('profileSelectorSet' => array('application' => $uncolapseAppl, 'evaluation' => $uncolapseEval)));
        $gID = CRM_Utils_Array::value('gid', $_GET);
        /* HR-401 set default for 'Is field searchable' */
        if (!empty($gID) && (in_array($gID, $uncolapseEval) || in_array($gID, $uncolapseAppl)) && $formName == 'CRM_Custom_Form_Field') {
            $default['is_searchable'] = 1;
            $form->setDefaults($default);
        }
    }
}
예제 #15
0
 /**
  * Test case for deleteContact( ).
  */
 public function testDeleteContact()
 {
     $contactParams = $this->contactParams();
     $customGroup = $this->customGroupCreate();
     $fields = array('label' => 'testFld', 'data_type' => 'String', 'html_type' => 'Text', 'custom_group_id' => $customGroup['id']);
     $customField = CRM_Core_BAO_CustomField::create($fields);
     $contactParams['custom'] = array($customField->id => array(-1 => array('value' => 'Test custom value', 'type' => 'String', 'custom_field_id' => $customField->id, 'custom_group_id' => $customGroup['id'], 'table_name' => $customGroup['values'][$customGroup['id']]['table_name'], 'column_name' => $customField->column_name, 'file_id' => NULL)));
     //create contact
     $contact = CRM_Contact_BAO_Contact::create($contactParams);
     $contactId = $contact->id;
     //delete contact permanently.
     CRM_Contact_BAO_Contact::deleteContact($contactId, FALSE, TRUE);
     //Now check DB for location elements.
     //Now check DB for Address
     $this->assertDBNull('CRM_Core_DAO_Address', $contactId, 'id', 'street_address', 'Database check, Address deleted successfully.');
     //Now check DB for Email
     $this->assertDBNull('CRM_Core_DAO_Email', $contactId, 'id', 'email', 'Database check, Email deleted successfully.');
     //Now check DB for Phone
     $this->assertDBNull('CRM_Core_DAO_Phone', $contactId, 'id', 'phone', 'Database check, Phone deleted successfully.');
     //Now check DB for Mobile
     $this->assertDBNull('CRM_Core_DAO_Phone', $contactId, 'id', 'phone', 'Database check, Mobile deleted successfully.');
     //Now check DB for IM
     $this->assertDBNull('CRM_Core_DAO_IM', $contactId, 'id', 'name', 'Database check, IM deleted successfully.');
     //Now check DB for openId
     $this->assertDBNull('CRM_Core_DAO_OpenID', $contactId, 'id', 'openid', 'Database check, openId deleted successfully.');
     // Check that the custom field value is no longer present
     $params = array('entityID' => $contactId, 'custom_' . $customField->id => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals(CRM_Utils_Array::value("custom_" . $customField->id, $values), '', 'Verify that the data value is empty for contact ' . $contactId);
     $this->assertEquals($values['is_error'], 1, 'Verify that is_error = 0 (success).');
     //Now check DB for contact.
     $this->assertDBNull('CRM_Contact_DAO_Contact', $contactId, 'id', 'sort_name', 'Database check, contact deleted successfully.');
     $this->quickCleanup(array('civicrm_contact', 'civicrm_note'));
     $this->customGroupDelete($customGroup['id']);
 }
예제 #16
0
 public function testCustomGroupMultiple()
 {
     $params = array();
     $contactID = $this->individualCreate();
     $customGroup = $this->customGroupCreate();
     $fields = array('custom_group_id' => $customGroup['id'], 'data_type' => 'String', 'html_type' => 'Text');
     $customField = $this->customFieldCreate($fields);
     $params = array('entityID' => $contactID, 'custom_' . $customField['id'] . '_-1' => 'First String');
     $error = CRM_Core_BAO_CustomValueTable::setValues($params);
     $newParams = array('entityID' => $contactID, 'custom_' . $customField['id'] => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($newParams);
     $this->assertEquals($params['custom_' . $customField['id'] . '_-1'], $result['custom_' . $customField['id']]);
     $this->assertEquals($params['entityID'], $result['entityID']);
     $this->customFieldDelete($customField['id']);
     $this->customGroupDelete($customGroup['id']);
     $this->contactDelete($contactID);
 }
예제 #17
0
 function testSetGetValuesYesNoRadio()
 {
     $params = array();
     $contactID = Contact::createIndividual();
     //create Custom Group
     $customGroup = Custom::createGroup($params, 'Individual', true);
     //create Custom Field of type YesNo(Boolean) Radio
     $fields = array('groupId' => $customGroup->id, 'dataType' => 'Boolean', 'htmlType' => 'Radio');
     $customField = Custom::createField($params, $fields);
     // Retrieve the field ID for sample custom field 'test_Boolean'
     $params = array('label' => 'test_Boolean');
     $field = array();
     //get field Id
     require_once 'CRM/Core/BAO/CustomField.php';
     CRM_Core_BAO_CustomField::retrieve($params, $field);
     $fieldID = $field['id'];
     // valid boolean value '1' for Boolean Radio
     $yesNo = '1';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $yesNo);
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     $this->assertEquals($result['is_error'], 0, 'Verify that is_error = 0 (success).');
     // Check that the YesNo radio value is stored
     $values = array();
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).');
     $this->assertEquals($values['custom_1_1'], $yesNo, 'Verify that the date value is stored for contact ' . $contactID);
     // Now set YesNo radio to an invalid boolean value and try to reset
     $badYesNo = '20';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $badYesNo);
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     // Check that the error flag is set AND that custom date value has not been modified
     $this->assertEquals($result['is_error'], $yesNo, 'Verify that is_error = 1 when bad boolen value is passed.');
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['custom_1_1'], $yesNo, 'Verify that the date value has NOT been updated for contact ' . $contactID);
     // Cleanup
     Custom::deleteField($customField);
     Custom::deleteGroup($customGroup);
     Contact::delete($contactID);
 }