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);
 }
Exemplo n.º 3
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);
 }
 /**
  * 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);
 }
Exemplo n.º 5
0
/**
 * Sets custom values for an entity.
 *
 * @param array $params
 *   Expected keys are in format custom_fieldID:recordID or custom_groupName:fieldName:recordID.
 *
 * @example:
 * @code
 *   // entity ID. You do not need to specify entity type, we figure it out based on the fields you're using
 *   'entity_id' => 123,
 *   // (omitting :id) inserts or updates a field in a single-valued group
 *   'custom_6' => 'foo',
 *   // custom_24 is checkbox or multiselect, so pass items as an array
 *   'custom_24' => array('bar', 'baz'),
 *   // in this case custom_33 is part of a multi-valued group, and we're updating record id 5
 *   'custom_33:5' => value,
 *   // inserts new record in multi-valued group
 *   'custom_33:-1' => value,
 *   // inserts another new record in multi-valued group
 *   'custom_33:-2' => value,
 *   // you can use group_name:field_name instead of ID
 *   'custom_some_group:my_field' => 'myinfo',
 *   // updates record ID 8 in my_other_field in multi-valued some_big_group
 *   'custom_some_big_group:my_other_field:8' => 'myinfo',
 * @endcode
 *
 * @throws Exception
 * @return array
 *   ['values' => TRUE] or ['is_error' => 1, 'error_message' => 'what went wrong']
 */
function civicrm_api3_custom_value_create($params)
{
    // @todo it's not clear where the entity_table is used as  CRM_Core_BAO_CustomValueTable::setValues($create)
    // didn't seem to use it
    // so not clear if it's relevant
    if (!empty($params['entity_table']) && substr($params['entity_table'], 0, 7) == 'civicrm') {
        $params['entity_table'] = substr($params['entity_table'], 8, 7);
    }
    $create = array('entityID' => $params['entity_id']);
    // Translate names and
    //Convert arrays to multi-value strings
    $sp = CRM_Core_DAO::VALUE_SEPARATOR;
    foreach ($params as $id => $param) {
        if (is_array($param)) {
            $param = $sp . implode($sp, $param) . $sp;
        }
        list($c, $id) = CRM_Utils_System::explode('_', $id, 2);
        if ($c != 'custom') {
            continue;
        }
        list($i, $n, $x) = CRM_Utils_System::explode(':', $id, 3);
        if (is_numeric($i)) {
            $key = $i;
            $x = $n;
        } else {
            // Lookup names if ID was not supplied
            $key = CRM_Core_BAO_CustomField::getCustomFieldID($n, $i);
            if (!$key) {
                continue;
            }
        }
        if ($x && is_numeric($x)) {
            $key .= '_' . $x;
        }
        $create['custom_' . $key] = $param;
    }
    $result = CRM_Core_BAO_CustomValueTable::setValues($create);
    if ($result['is_error']) {
        throw new Exception($result['error_message']);
    }
    return civicrm_api3_create_success(TRUE, $params, 'CustomValue');
}
Exemplo n.º 6
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;
 }
Exemplo n.º 7
0
/**
 * Set a single value using the api.
 *
 * This function is called when no specific setvalue api exists.
 * Params must contain at least id=xx & {one of the fields from getfields}=value
 *
 * @param array $apiRequest
 *
 * @throws API_Exception
 * @return array
 */
