public function testGetDisplayedValues()
 {
     $customGroup = Custom::createGroup(array(), 'Individual');
     $fieldsToCreate = array(array('data_type' => 'Country', 'html_type' => 'Select Country', 'tests' => array('UNITED STATES' => 1228, '' => NULL)), array('data_type' => 'StateProvince', 'html_type' => 'Multi-Select State/Province', 'tests' => array('' => 0, 'Alabama' => 1000, 'Alabama, Alaska' => array(1000, 1001))), array('data_type' => 'String', 'html_type' => 'Radio', 'option_values' => array('key' => 'KeyLabel'), 'tests' => array('KeyLabel' => 'key')), array('data_type' => 'String', 'html_type' => 'CheckBox', 'option_values' => array('key1' => 'Label1', 'key2' => 'Label2', 'key3' => 'Label3', 'key4' => 'Label4'), 'tests' => array('Label1' => array('key1'), 'Label2' => 'key2', 'Label2, Label3' => array('key2', 'key3'), 'Label3, Label4' => CRM_Utils_Array::implodePadded(array('key3', 'key4')), 'Label1, Label4' => array('key1' => 1, 'key4' => 1))), array('data_type' => 'Date', 'html_type' => 'Select Date', 'date_format' => 'd M yy', 'time_format' => 1, 'tests' => array('1 Jun 1999 1:30PM' => '1999-06-01 13:30', '' => '')));
     foreach ($fieldsToCreate as $num => $field) {
         $params = $field + array('label' => 'test field ' . $num, 'custom_group_id' => $customGroup->id);
         unset($params['tests']);
         $createdField = $this->callAPISuccess('customField', 'create', $params);
         foreach ($field['tests'] as $expected => $input) {
             $this->assertEquals($expected, CRM_Core_BAO_CustomField::displayValue($input, $createdField['id']));
         }
     }
     Custom::deleteGroup($customGroup);
 }
Exemple #2
0
 /**
  * Takes an associative array and creates a price set object.
  *
  * @param array $params
  *   (reference) an assoc array of name/value pairs.
  *
  * @return CRM_Price_DAO_PriceSet
  */
 public static function create(&$params)
 {
     if (empty($params['id']) && empty($params['name'])) {
         $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
     }
     if (!empty($params['extends']) && is_array($params['extends'])) {
         $params['extends'] = CRM_Utils_Array::implodePadded($params['extends']);
     }
     $priceSetBAO = new CRM_Price_BAO_PriceSet();
     $priceSetBAO->copyValues($params);
     if (self::eventPriceSetDomainID()) {
         $priceSetBAO->domain_id = CRM_Core_Config::domainID();
     }
     return $priceSetBAO->save();
 }
 /**
  * When changing the value of an option this is called to update all corresponding custom data
  *
  * @param int $optionId
  * @param string $newValue
  */
 public static function updateValue($optionId, $newValue)
 {
     $optionValue = new CRM_Core_DAO_OptionValue();
     $optionValue->id = $optionId;
     $optionValue->find(TRUE);
     $oldValue = $optionValue->value;
     if ($oldValue == $newValue) {
         return;
     }
     $customField = new CRM_Core_DAO_CustomField();
     $customField->option_group_id = $optionValue->option_group_id;
     $customField->find();
     while ($customField->fetch()) {
         $customGroup = new CRM_Core_DAO_CustomGroup();
         $customGroup->id = $customField->custom_group_id;
         $customGroup->find(TRUE);
         if (CRM_Core_BAO_CustomField::isSerialized($customField)) {
             $params = array(1 => array(CRM_Utils_Array::implodePadded($oldValue), 'String'), 2 => array(CRM_Utils_Array::implodePadded($newValue), 'String'), 3 => array('%' . CRM_Utils_Array::implodePadded($oldValue) . '%', 'String'));
         } else {
             $params = array(1 => array($oldValue, 'String'), 2 => array($newValue, 'String'), 3 => array($oldValue, 'String'));
         }
         $sql = "UPDATE `{$customGroup->table_name}` SET `{$customField->column_name}` = REPLACE(`{$customField->column_name}`, %1, %2) WHERE `{$customField->column_name}` LIKE %3";
         $customGroup->free();
         CRM_Core_DAO::executeQuery($sql, $params);
     }
     $customField->free();
 }
Exemple #4
0
 /**
  * Common Process.
  *
  * @todo Document what I do.
  *
  * @param array $params
  */
 public function commonProcess(&$params)
 {
     // save autocomplete search options
     if (!empty($params['contact_autocomplete_options'])) {
         Civi::settings()->set('contact_autocomplete_options', CRM_Utils_Array::implodePadded(array_keys($params['contact_autocomplete_options'])));
         unset($params['contact_autocomplete_options']);
     }
     // save autocomplete contact reference options
     if (!empty($params['contact_reference_options'])) {
         Civi::settings()->set('contact_reference_options', CRM_Utils_Array::implodePadded(array_keys($params['contact_reference_options'])));
         unset($params['contact_reference_options']);
     }
     // save components to be enabled
     if (array_key_exists('enableComponents', $params)) {
         civicrm_api3('setting', 'create', array('enable_components' => $params['enableComponents']));
         unset($params['enableComponents']);
     }
     // verify ssl peer option
     if (isset($params['verifySSL'])) {
         Civi::settings()->set('verifySSL', $params['verifySSL']);
         unset($params['verifySSL']);
     }
     // force secure URLs
     if (isset($params['enableSSL'])) {
         Civi::settings()->set('enableSSL', $params['enableSSL']);
         unset($params['enableSSL']);
     }
     $settings = array_intersect_key($params, $this->_settings);
     $result = civicrm_api('setting', 'create', $settings + array('version' => 3));
     foreach ($settings as $setting => $settingGroup) {
         //@todo array_diff this
         unset($params[$setting]);
     }
     if (!empty($result['error_message'])) {
         CRM_Core_Session::setStatus($result['error_message'], ts('Save Failed'), 'error');
     }
     //CRM_Core_BAO_ConfigSetting::create($params);
     $params = CRM_Core_BAO_ConfigSetting::filterSkipVars($params);
     if (!empty($params)) {
         CRM_Core_Error::fatal('Unrecognized setting. This may be a config field which has not been properly migrated to a setting. (' . implode(', ', array_keys($params)) . ')');
     }
     CRM_Core_Config::clearDBCache();
     CRM_Utils_System::flushCache();
     CRM_Core_Resources::singleton()->resetCacheCode();
     CRM_Core_Session::setStatus(" ", ts('Changes Saved'), "success");
 }
 /**
  * Determine if there are any CustomGroups for the given $activityTypeId.
  * If none found, create one.
  *
  * @param int $activityTypeId
  *
  * @return bool
  *   TRUE if a group is found or created; FALSE on error
  */
 public static function autoCreateByActivityType($activityTypeId)
 {
     if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) {
         return TRUE;
     }
     $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
     // everything
     $params = array('version' => 3, 'extends' => 'Activity', 'extends_entity_column_id' => NULL, 'extends_entity_column_value' => CRM_Utils_Array::implodePadded(array($activityTypeId)), 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])), 'style' => 'Inline', 'is_active' => 1);
     $result = civicrm_api('CustomGroup', 'create', $params);
     return !$result['is_error'];
 }
 /**
  * Schedule message delivery for any contribution, regardless of type.
  */
 public function scheduleForAny()
 {
     $actTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id');
     $this->schedule->mapping_id = CRM_Activity_ActionMapping::ACTIVITY_MAPPING_ID;
     $this->schedule->start_action_date = 'receive_date';
     $this->schedule->entity_value = CRM_Utils_Array::implodePadded(array_keys($actTypes));
     $this->schedule->entity_status = CRM_Utils_Array::implodePadded(NULL);
 }
Exemple #7
0
/**
 * Check parameters passed in.
 *
 * This function is on it's way out.
 *
 * @param array $params
 * @param bool $dupeCheck
 *
 * @return null
 * @throws API_Exception
 * @throws CiviCRM_API3_Exception
 */