function civicrm_api3_generic_setValue($apiRequest)
{
    $entity = $apiRequest['entity'];
    $params = $apiRequest['params'];
    $id = $params['id'];
    if (!is_numeric($id)) {
        return civicrm_api3_create_error(ts('Please enter a number'), array('error_code' => 'NaN', 'field' => "id"));
    }
    $field = CRM_Utils_String::munge($params['field']);
    $value = $params['value'];
    $fields = civicrm_api($entity, 'getFields', array('version' => 3, 'action' => 'create', "sequential"));
    // getfields error, shouldn't happen.
    if ($fields['is_error']) {
        return $fields;
    }
    $fields = $fields['values'];
    $isCustom = strpos($field, 'custom_') === 0;
    // Trim off the id portion of a multivalued custom field name
    $fieldKey = $isCustom && substr_count($field, '_') > 1 ? rtrim(rtrim($field, '1234567890'), '_') : $field;
    if (!array_key_exists($fieldKey, $fields)) {
        return civicrm_api3_create_error("Param 'field' ({$field}) is invalid. must be an existing field", array("error_code" => "invalid_field", "fields" => array_keys($fields)));
    }
    $def = $fields[$fieldKey];
    $title = CRM_Utils_Array::value('title', $def, ts('Field'));
    // Disallow empty values except for the number zero.
    // TODO: create a utility for this since it's needed in many places
    if (!empty($def['required']) || !empty($def['is_required'])) {
        if ((empty($value) || $value === 'null') && $value !== '0' && $value !== 0) {
            return civicrm_api3_create_error(ts('%1 is a required field.', array(1 => $title)), array("error_code" => "required", "field" => $field));
        }
    }
    switch ($def['type']) {
        case CRM_Utils_Type::T_FLOAT:
            if (!is_numeric($value) && !empty($value) && $value !== 'null') {
                return civicrm_api3_create_error(ts('%1 must be a number.', array(1 => $title)), array('error_code' => 'NaN'));
            }
            break;
        case CRM_Utils_Type::T_INT:
            if (!CRM_Utils_Rule::integer($value) && !empty($value) && $value !== 'null') {
                return civicrm_api3_create_error(ts('%1 must be a number.', array(1 => $title)), array('error_code' => 'NaN'));
            }
            break;
        case CRM_Utils_Type::T_STRING:
        case CRM_Utils_Type::T_TEXT:
            if (!CRM_Utils_Rule::xssString($value)) {
                return civicrm_api3_create_error(ts('Illegal characters in input (potential scripting attack)'), array('error_code' => 'XSS'));
            }
            if (array_key_exists('maxlength', $def)) {
                $value = substr($value, 0, $def['maxlength']);
            }
            break;
        case CRM_Utils_Type::T_DATE:
            $value = CRM_Utils_Type::escape($value, "Date", FALSE);
            if (!$value) {
                return civicrm_api3_create_error("Param '{$field}' is not a date. format YYYYMMDD or YYYYMMDDHHMMSS");
            }
            break;
        case CRM_Utils_Type::T_BOOLEAN:
            // Allow empty value for non-required fields
            if ($value === '' || $value === 'null') {
                $value = '';
            } else {
                $value = (bool) $value;
            }
            break;
        default:
            return civicrm_api3_create_error("Param '{$field}' is of a type not managed yet (" . $def['type'] . "). Join the API team and help us implement it", array('error_code' => 'NOT_IMPLEMENTED'));
    }
    $dao_name = _civicrm_api3_get_DAO($entity);
    $params = array('id' => $id, $field => $value);
    if ((!empty($def['pseudoconstant']) || !empty($def['option_group_id'])) && $value !== '' && $value !== 'null') {
        _civicrm_api3_api_match_pseudoconstant($params[$field], $entity, $field, $def);
    }
    CRM_Utils_Hook::pre('edit', $entity, $id, $params);
    // Custom fields
    if ($isCustom) {
        CRM_Utils_Array::crmReplaceKey($params, 'id', 'entityID');
        // Treat 'null' as empty value. This is awful but the rest of the code supports it.
        if ($params[$field] === 'null') {
            $params[$field] = '';
        }
        CRM_Core_BAO_CustomValueTable::setValues($params);
        CRM_Utils_Hook::post('edit', $entity, $id, CRM_Core_DAO::$_nullObject);
    } elseif (CRM_Core_DAO::setFieldValue($dao_name, $id, $field, $params[$field])) {
        $entityDAO = new $dao_name();
        $entityDAO->copyValues($params);
        CRM_Utils_Hook::post('edit', $entity, $entityDAO->id, $entityDAO);
    } else {
        return civicrm_api3_create_error("error assigning {$field}={$value} for {$entity} (id={$id})");
    }
    // Add changelog entry - TODO: Should we do this for other entities as well?
    if (strtolower($entity) === 'contact') {
        CRM_Core_BAO_Log::register($id, 'civicrm_contact', $id);
    }
    return civicrm_api3_create_success($params);
}
Exemplo n.º 8
0
 public function postProcess()
 {
     $formValues = $this->exportValues();
     // 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();
     $tableOperations = 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']);
             if (array_key_exists('operation', $formValues)) {
                 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
                     if (array_key_exists($key, $formValues['operation'])) {
                         $tableOperations[$table] = $formValues['operation'][$key];
                     }
                 }
             }
         }
     }
     // 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);
     $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);
             $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, $tableOperations);
     }
     // 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
         if (!empty($fileIds[$this->_cid])) {
             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 view only custom fields CRM-5362
     $viewOnlyCustomFields = array();
     foreach ($submitted as $key => $value) {
         $fid = (int) substr($key, 7);
         if (array_key_exists($fid, $cFields) && CRM_Utils_Array::value('is_view', $cFields[$fid]['attributes'])) {
             $viewOnlyCustomFields[$key] = $value;
         }
     }
     //special case to set values for view only, CRM-5362
     if (!empty($viewOnlyCustomFields)) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         $viewOnlyCustomFields['entityID'] = $this->_cid;
         CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
     }
     // 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('merge duplicate contacts') && CRM_Core_Permission::check('delete contacts')) {
         // if ext id is submitted then set it null for contact to be deleted
         if (CRM_Utils_Array::value('external_identifier', $submitted)) {
             $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$this->_oid}";
             CRM_Core_DAO::executeQuery($query);
         }
         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);
 }