function _civicrm_api3_contact_check_params(&$params, $dupeCheck)
{
    switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
        case 'household':
            civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
            break;
        case 'organization':
            civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
            break;
        case 'individual':
            civicrm_api3_verify_one_mandatory($params, NULL, array('first_name', 'last_name', 'email', 'display_name'));
            break;
    }
    // Fixme: This really needs to be handled at a lower level. @See CRM-13123
    if (isset($params['preferred_communication_method'])) {
        $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
    }
    if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
        if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type'])) {
            throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
        }
    }
    if ($dupeCheck) {
        // check for record already existing
        $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
        // CRM-6431
        // setting 'check_permission' here means that the dedupe checking will be carried out even if the
        // person does not have permission to carry out de-dupes
        // this is similar to the front end form
        if (isset($params['check_permission'])) {
            $dedupeParams['check_permission'] = $params['check_permission'];
        }
        $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
        if (count($ids) > 0) {
            throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
        }
    }
    // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
    if (!empty($params['current_employer'])) {
        $organizationParams = array('organization_name' => $params['current_employer']);
        $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
        $dedupParams['check_permission'] = FALSE;
        $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
        // check for mismatch employer name and id
        if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
            throw new API_Exception('Employer name and Employer id Mismatch');
        }
        // show error if multiple organisation with same name exist
        if (empty($params['employer_id']) && count($dupeIds) > 1) {
            throw new API_Exception('Found more than one Organisation with same Name.');
        }
        if ($dupeIds) {
            $params['employer_id'] = $dupeIds[0];
        } else {
            $result = civicrm_api3('Contact', 'create', array('organization_name' => $params['current_employer'], 'contact_type' => 'Organization'));
            $params['employer_id'] = $result['id'];
        }
    }
    return NULL;
}
Exemple #8
0
/**
 * Validate & swap out any pseudoconstants / options.
 *
 * @param mixed $fieldValue
 * @param string $entity : api entity name
 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
 * @param array $fieldInfo : getfields meta-data
 *
 * @throws \API_Exception
 */
function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo)
{
    $options = CRM_Utils_Array::value('options', $fieldInfo);
    if (!$options) {
        if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
            // We need to get the options from the entity the field relates to.
            $entity = $fieldInfo['entity'];
        }
        $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
        $options = CRM_Utils_Array::value('values', $options, array());
    }
    // If passed a value-separated string, explode to an array, then re-implode after matching values.
    $implode = FALSE;
    if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
        $fieldValue = CRM_Utils_Array::explodePadded($fieldValue);
        $implode = TRUE;
    }
    // If passed multiple options, validate each.
    if (is_array($fieldValue)) {
        foreach ($fieldValue as &$value) {
            if (!is_array($value)) {
                _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
            }
        }
        // TODO: unwrap the call to implodePadded from the conditional and do it always
        // need to verify that this is safe and doesn't break anything though.
        // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
        if ($implode) {
            CRM_Utils_Array::implodePadded($fieldValue);
        }
    } else {
        _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
    }
}
 /**
  * Format custom fields before inserting.
  *
  * @param int $customFieldId
  *   Custom field id.
  * @param array $customFormatted
  *   Formatted array.
  * @param mixed $value
  *   Value of custom field.
  * @param string $customFieldExtend
  *   Custom field extends.
  * @param int $customValueId
  *   Custom option value id.
  * @param int $entityId
  *   Entity id (contribution, membership...).
  * @param bool $inline
  *   Consider inline custom groups only.
  * @param bool $checkPermission
  *   If false, do not include permissioning clause.
  * @param bool $includeViewOnly
  *   If true, fields marked 'View Only' are included. Required for APIv3.
  *
  * @return array|NULL
  *   formatted custom field array
  */
 public static function formatCustomField($customFieldId, &$customFormatted, $value, $customFieldExtend, $customValueId = NULL, $entityId = NULL, $inline = FALSE, $checkPermission = TRUE, $includeViewOnly = FALSE)
 {
     //get the custom fields for the entity
     //subtype and basic type
     $customDataSubType = NULL;
     if ($customFieldExtend) {
         // This is the case when getFieldsForImport() requires fields
         // of subtype and its parent.CRM-5143
         // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
         $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
         if (!empty($customDataSubType) && is_array($customDataSubType)) {
             $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
             if (is_array($customFieldExtend)) {
                 $customFieldExtend = array_unique(array_values($customFieldExtend));
             }
         }
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend, FALSE, $inline, $customDataSubType, NULL, FALSE, FALSE, $checkPermission);
     if (!array_key_exists($customFieldId, $customFields)) {
         return NULL;
     }
     // return if field is a 'code' field
     if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
         return NULL;
     }
     list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
     if (!$customValueId && !$customFields[$customFieldId]['is_multiple'] && $entityId) {
         $query = "\nSELECT id\n  FROM {$tableName}\n WHERE entity_id={$entityId}";
         $customValueId = CRM_Core_DAO::singleValueQuery($query);
     }
     //fix checkbox, now check box always submits values
     if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
         if ($value) {
             // Note that only during merge this is not an array, and you can directly use value
             if (is_array($value)) {
                 $selectedValues = array();
                 foreach ($value as $selId => $val) {
                     if ($val) {
                         $selectedValues[] = $selId;
                     }
                 }
                 if (!empty($selectedValues)) {
                     $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $selectedValues) . CRM_Core_DAO::VALUE_SEPARATOR;
                 } else {
                     $value = '';
                 }
             }
         }
     }
     if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' || $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select') {
         if ($value) {
             $value = CRM_Utils_Array::implodePadded($value);
         } else {
             $value = '';
         }
     }
     if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' || $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' || $customFields[$customFieldId]['html_type'] == 'CheckBox') && $customFields[$customFieldId]['data_type'] == 'String' && !empty($customFields[$customFieldId]['text_length']) && !empty($value)) {
         // lets make sure that value is less than the length, else we'll
         // be losing some data, CRM-7481
         if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
             // need to do a few things here
             // 1. lets find a new length
             $newLength = $customFields[$customFieldId]['text_length'];
             $minLength = strlen($value);
             while ($newLength < $minLength) {
                 $newLength = $newLength * 2;
             }
             // set the custom field meta data to have a length larger than value
             // alter the custom value table column to match this length
             CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
         }
     }
     $date = NULL;
     if ($customFields[$customFieldId]['data_type'] == 'Date') {
         if (!CRM_Utils_System::isNull($value)) {
             $format = $customFields[$customFieldId]['date_format'];
             $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
         }
         $value = $date;
     }
     if ($customFields[$customFieldId]['data_type'] == 'Float' || $customFields[$customFieldId]['data_type'] == 'Money') {
         if (!$value) {
             $value = 0;
         }
         if ($customFields[$customFieldId]['data_type'] == 'Money') {
             $value = CRM_Utils_Rule::cleanMoney($value);
         }
     }
     if (($customFields[$customFieldId]['data_type'] == 'StateProvince' || $customFields[$customFieldId]['data_type'] == 'Country') && empty($value)) {
         // CRM-3415
         $value = 0;
     }
     $fileId = NULL;
     if ($customFields[$customFieldId]['data_type'] == 'File') {
         if (empty($value)) {
             return;
         }
         $config = CRM_Core_Config::singleton();
         $fName = $value['name'];
         $mimeType = $value['type'];
         // If we are already passing the file id as a value then retrieve and set the file data
         if (CRM_Utils_Rule::integer($value)) {
             $fileDAO = new CRM_Core_DAO_File();
             $fileDAO->id = $value;
             $fileDAO->find(TRUE);
             if ($fileDAO->N) {
                 $fileID = $value;
                 $fName = $fileDAO->uri;
                 $mimeType = $fileDAO->mime_type;
             }
         }
         $filename = pathinfo($fName, PATHINFO_BASENAME);
         // rename this file to go into the secure directory only if
         // user has uploaded new file not existing verfied on the basis of $fileID
         if (empty($fileID) && !rename($fName, $config->customFileUploadDir . $filename)) {
             CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
         }
         if ($customValueId && empty($fileID)) {
             $query = "\nSELECT {$columnName}\n  FROM {$tableName}\n WHERE id = %1";
             $params = array(1 => array($customValueId, 'Integer'));
             $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
         }
         $fileDAO = new CRM_Core_DAO_File();
         if ($fileId) {
             $fileDAO->id = $fileId;
         }
         $fileDAO->uri = $filename;
         $fileDAO->mime_type = $mimeType;
         $fileDAO->upload_date = date('Ymdhis');
         $fileDAO->save();
         $fileId = $fileDAO->id;
         $value = $filename;
     }
     if (!is_array($customFormatted)) {
         $customFormatted = array();
     }
     if (!array_key_exists($customFieldId, $customFormatted)) {
         $customFormatted[$customFieldId] = array();
     }
     $index = -1;
     if ($customValueId) {
         $index = $customValueId;
     }
     if (!array_key_exists($index, $customFormatted[$customFieldId])) {
         $customFormatted[$customFieldId][$index] = array();
     }
     $customFormatted[$customFieldId][$index] = array('id' => $customValueId > 0 ? $customValueId : NULL, 'value' => $value, 'type' => $customFields[$customFieldId]['data_type'], 'custom_field_id' => $customFieldId, 'custom_group_id' => $groupID, 'table_name' => $tableName, 'column_name' => $columnName, 'file_id' => $fileId, 'is_multiple' => $customFields[$customFieldId]['is_multiple']);
     //we need to sort so that custom fields are created in the order of entry
     krsort($customFormatted[$customFieldId]);
     return $customFormatted;
 }