/**
* Sets custom values for an entity.
*
*
* @param $params  expected keys are in format custom_fieldID:recordID or custom_groupName:fieldName:recordID
* for example:
// entity ID. You do not need to specify entity type, we figure it out based on the fields you're using
* 'entity_id' => 123,
// (omitting :id) inserts or updates a field in a single-valued group
* 'custom_6' => 'foo',
// custom_24 is checkbox or multiselect, so pass items as an array
* 'custom_24' => array('bar', 'baz'),
// in this case custom_33 is part of a multi-valued group, and we're updating record id 5
* 'custom_33:5' => value,
// inserts new record in multi-valued group
* 'custom_33:-1' => value,
// inserts another new record in multi-valued group
* 'custom_33:-2' => value,
// you can use group_name:field_name instead of ID
* 'custom_some_group:my_field => 'myinfo',
// updates record ID 8 in my_other_field in multi-valued some_big_group
* 'custom_some_big_group:my_other_field:8 => 'myinfo',
*
*
* @return array('values' => TRUE) or array('is_error' => 1, 'error_message' => 'what went wrong')
*
* @access public
*
*/
function civicrm_api3_custom_value_create($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('entity_id'));
    if (substr($params['entity_table'], 0, 7) == 'civicrm') {
        $params['entity_table'] = substr($params['entity_table'], 8, 7);
    }
    $create = array('entityID' => $params['entity_id']);
    // Translate names and
    //Convert arrays to multi-value strings
    $sp = CRM_Core_DAO::VALUE_SEPARATOR;
    foreach ($params as $id => $param) {
        if (is_array($param)) {
            $param = $sp . implode($sp, $param) . $sp;
        }
        list($c, $id) = explode('_', $id, 2);
        if ($c != 'custom') {
            continue;
        }
        list($i, $n, $x) = explode(':', $id);
        if (is_numeric($i)) {
            $key = $i;
            $x = $n;
        } else {
            // Lookup names if ID was not supplied
            $key = CRM_Core_BAO_CustomField::getCustomFieldID($n, $i);
            if (!$key) {
                continue;
            }
        }
        if ($x && is_numeric($x)) {
            $key .= '_' . $x;
        }
        $create['custom_' . $key] = $param;
    }
    $result = CRM_Core_BAO_CustomValueTable::setValues($create);
    if ($result['is_error']) {
        return civicrm_api3_create_error($result['error_message']);
    }
    return civicrm_api3_create_success(TRUE, $params);
}
Exemplo n.º 10
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;
 }
Exemplo n.º 11
0
/**
 * Implementation of hook_civicrm_postProcess
 *
 * @params string $formName - the name of the form
 *         object $form - reference to the form object
 * @return void
 */
function hrrecruitment_civicrm_postProcess($formName, &$form)
{
    if ($formName == 'CRM_Case_Form_Activity') {
        if (!empty($form->_submitValues['evaluationProfile']) && isset($_POST['new_activity_id'])) {
            //Save evaluation profile fields
            $pID = $form->_submitValues['evaluationProfile'];
            $profileContactType = CRM_Core_BAO_UFGroup::getContactType($pID);
            $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $profileContactType);
            $dedupeParams['check_permission'] = FALSE;
            $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $profileContactType);
            $applicantID = $form->_currentlyViewedContactId;
            if (count($ids)) {
                $applicantID = CRM_Utils_Array::value(0, $ids);
            }
            $applicantID = CRM_Contact_BAO_Contact::createProfileContact($form->_submitValues, CRM_Core_DAO::$_nullArray, $applicantID, NULL, $pID);
            //set custom fields values
            $profileFields = CRM_Core_BAO_UFGroup::getFields($form->_submitValues['evaluationProfile']);
            foreach ($profileFields as $profileFieldKey => $profileFieldVal) {
                $params = array("entityID" => $_POST['new_activity_id'], $profileFieldKey => $form->_submitValues[$profileFieldKey]);
                CRM_Core_BAO_CustomValueTable::setValues($params);
            }
        }
    }
}
Exemplo n.º 12
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);
 }