Exemple #10
0
 /**
  * Format profile contact parameters.
  *
  * @param array $params
  * @param $fields
  * @param int $contactID
  * @param int $ufGroupId
  * @param null $ctype
  * @param bool $skipCustom
  *
  * @return array
  */
 public static function formatProfileContactParams(&$params, &$fields, $contactID = NULL, $ufGroupId = NULL, $ctype = NULL, $skipCustom = FALSE)
 {
     $data = $contactDetails = array();
     // get the contact details (hier)
     if ($contactID) {
         list($details, $options) = self::getHierContactDetails($contactID, $fields);
         $contactDetails = $details[$contactID];
         $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails);
         $data['contact_sub_type'] = CRM_Utils_Array::value('contact_sub_type', $contactDetails);
     } else {
         //we should get contact type only if contact
         if ($ufGroupId) {
             $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId);
             //special case to handle profile with only contact fields
             if ($data['contact_type'] == 'Contact') {
                 $data['contact_type'] = 'Individual';
             } elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) {
                 $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']);
             }
         } elseif ($ctype) {
             $data['contact_type'] = $ctype;
         } else {
             $data['contact_type'] = 'Individual';
         }
     }
     //fix contact sub type CRM-5125
     if (array_key_exists('contact_sub_type', $params) && !empty($params['contact_sub_type'])) {
         $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
     } elseif (array_key_exists('contact_sub_type_hidden', $params) && !empty($params['contact_sub_type_hidden'])) {
         // if profile was used, and had any subtype, we obtain it from there
         //CRM-13596 - add to existing contact types, rather than overwriting
         $data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
         if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
             $data['contact_sub_type'] .= CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
         }
     }
     if ($ctype == 'Organization') {
         $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails);
     } elseif ($ctype == 'Household') {
         $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails);
     }
     $locationType = array();
     $count = 1;
     if ($contactID) {
         //add contact id
         $data['contact_id'] = $contactID;
         $primaryLocationType = self::getPrimaryLocationType($contactID);
     } else {
         $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
         $defaultLocationId = $defaultLocation->id;
     }
     $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
     $blocks = array('email', 'phone', 'im', 'openid');
     $multiplFields = array('url');
     // prevent overwritten of formatted array, reset all block from
     // params if it is not in valid format (since import pass valid format)
     foreach ($blocks as $blk) {
         if (array_key_exists($blk, $params) && !is_array($params[$blk])) {
             unset($params[$blk]);
         }
     }
     $primaryPhoneLoc = NULL;
     $session = CRM_Core_Session::singleton();
     foreach ($params as $key => $value) {
         $locTypeId = $typeId = NULL;
         list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3);
         //store original location type id
         $actualLocTypeId = $locTypeId;
         if ($locTypeId == 'Primary') {
             if ($contactID) {
                 if (in_array($fieldName, $blocks)) {
                     $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
                 } else {
                     $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
                 }
                 $primaryLocationType = $locTypeId;
             } else {
                 $locTypeId = $defaultLocationId;
             }
         }
         if (is_numeric($locTypeId) && !in_array($fieldName, $multiplFields) && substr($fieldName, 0, 7) != 'custom_') {
             $index = $locTypeId;
             if (is_numeric($typeId)) {
                 $index .= '-' . $typeId;
             }
             if (!in_array($index, $locationType)) {
                 $locationType[$count] = $index;
                 $count++;
             }
             $loc = CRM_Utils_Array::key($index, $locationType);
             $blockName = in_array($fieldName, $blocks) ? $fieldName : 'address';
             $data[$blockName][$loc]['location_type_id'] = $locTypeId;
             //set is_billing true, for location type "Billing"
             if ($locTypeId == $billingLocationTypeId) {
                 $data[$blockName][$loc]['is_billing'] = 1;
             }
             if ($contactID) {
                 //get the primary location type
                 if ($locTypeId == $primaryLocationType) {
                     $data[$blockName][$loc]['is_primary'] = 1;
                 }
             } elseif ($locTypeId == $defaultLocationId) {
                 $data[$blockName][$loc]['is_primary'] = 1;
             }
             if (in_array($fieldName, array('phone'))) {
                 if ($typeId) {
                     $data['phone'][$loc]['phone_type_id'] = $typeId;
                 } else {
                     $data['phone'][$loc]['phone_type_id'] = '';
                 }
                 $data['phone'][$loc]['phone'] = $value;
                 //special case to handle primary phone with different phone types
                 // in this case we make first phone type as primary
                 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
                     $primaryPhoneLoc = $loc;
                 }
                 if ($loc != $primaryPhoneLoc) {
                     unset($data['phone'][$loc]['is_primary']);
                 }
             } elseif ($fieldName == 'phone_ext') {
                 $data['phone'][$loc]['phone_ext'] = $value;
             } elseif ($fieldName == 'email') {
                 $data['email'][$loc]['email'] = $value;
                 if (empty($contactID)) {
                     $data['email'][$loc]['is_primary'] = 1;
                 }
             } elseif ($fieldName == 'im') {
                 if (isset($params[$key . '-provider_id'])) {
                     $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
                 }
                 if (strpos($key, '-provider_id') !== FALSE) {
                     $data['im'][$loc]['provider_id'] = $params[$key];
                 } else {
                     $data['im'][$loc]['name'] = $value;
                 }
             } elseif ($fieldName == 'openid') {
                 $data['openid'][$loc]['openid'] = $value;
             } else {
                 if ($fieldName === 'state_province') {
                     // CRM-3393
                     if (is_numeric($value) && (int) $value >= 1000) {
                         $data['address'][$loc]['state_province_id'] = $value;
                     } elseif (empty($value)) {
                         $data['address'][$loc]['state_province_id'] = '';
                     } else {
                         $data['address'][$loc]['state_province'] = $value;
                     }
                 } elseif ($fieldName === 'country') {
                     // CRM-3393
                     if (is_numeric($value) && (int) $value >= 1000) {
                         $data['address'][$loc]['country_id'] = $value;
                     } elseif (empty($value)) {
                         $data['address'][$loc]['country_id'] = '';
                     } else {
                         $data['address'][$loc]['country'] = $value;
                     }
                 } elseif ($fieldName === 'county') {
                     $data['address'][$loc]['county_id'] = $value;
                 } elseif ($fieldName == 'address_name') {
                     $data['address'][$loc]['name'] = $value;
                 } elseif (substr($fieldName, 0, 14) === 'address_custom') {
                     $data['address'][$loc][substr($fieldName, 8)] = $value;
                 } else {
                     $data['address'][$loc][$fieldName] = $value;
                 }
             }
         } else {
             if (substr($key, 0, 4) === 'url-') {
                 $websiteField = explode('-', $key);
                 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
                 $data['website'][$websiteField[1]]['url'] = $value;
             } elseif (in_array($key, self::$_greetingTypes, TRUE)) {
                 //save email/postal greeting and addressee values if any, CRM-4575
                 $data[$key . '_id'] = $value;
             } elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
                 // for autocomplete transfer hidden value instead of label
                 if ($params[$key] && isset($params[$key . '_id'])) {
                     $value = $params[$key . '_id'];
                 }
                 // we need to append time with date
                 if ($params[$key] && isset($params[$key . '_time'])) {
                     $value .= ' ' . $params[$key . '_time'];
                 }
                 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
                 if (($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN) == 0 && ($value == '' || !isset($value))) {
                     continue;
                 }
                 $valueId = NULL;
                 if (!empty($params['customRecordValues'])) {
                     if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
                         foreach ($params['customRecordValues'] as $recId => $customFields) {
                             if (is_array($customFields) && !empty($customFields)) {
                                 foreach ($customFields as $customFieldName) {
                                     if ($customFieldName == $key) {
                                         $valueId = $recId;
                                         break;
                                     }
                                 }
                             }
                         }
                     }
                 }
                 //CRM-13596 - check for contact_sub_type_hidden first
                 if (array_key_exists('contact_sub_type_hidden', $params)) {
                     $type = $params['contact_sub_type_hidden'];
                 } else {
                     $type = $data['contact_type'];
                     if (!empty($data['contact_sub_type'])) {
                         $type = $data['contact_sub_type'];
                         $type = CRM_Utils_Array::explodePadded($type);
                         // generally a contact even if, has multiple subtypes the parent-type is going to be one only
                         // and since formatCustomField() would be interested in parent type, lets consider only one subtype
                         // as the results going to be same.
                         $type = $type[0];
                     }
                 }
                 CRM_Core_BAO_CustomField::formatCustomField($customFieldId, $data['custom'], $value, $type, $valueId, $contactID);
             } elseif ($key == 'edit') {
                 continue;
             } else {
                 if ($key == 'location') {
                     foreach ($value as $locationTypeId => $field) {
                         foreach ($field as $block => $val) {
                             if ($block == 'address' && array_key_exists('address_name', $val)) {
                                 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
                             }
                         }
                     }
                 }
                 if ($key == 'phone' && isset($params['phone_ext'])) {
                     $data[$key] = $value;
                     foreach ($value as $cnt => $phoneBlock) {
                         if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
                             $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
                         }
                     }
                 } elseif (in_array($key, array('nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id')) && ($value == '' || !isset($value)) && ($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN) == 0 || $key == 'current_employer' && empty($params['current_employer'])) {
                     // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
                     // to avoid update with empty values
                     continue;
                 } else {
                     $data[$key] = $value;
                 }
             }
         }
     }
     if (!isset($data['contact_type'])) {
         $data['contact_type'] = 'Individual';
     }
     //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
     $privacy = CRM_Core_SelectValues::privacy();
     foreach ($privacy as $key => $value) {
         if (array_key_exists($key, $fields)) {
             // do not reset values for existing contacts, if fields are added to a profile
             if (array_key_exists($key, $params)) {
                 $data[$key] = $params[$key];
                 if (empty($params[$key])) {
                     $data[$key] = 0;
                 }
             } elseif (!$contactID) {
                 $data[$key] = 0;
             }
         }
     }
     return array($data, $contactDetails);
 }
Exemple #11
0
 public function scheduleForSoftCreditor()
 {
     $this->schedule->mapping_id = CRM_Contribute_ActionMapping_ByType::MAPPING_ID;
     $this->schedule->start_action_date = 'receive_date';
     $this->schedule->entity_value = CRM_Utils_Array::implodePadded(NULL);
     $this->schedule->entity_status = CRM_Utils_Array::implodePadded(NULL);
     $this->schedule->limit_to = 1;
     $this->schedule->recipient = 'soft_credit_type';
     $this->schedule->recipient_listing = CRM_Utils_Array::implodePadded(array(3));
 }
 /**
  * Get line item purchase information.
  *
  * This function takes the input parameters and interprets out of it what has been purchased.
  *
  * @param $fields
  *   This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
  *   And, it would make sense to introduce caching into that function and call it from here rather than
  *   require the $fields array which is passed from pillar to post around the form in order to pass it in here.
  * @param array $params
  *   Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
  * @param $lineItem
  *   Line item array to be altered.
  * @param string $component
  *   This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
  *   (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
  */
 public static function processAmount($fields, &$params, &$lineItem, $component = '')
 {
     // using price set
     $totalPrice = $totalTax = 0;
     $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
     if ($component) {
         $autoRenew = array();
         $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
     }
     foreach ($fields as $id => $field) {
         if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) {
             // skip if nothing was submitted for this field
             continue;
         }
         switch ($field['html_type']) {
             case 'Text':
                 $firstOption = reset($field['options']);
                 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
                     $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                     $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                 }
                 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
                     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
                     if (array_key_exists($params['financial_type_id'], $taxRates)) {
                         $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
                         $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
                         $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
                         $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                         $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                     }
                 }
                 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
                 break;
             case 'Radio':
                 //special case if user select -none-
                 if ($params["price_{$id}"] <= 0) {
                     continue;
                 }
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
                 $params['amount_priceset_level_radio'] = array();
                 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
                 if (isset($radioLevel)) {
                     $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio']));
                 } else {
                     $radioLevel = array_keys($params['amount_priceset_level_radio']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                     if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
                         $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
                     }
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'Select':
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_select'] = array();
                 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
                 if (isset($selectLevel)) {
                     $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
                 } else {
                     $selectLevel = array_keys($params['amount_priceset_level_select']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'CheckBox':
                 $params['amount_priceset_level_checkbox'] = $optionIds = array();
                 foreach ($params["price_{$id}"] as $optionId => $option) {
                     $optionIds[] = $optionId;
                     $optionLabel = $field['options'][$optionId]['label'];
                     $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
                     if (isset($checkboxLevel)) {
                         $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox'])));
                     } else {
                         $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
                     }
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 foreach ($optionIds as $optionId) {
                     if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
                         $lineItem = self::setLineItem($field, $lineItem, $optionId);
                         $totalTax += $field['options'][$optionId]['tax_amount'];
                     }
                     $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
                     if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) {
                         $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
                     }
                 }
                 break;
         }
     }
     $amount_level = array();
     $totalParticipant = 0;
     if (is_array($lineItem)) {
         foreach ($lineItem as $values) {
             $totalParticipant += $values['participant_count'];
             // This is a bit nasty. The logic of 'quick config' was because price set configuration was
             // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
             // page.
             //
             // However, because the quick config concept existed all sorts of logic was hung off it
             // and function behaviour sometimes depends on whether 'price set' is set - although actually it
             // is always set at the functional level. In this case we are dealing with the default 'quick config'
             // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
             // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
             // place holder.
             //
             // But, in the interests of being careful when capacity is low - avoiding the known default value
             // will get us by.
             // Crucially a test has been added so a better solution can be implemented later with some comfort.
             // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
             if ($values['label'] != ts('Contribution Amount')) {
                 $amount_level[] = $values['label'] . ' - ' . (double) $values['qty'];
             }
         }
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
     if (!empty($amount_level)) {
         $params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level);
         if (!empty($displayParticipantCount)) {
             $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
         }
     }
     $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
     $params['tax_amount'] = $totalTax;
     if ($component) {
         foreach ($autoRenew as $dontCare => $eachAmount) {
             if (!$eachAmount) {
                 unset($autoRenew[$dontCare]);
             }
         }
         if (count($autoRenew) > 1) {
             $params['autoRenew'] = $autoRenew;
         }
     }
 }