Example #1
0
 /**
  * This function uses the deprecated v1 datatable api and needs updating. See CRM-16353.
  * @deprecated
  */
 public static function getOptionList()
 {
     $params = $_REQUEST;
     $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
     $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
     $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
     $params['page'] = $offset / $rowCount + 1;
     $params['rp'] = $rowCount;
     $options = CRM_Core_BAO_CustomOption::getOptionListSelector($params);
     $iFilteredTotal = $iTotal = $params['total'];
     $selectorElements = array('label', 'value', 'is_default', 'is_active', 'links', 'class');
     CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
     echo CRM_Utils_JSON::encodeDataTableSelector($options, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
     CRM_Utils_System::civiExit();
 }
Example #2
0
 /** 
  * This function sets the default values for the form. Note that in edit/view mode 
  * the default values are retrieved from the database 
  * 
  * @access public 
  * @return void 
  */
 function setDefaultValues()
 {
     $defaults = parent::setDefaultValues();
     require_once 'CRM/Core/BAO/CustomOption.php';
     CRM_Core_BAO_CustomOption::getAssoc('civicrm_contribution_page', $this->_id, $defaults);
     if (CRM_Utils_Array::value('value', $defaults)) {
         foreach ($defaults['value'] as $i => $v) {
             if ($v == $defaults['default_amount']) {
                 $defaults['default'] = $i;
                 break;
             }
         }
     }
     return $defaults;
 }
Example #3
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 function preProcess()
 {
     // current contribution page id
     $this->_id = $this->get('id');
     // get all the values from the dao object
     $params = array('id' => $this->_id);
     $this->_values = array();
     CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $this->_values);
     // get the amounts and the label
     require_once 'CRM/Core/BAO/CustomOption.php';
     CRM_Core_BAO_CustomOption::getAssoc('civicrm_contribution_page', $this->_id, $this->_values);
     // get the profile ids
     require_once 'CRM/Core/BAO/UFJoin.php';
     $ufJoinParams = array('entity_table' => 'civicrm_contribution_page', 'entity_id' => $this->_id, 'weight' => 1);
     $this->_values['custom_pre_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
     $ufJoinParams['weight'] = 2;
     $this->_values['custom_post_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
 }
Example #4
0
/**
 * take the input parameter list as specified in the data model and 
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs to insert in new contact.
 * @param array  $values       The reformatted properties that we can use internally
 *
 * @param array  $create       Is the formatted Values array going to
 *                             be used for CRM_Activity_BAO_Activity::create()
 *
 * @return array|CRM_Error
 * @access public
 */
function _civicrm_activity_formatted_param(&$params, &$values, $create = false)
{
    $fields =& CRM_Activity_DAO_Activity::fields();
    _civicrm_store_values($fields, $params, $values);
    require_once 'CRM/Core/OptionGroup.php';
    $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        //Handling Custom Data
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            $values[$key] = $value;
            $type = $customFields[$customFieldID]['html_type'];
            if ($type == 'CheckBox' || $type == 'Multi-Select') {
                $mulValues = explode(',', $value);
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                $values[$key] = array();
                foreach ($mulValues as $v1) {
                    foreach ($customOption as $customValueID => $customLabel) {
                        $customValue = $customLabel['value'];
                        if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            if ($type == 'CheckBox') {
                                $values[$key][$customValue] = 1;
                            } else {
                                $values[$key][] = $customValue;
                            }
                        }
                    }
                }
            } else {
                if ($type == 'Select' || $type == 'Radio') {
                    $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                    foreach ($customOption as $customValue => $customLabel) {
                        if (strtolower($customLabel) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            $values[$key] = $customValue;
                        }
                    }
                }
            }
        }
    }
    return null;
}
Example #5
0
 /**
  * Replace all the org-level tokens in $str
  *
  * @param string $str
  *   The string with tokens to be replaced.
  * @param object $org
  *   Associative array of org properties.
  * @param bool $html
  *   Replace tokens with HTML or plain text.
  *
  * @param bool $escapeSmarty
  *
  * @return string
  *   The processed string
  */
 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE)
 {
     self::$_tokens['org'] = array_merge(array_keys(CRM_Contact_BAO_Contact::importableFields('Organization')), array('address', 'display_name', 'checksum', 'contact_id'));
     $cv = NULL;
     foreach (self::$_tokens['org'] as $token) {
         // print "Getting token value for $token<br/><br/>";
         if ($token == '') {
             continue;
         }
         // If the string doesn't contain this token, skip it.
         if (!self::token_match('org', $token, $str)) {
             continue;
         }
         // Construct value from $token and $contact
         $value = NULL;
         if ($cfID = CRM_Core_BAO_CustomField::getKeyID($token)) {
             // only generate cv if we need it
             if ($cv === NULL) {
                 $cv = CRM_Core_BAO_CustomValue::getContactValues($org['contact_id']);
             }
             foreach ($cv as $cvFieldID => $value) {
                 if ($cvFieldID == $cfID) {
                     $value = CRM_Core_BAO_CustomOption::getOptionLabel($cfID, $value);
                     break;
                 }
             }
         } elseif ($token == 'checksum') {
             $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($org['contact_id']);
             $value = "cs={$cs}";
         } elseif ($token == 'address') {
             // Build the location values array
             $loc = array();
             $loc['display_name'] = CRM_Utils_Array::retrieveValueRecursive($org, 'display_name');
             $loc['street_address'] = CRM_Utils_Array::retrieveValueRecursive($org, 'street_address');
             $loc['city'] = CRM_Utils_Array::retrieveValueRecursive($org, 'city');
             $loc['state_province'] = CRM_Utils_Array::retrieveValueRecursive($org, 'state_province');
             $loc['postal_code'] = CRM_Utils_Array::retrieveValueRecursive($org, 'postal_code');
             // Construct the address token
             $value = CRM_Utils_Address::format($loc);
             if ($html) {
                 $value = str_replace("\n", '<br />', $value);
             }
         } else {
             $value = CRM_Utils_Array::retrieveValueRecursive($org, $token);
         }
         self::token_replace('org', $token, $value, $str, $escapeSmarty);
     }
     return $str;
 }
Example #6
0
 /**
  * Process the form
  * 
  * @param null
  * 
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->controller->exportValues('Option');
     // set values for custom field properties and save
     require_once 'CRM/Core/DAO/OptionValue.php';
     require_once 'CRM/Utils/String.php';
     $customOption =& new CRM_Core_DAO_OptionValue();
     $customOption->label = $params['label'];
     $customOption->name = CRM_Utils_String::titleToVar($params['label']);
     $customOption->weight = $params['weight'];
     $customOption->value = $params['value'];
     $customOption->is_active = CRM_Utils_Array::value('is_active', $params, false);
     if ($this->_action == CRM_Core_Action::DELETE) {
         $fieldValues = array('option_group_id' => $this->_optionGroupID);
         $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
         CRM_Core_BAO_CustomOption::del($this->_id);
         CRM_Core_Session::setStatus(ts('Your multiple choice option has been deleted', array(1 => $customOption->label)));
         return;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $customOption->id = $this->_id;
         CRM_Core_BAO_CustomOption::updateCustomValues($params);
     }
     if ($this->_id) {
         $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'weight', 'id');
     }
     $fieldValues = array('option_group_id' => $this->_optionGroupID);
     $customOption->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, $params['weight'], $fieldValues);
     $customOption->option_group_id = $this->_optionGroupID;
     $customField =& new CRM_Core_DAO_CustomField();
     $customField->id = $this->_fid;
     if ($customField->find(true) && ($customField->html_type == 'CheckBox' || $customField->html_type == 'AdvMulti-Select' || $customField->html_type == 'Multi-Select')) {
         $defVal = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($customField->default_value, 1, -1));
         if (CRM_Utils_Array::value('default_value', $params)) {
             if (!in_array($customOption->value, $defVal)) {
                 if (empty($defVal[0])) {
                     $defVal = array($customOption->value);
                 } else {
                     $defVal[] = $customOption->value;
                 }
                 $customField->default_value = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $defVal) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                 $customField->save();
             }
         } else {
             if (in_array($customOption->value, $defVal)) {
                 $tempVal = array();
                 foreach ($defVal as $v) {
                     if ($v != $customOption->value) {
                         $tempVal[] = $v;
                     }
                 }
                 $customField->default_value = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $tempVal) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                 $customField->save();
             }
         }
     } else {
         switch ($customField->data_type) {
             case 'Money':
                 require_once 'CRM/Utils/Rule.php';
                 $customOption->value = CRM_Utils_Rule::cleanMoney($customOption->value);
                 break;
             case 'Int':
                 $customOption->value = intval($customOption->value);
                 break;
             case 'Float':
                 $customOption->value = floatval($customOption->value);
                 break;
         }
         if (CRM_Utils_Array::value('default_value', $params)) {
             $customField->default_value = $customOption->value;
             $customField->save();
         } else {
             if ($customField->find(true) && $customField->default_value == $customOption->value) {
                 // this is the case where this option is the current default value and we have been reset
                 $customField->default_value = 'null';
                 $customField->save();
             }
         }
     }
     $customOption->save();
     CRM_Core_Session::setStatus(ts('Your multiple choice option \'%1\' has been saved', array(1 => $customOption->label)));
     $buttonName = $this->controller->getButtonName();
     $session =& CRM_Core_Session::singleton();
     if ($buttonName == $this->getButtonName('next', 'new')) {
         CRM_Core_Session::setStatus(ts(' You can add another option.'));
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field/option', 'reset=1&action=add&fid=' . $this->_fid . '&gid=' . $this->_gid));
     }
 }
Example #7
0
 /**
  * Function to fetch the values 
  */
 function autocomplete(&$config)
 {
     $fieldID = CRM_Utils_Type::escape($_GET['cfid'], 'Integer');
     $optionGroupID = CRM_Utils_Type::escape($_GET['ogid'], 'Integer');
     $label = CRM_Utils_Type::escape($_GET['s'], 'String');
     require_once 'CRM/Core/BAO/CustomOption.php';
     $selectOption =& CRM_Core_BAO_CustomOption::valuesByID($fieldID, $optionGroupID);
     $completeList = null;
     foreach ($selectOption as $id => $value) {
         if (strtolower($label) == strtolower(substr($value, 0, strlen($label)))) {
             echo $completeList = "{$value}|{$id}\n";
         }
     }
     exit;
 }
Example #8
0
 /**
  * Run the page.
  *
  * This method is called after the page is created. It checks for the  
  * type of action and executes that action. 
  * 
  * @param null
  * 
  * @return void
  * @access public
  */
 function run()
 {
     require_once 'CRM/Core/BAO/CustomField.php';
     // get the field id
     $this->_fid = CRM_Utils_Request::retrieve('fid', $this, false, 0);
     $this->_gid = CRM_Utils_Request::retrieve('gid', $this, false, 0);
     if ($this->_fid) {
         $fieldTitle = CRM_Core_BAO_CustomField::getTitle($this->_fid);
         $this->assign('fid', $this->_fid);
         $this->assign('fieldTitle', $fieldTitle);
         CRM_Utils_System::setTitle(ts('%1 - Multiple Choice Options', array(1 => $fieldTitle)));
     }
     // get the requested action
     $action = CRM_Utils_Request::retrieve('action', $this, false, 'browse');
     // default to 'browse'
     // assign vars to templates
     $this->assign('action', $action);
     $id = CRM_Utils_Request::retrieve('id', $this, false, 0);
     // what action to take ?
     if ($action & (CRM_CORE_ACTION_UPDATE | CRM_CORE_ACTION_ADD | CRM_CORE_ACTION_VIEW | CRM_CORE_ACTION_DELETE)) {
         $this->edit($action);
         // no browse for edit/update/view
     } else {
         if ($action & CRM_CORE_ACTION_DISABLE) {
             CRM_Core_BAO_CustomOption::setIsActive($id, 0);
         } else {
             if ($action & CRM_CORE_ACTION_ENABLE) {
                 CRM_Core_BAO_CustomOption::setIsActive($id, 1);
             }
         }
         $this->browse();
     }
     // Call the parents run method
     parent::run();
 }
 /**
  * Function to set default values for custom data used in profile
  *
  * @params int    $customFieldId custom field id
  * @params string $elementName   custom field name
  * @params array  $defaults      associated array of fields
  * @params int    $contactId     contact id
  * @param  int    $mode          profile mode
  * 
  * @static
  * @access public
  */
 function setProfileDefaults($customFieldId, $elementName, &$defaults, $contactId = null, $mode = null)
 {
     //get the type of custom field
     $customField =& new CRM_Core_BAO_CustomField();
     $customField->id = $customFieldId;
     $customField->find(true);
     require_once "CRM/Profile/Form.php";
     if (!$contactId) {
         if ($mode == CRM_PROFILE_FORM_MODE_CREATE) {
             $value = $customField->default_value;
         }
     } else {
         // make sure the custom value exists
         $cv =& new CRM_Core_BAO_CustomValue();
         $cv->custom_field_id = $customFieldId;
         $cv->entity_table = 'civicrm_contact';
         $cv->entity_id = $contactId;
         if ($cv->find(true)) {
             switch ($customField->data_type) {
                 case 'String':
                     $value = $cv->char_data;
                     break;
                 case 'Int':
                 case 'Boolean':
                 case 'StateProvince':
                 case 'Country':
                     $value = $cv->int_data;
                     break;
                 case 'Float':
                     $value = $cv->int_float;
                     break;
                 case 'Money':
                     $value = $cv->decimal_data;
                     break;
                 case 'Memo':
                     $value = $cv->memo_data;
                     break;
                 case 'Date':
                     $value = $cv->date_data;
                     break;
             }
         }
     }
     //set defaults if mode is registration / edit
     if (!trim($value) && $mode != CRM_PROFILE_FORM_MODE_SEARCH) {
         $value = $customField->default_value;
     }
     switch ($customField->html_type) {
         case 'CheckBox':
             $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, $inactiveNeeded);
             $defaults[$elementName] = array();
             $checkedValue = explode(CRM_CORE_BAO_CUSTOMOPTION_VALUE_SEPERATOR, $value);
             foreach ($customOption as $val) {
                 if (in_array($val['value'], $checkedValue)) {
                     $defaults[$elementName][$val['value']] = 1;
                 } else {
                     $defaults[$elementName][$val['value']] = 0;
                 }
             }
             break;
             //added a case for Multi-Select option
         //added a case for Multi-Select option
         case 'Multi-Select':
             $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
             $defaults[$elementName] = array();
             $checkedValue = explode(CRM_CORE_BAO_CUSTOMOPTION_VALUE_SEPERATOR, $value);
             foreach ($customOption as $val) {
                 if (in_array($val['value'], $checkedValue)) {
                     $defaults[$elementName][$val['value']] = $val['value'];
                 }
             }
             break;
         default:
             $defaults[$elementName] = $value;
     }
 }
 /**
  * Browse the listing.
  *
  * @return void
  */
 public function browse()
 {
     $dateFields = NULL;
     $cgcount = 0;
     $attributes = array();
     $dateFieldsVals = NULL;
     if ($this->_pageViewType == 'profileDataView' && $this->_profileId) {
         $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::EDIT);
         $multiRecordFields = array();
         $fieldIDs = NULL;
         $result = NULL;
         $multiRecordFieldsWithSummaryListing = CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields, TRUE);
         $multiFieldId = CRM_Core_BAO_CustomField::getKeyID(key($multiRecordFields));
         $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $multiFieldId, 'custom_group_id');
         $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
         if (!$reached) {
             $this->assign('contactId', $this->_contactId);
             $this->assign('gid', $this->_profileId);
         }
         $this->assign('reachedMax', $reached);
         if ($multiRecordFieldsWithSummaryListing && !empty($multiRecordFieldsWithSummaryListing)) {
             $fieldIDs = array_keys($multiRecordFieldsWithSummaryListing);
         }
     } elseif ($this->_pageViewType == 'customDataView') {
         // require custom group id for _pageViewType of customDataView
         $customGroupId = $this->_customGroupId;
         $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
         if (!$reached) {
             $this->assign('contactId', $this->_contactId);
             $this->assign('customGroupId', $customGroupId);
             $this->assign('ctype', $this->_contactType);
         }
         $this->assign('reachedMax', $reached);
         // custom group info : this consists of the field title of group fields
         $groupDetail = CRM_Core_BAO_CustomGroup::getGroupDetail($customGroupId, NULL, CRM_Core_DAO::$_nullObject, TRUE);
         // field ids of fields in_selector for the custom group id provided
         $fieldIDs = array_keys($groupDetail[$customGroupId]['fields']);
         // field labels for headers
         $fieldLabels = $groupDetail[$customGroupId]['fields'];
         // from the above customGroupInfo we can get $this->_customGroupTitle
         $this->_customGroupTitle = $groupDetail[$customGroupId]['title'];
     }
     if ($fieldIDs && !empty($fieldIDs) && $this->_contactId) {
         $options = array();
         $returnProperities = array('html_type', 'data_type', 'date_format', 'time_format', 'default_value', 'is_required');
         foreach ($fieldIDs as $key => $fieldID) {
             $fieldIDs[$key] = !is_numeric($fieldID) ? CRM_Core_BAO_CustomField::getKeyID($fieldID) : $fieldID;
             $param = array('id' => $fieldIDs[$key]);
             $returnValues = array();
             CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $param, $returnValues, $returnProperities);
             if ($returnValues['data_type'] == 'Date') {
                 $dateFields[$fieldIDs[$key]] = 1;
                 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats();
                 $dateFormat = (array) CRM_Utils_Array::value($returnValues['date_format'], $actualPHPFormats);
                 $timeFormat = CRM_Utils_Array::value('time_format', $returnValues);
             }
             $optionValuePairs = CRM_Core_BAO_CustomOption::getCustomOption($fieldIDs[$key]);
             if (!empty($optionValuePairs)) {
                 foreach ($optionValuePairs as $optionPairs) {
                     $options[$fieldIDs[$key]][$optionPairs['value']] = $optionPairs['label'];
                 }
             }
             $options[$fieldIDs[$key]]['attributes']['html_type'] = $returnValues['html_type'];
             $options[$fieldIDs[$key]]['attributes']['data_type'] = $returnValues['data_type'];
             $options[$fieldIDs[$key]]['attributes']['is_required'] = !empty($returnValues['is_required']);
             $options[$fieldIDs[$key]]['attributes']['default_value'] = CRM_Utils_Array::value('default_value', $returnValues);
             $options[$fieldIDs[$key]]['attributes']['format'] = $options[$fieldIDs[$key]]['attributes']['date_format'] = CRM_Utils_Array::value('date_format', $returnValues);
             $options[$fieldIDs[$key]]['attributes']['time_format'] = CRM_Utils_Array::value('time_format', $returnValues);
         }
         // commonly used for both views i.e profile listing view (profileDataView) and custom data listing view (customDataView)
         $result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE);
         if ($this->_pageViewType == 'profileDataView') {
             if (!empty($fieldIDs)) {
                 //get the group info of multi rec fields in listing view
                 $fieldInput = $fieldIDs;
                 $fieldIdInput = $fieldIDs[0];
             } else {
                 //if no listing fields exist, take the group title for display
                 $nonListingFieldIds = array_keys($multiRecordFields);
                 $singleField = CRM_Core_BAO_CustomField::getKeyID($nonListingFieldIds[0]);
                 $fieldIdInput = $singleField;
                 $singleField = array($singleField);
                 $fieldInput = $singleField;
             }
             $customGroupInfo = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldInput);
             $this->_customGroupTitle = $customGroupInfo[$fieldIdInput]['groupTitle'];
         }
         // $cgcount is defined before 'if' condition as enitiy may have no record
         // and $cgcount is used to build new record url
         $cgcount = 1;
         if ($result && !empty($result)) {
             $links = self::links();
             if ($this->_pageViewType == 'profileDataView') {
                 $pageCheckSum = $this->get('pageCheckSum');
                 if ($pageCheckSum) {
                     foreach ($links as $key => $link) {
                         $links[$key] = $link['qs'] . "&cs=%%cs%%";
                     }
                 }
             }
             $linkAction = array_sum(array_keys($this->links()));
             if ($reached) {
                 unset($links[CRM_Core_Action::COPY]);
             }
             $newCgCount = !$reached ? count($result) + 1 : NULL;
             foreach ($result as $recId => &$value) {
                 foreach ($value as $fieldId => &$val) {
                     if (is_numeric($fieldId)) {
                         $customValue =& $val;
                         if (!empty($dateFields) && array_key_exists($fieldId, $dateFields)) {
                             // formated date capture value capture
                             $dateFieldsVals[$fieldId][$recId] = CRM_Core_BAO_CustomField::getDisplayValue($customValue, $fieldId, $options);
                             //set date and time format
                             switch ($timeFormat) {
                                 case 1:
                                     $dateFormat[1] = 'g:iA';
                                     break;
                                 case 2:
                                     $dateFormat[1] = 'G:i';
                                     break;
                                 default:
                                     // if time is not selected remove time from value
                                     $result[$recId][$fieldId] = substr($result[$recId][$fieldId], 0, 10);
                             }
                             $result[$recId][$fieldId] = CRM_Utils_Date::processDate($result[$recId][$fieldId], NULL, FALSE, implode(" ", $dateFormat));
                         } else {
                             // assign to $result
                             $customValue = CRM_Core_BAO_CustomField::getDisplayValue($customValue, $fieldId, $options);
                         }
                         // FIXME: getDisplayValue should always return a string so why is this necessary?
                         if (!$customValue && $customValue !== '0') {
                             $customValue = "";
                         }
                         // Set field attributes to support crmEditable
                         // Note that $fieldAttributes[data-type] actually refers to the html type not the sql data type
                         // TODO: Not all widget types and validation rules are supported by crmEditable so some fields will not be in-place editable
                         $fieldAttributes = array('class' => "crmf-custom_{$fieldId}_{$recId}");
                         $editable = FALSE;
                         if ($linkAction & CRM_Core_Action::UPDATE) {
                             $spec = $options[$fieldId]['attributes'];
                             switch ($spec['html_type']) {
                                 case 'Text':
                                     // Other data types like money would require some extra validation
                                     // FIXME: crmEditable currently does not support any validation rules :(
                                     $supportedDataTypes = array('Float', 'String', 'Int');
                                     $editable = in_array($spec['data_type'], $supportedDataTypes);
                                     break;
                                 case 'TextArea':
                                     $editable = TRUE;
                                     $fieldAttributes['data-type'] = 'textarea';
                                     break;
                                 case 'Radio':
                                 case 'Select':
                                 case 'Select Country':
                                 case 'Select State/Province':
                                     $editable = TRUE;
                                     $fieldAttributes['data-type'] = $spec['data_type'] == 'Boolean' ? 'boolean' : 'select';
                                     if (!$spec['is_required']) {
                                         $fieldAttributes['data-empty-option'] = ts('- none -');
                                     }
                                     break;
                             }
                         }
                         if ($editable) {
                             $fieldAttributes['class'] .= ' crm-editable';
                         }
                         $attributes[$fieldId][$recId] = $fieldAttributes;
                         $op = NULL;
                         if ($this->_pageViewType == 'profileDataView') {
                             $actionParams = array('recordId' => $recId, 'gid' => $this->_profileId, 'id' => $this->_contactId);
                             $op = 'profile.multiValue.row';
                         } else {
                             // different set of url params
                             $actionParams['gid'] = $actionParams['groupID'] = $this->_customGroupId;
                             $actionParams['cid'] = $actionParams['entityID'] = $this->_contactId;
                             $actionParams['recId'] = $recId;
                             $actionParams['type'] = $this->_contactType;
                             $actionParams['cgcount'] = $cgcount;
                             $actionParams['newCgCount'] = $newCgCount;
                             // DELETE action links
                             $deleteData = array('valueID' => $recId, 'groupID' => $this->_customGroupId, 'contactId' => $this->_contactId, 'key' => CRM_Core_Key::get('civicrm/ajax/customvalue'));
                             $links[CRM_Core_Action::DELETE]['url'] = '#';
                             $links[CRM_Core_Action::DELETE]['extra'] = ' data-delete_params="' . htmlspecialchars(json_encode($deleteData)) . '"';
                             $links[CRM_Core_Action::DELETE]['class'] = 'delete-custom-row';
                         }
                         if (!empty($pageCheckSum)) {
                             $actionParams['cs'] = $pageCheckSum;
                         }
                         $value['action'] = CRM_Core_Action::formLink($links, $linkAction, $actionParams, ts('more'), FALSE, $op, 'customValue', $fieldId);
                     }
                 }
                 $cgcount++;
             }
         }
     }
     $headers = array();
     if (!empty($fieldIDs)) {
         foreach ($fieldIDs as $fieldID) {
             $headers[$fieldID] = $this->_pageViewType == 'profileDataView' ? $customGroupInfo[$fieldID]['fieldLabel'] : $fieldLabels[$fieldID]['label'];
         }
     }
     $this->assign('dateFields', $dateFields);
     $this->assign('dateFieldsVals', $dateFieldsVals);
     $this->assign('cgcount', $cgcount);
     $this->assign('customGroupTitle', $this->_customGroupTitle);
     $this->assign('headers', $headers);
     $this->assign('records', $result);
     $this->assign('attributes', $attributes);
 }
 /**
  * Add an Option Value.
  *
  * @param array $params
  *   Reference array contains the values submitted by the form.
  * @param array $ids
  *   Reference array contains the id.
  *
  *
  * @return CRM_Core_DAO_OptionValue
  */
 public static function add(&$params, &$ids)
 {
     // CRM-10921: do not reset attributes to default if this is an update
     //@todo consider if defaults are being set in the right place. 'dumb' defaults like
     // these would be usefully set @ the api layer so they are visible to api users
     // complex defaults like the domain id below would make sense in the setDefauls function
     // but unclear what other ways this function is being used
     if (empty($ids['optionValue'])) {
         $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
         $params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
         $params['is_optgroup'] = CRM_Utils_Array::value('is_optgroup', $params, FALSE);
         $params['filter'] = CRM_Utils_Array::value('filter', $params, FALSE);
     } elseif (isset($params['value'])) {
         CRM_Core_BAO_CustomOption::updateValue($ids['optionValue'], $params['value']);
     }
     // action is taken depending upon the mode
     $optionValue = new CRM_Core_DAO_OptionValue();
     $optionValue->copyValues($params);
     if (!empty($params['is_default'])) {
         $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE  option_group_id = %1';
         // tweak default reset, and allow multiple default within group.
         if ($resetDefaultFor = CRM_Utils_Array::value('reset_default_for', $params)) {
             if (is_array($resetDefaultFor)) {
                 $colName = key($resetDefaultFor);
                 $colVal = $resetDefaultFor[$colName];
                 $query .= " AND ( {$colName} IN (  {$colVal} ) )";
             }
         }
         $p = array(1 => array($params['option_group_id'], 'Integer'));
         CRM_Core_DAO::executeQuery($query, $p);
     }
     // CRM-13814 : evalute option group id
     if (!array_key_exists('option_group_id', $params) && !empty($ids['optionValue'])) {
         $groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $ids['optionValue'], 'option_group_id', 'id');
     } else {
         $groupId = $params['option_group_id'];
     }
     $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $groupId, 'name', 'id');
     if (in_array($groupName, CRM_Core_OptionGroup::$_domainIDGroups)) {
         $optionValue->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
     }
     $optionValue->id = CRM_Utils_Array::value('optionValue', $ids);
     $optionValue->save();
     CRM_Core_PseudoConstant::flush();
     return $optionValue;
 }
Example #12
0
 /**
  * Update saved search for multi-select custom fields on DB upgrade
  *
  * @param CRM_Queue_TaskContext $ctx
  *
  * @return bool TRUE for success
  */
 public static function updateSavedSearch(CRM_Queue_TaskContext $ctx)
 {
     $sql = "SELECT id, form_values FROM civicrm_saved_search";
     $dao = CRM_Core_DAO::executeQuery($sql);
     while ($dao->fetch()) {
         $copy = $formValues = unserialize($dao->form_values);
         $update = FALSE;
         foreach ($copy as $field => $data_value) {
             if (preg_match('/^custom_/', $field) && is_array($data_value) && !array_key_exists("{$field}_operator", $formValues)) {
                 // Now check for CiviCRM_OP_OR as either key or value in the data_value array.
                 // This is the conclusive evidence of an old-style data format.
                 if (array_key_exists('CiviCRM_OP_OR', $data_value) || FALSE !== array_search('CiviCRM_OP_OR', $data_value)) {
                     // We have old style data. Mark this record to be updated.
                     $update = TRUE;
                     $op = 'and';
                     if (!preg_match('/^custom_([0-9]+)/', $field, $matches)) {
                         // fatal error?
                         continue;
                     }
                     $fieldID = $matches[1];
                     if (array_key_exists('CiviCRM_OP_OR', $data_value)) {
                         // This indicates data structure identified by jamie in the form:
                         // value1 => 1, value2 => , value3 => 1.
                         $data_value = array_keys($data_value, 1);
                         // If CiviCRM_OP_OR - change OP from default to OR
                         if ($data_value['CiviCRM_OP_OR'] == 1) {
                             $op = 'or';
                         }
                         unset($data_value['CiviCRM_OP_OR']);
                     } else {
                         // The value is here, but it is not set as a key.
                         // This is using the style identified by Monish - the existence of the value
                         // indicates an OR search and values are set in the form of:
                         // 0 => value1, 1 => value1, 3 => value2.
                         $key = array_search('CiviCRM_OP_OR', $data_value);
                         $op = 'or';
                         unset($data_value[$key]);
                     }
                     //If only Or operator has been chosen, means we need to select all values and
                     //so to execute OR operation between these values according to new data structure
                     if (count($data_value) == 0 && $op == 'or') {
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($fieldID);
                         foreach ($customOption as $option) {
                             $data_value[] = CRM_Utils_Array::value('value', $option);
                         }
                     }
                     $formValues[$field] = $data_value;
                     $formValues["{$field}_operator"] = $op;
                 }
             }
         }
         if ($update) {
             $sql = "UPDATE civicrm_saved_search SET form_values = %0 WHERE id = %1";
             CRM_Core_DAO::executeQuery($sql, array(array(serialize($formValues), 'String'), array($dao->id, 'Integer')));
         }
     }
     return TRUE;
 }
Example #13
0
 /**
  * Function to fetch the values
  */
 static function autocomplete()
 {
     $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('cfid', 'ogid', 'sigts'));
     if (CRM_Utils_Time::getTimeRaw() > $_REQUEST['sigts'] + self::AUTOCOMPLETE_TTL || !$signer->validate($_REQUEST['sig'], $_REQUEST)) {
         CRM_Utils_System::civiExit();
     }
     $fieldID = CRM_Utils_Type::escape($_GET['cfid'], 'Integer');
     $optionGroupID = CRM_Utils_Type::escape($_GET['ogid'], 'Integer');
     $label = CRM_Utils_Type::escape($_GET['s'], 'String');
     $selectOption = CRM_Core_BAO_CustomOption::valuesByID($fieldID, $optionGroupID);
     $completeList = NULL;
     foreach ($selectOption as $id => $value) {
         if (strtolower($label) == strtolower(substr($value, 0, strlen($label)))) {
             echo $completeList = "{$value}|{$id}\n";
         }
     }
     CRM_Utils_System::civiExit();
 }
Example #14
0
 /**
  * Replace all the org-level tokens in $str
  *
  * @param string $str       The string with tokens to be replaced
  * @param object $org       Associative array of org properties
  * @param boolean $html     Replace tokens with HTML or plain text
  * @return string           The processed string
  * @access public
  * @static
  */
 public static function &replaceOrgTokens($str, &$org, $html = false)
 {
     self::$_tokens['org'] = array_merge(array_keys(CRM_Contact_BAO_Contact::importableFields('Organization')), array('address', 'display_name', 'checksum', 'contact_id'));
     /*
     print "org tokens: <pre>";
     print_r( $_tokens['org'] );
     print "</pre>";
     */
     $cv = null;
     foreach (self::$_tokens['org'] as $token) {
         // print "Getting token value for $token<br/><br/>";
         if ($token == '') {
             continue;
         }
         /* If the string doesn't contain this token, skip it. */
         if (!self::token_match('org', $token, $str)) {
             continue;
         }
         /* Construct value from $token and $contact */
         $value = null;
         if ($cfID = CRM_Core_BAO_CustomField::getKeyID($token)) {
             // only generate cv if we need it
             if ($cv === null) {
                 $cv =& CRM_Core_BAO_CustomValue::getContactValues($org['contact_id']);
             }
             foreach ($cv as $cvFieldID => $value) {
                 if ($cvFieldID == $cfID) {
                     $value = CRM_Core_BAO_CustomOption::getOptionLabel($cfID, $value);
                     break;
                 }
             }
         } else {
             if ($token == 'checksum') {
                 require_once 'CRM/Contact/BAO/Contact/Utils.php';
                 $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($org['contact_id']);
                 $value = "cs={$cs}";
             } else {
                 if ($token == 'address') {
                     /* Build the location values array */
                     $loc = array();
                     $loc['display_name'] = CRM_Utils_Array::retrieveValueRecursive($org, 'display_name');
                     $loc['street_address'] = CRM_Utils_Array::retrieveValueRecursive($org, 'street_address');
                     $loc['city'] = CRM_Utils_Array::retrieveValueRecursive($org, 'city');
                     $loc['state_province'] = CRM_Utils_Array::retrieveValueRecursive($org, 'state_province');
                     $loc['postal_code'] = CRM_Utils_Array::retrieveValueRecursive($org, 'postal_code');
                     /* Construct the address token */
                     $value = CRM_Utils_Address::format($loc);
                     if ($html) {
                         $value = str_replace("\n", '<br />', $value);
                     }
                 } else {
                     /*
                     print "\$org: <pre>";
                     print_r( $org );
                     print "</pre>";
                     */
                     $value = CRM_Utils_Array::retrieveValueRecursive($org, $token);
                     /*
                     print "\$value: <pre>";
                     print_r( $value );
                     print "</pre>";
                     */
                 }
             }
         }
         self::token_replace('org', $token, $value, $str);
     }
     return $str;
 }
 /**
  * Browse the listing
  *
  * @return void
  * @access public
  */
 function browse()
 {
     if ($this->_profileId) {
         $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::EDIT);
         $multiRecordFields = array();
         $fieldIDs = NULL;
         $result = NULL;
         $multiRecordFieldsWithSummaryListing = CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields, TRUE);
         $multiFieldId = CRM_Core_BAO_CustomField::getKeyID(key($multiRecordFields));
         $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $multiFieldId, 'custom_group_id');
         $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
         if (!$reached) {
             $this->assign('contactId', $this->_contactId);
             $this->assign('gid', $this->_profileId);
         }
         $this->assign('reachedMax', $reached);
         if ($multiRecordFieldsWithSummaryListing && !empty($multiRecordFieldsWithSummaryListing)) {
             $fieldIDs = array_keys($multiRecordFieldsWithSummaryListing);
         }
     }
     if ($fieldIDs && !empty($fieldIDs) && $this->_contactId) {
         $options = array();
         $returnProperities = array('html_type', 'data_type', 'date_format', 'time_format');
         foreach ($fieldIDs as $key => $fieldID) {
             $fieldIDs[$key] = CRM_Core_BAO_CustomField::getKeyID($fieldID);
             $param = array('id' => $fieldIDs[$key]);
             $returnValues = array();
             CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $param, $returnValues, $returnProperities);
             $optionValuePairs = CRM_Core_BAO_CustomOption::getCustomOption($fieldIDs[$key]);
             if (!empty($optionValuePairs)) {
                 foreach ($optionValuePairs as $optionPairs) {
                     $options[$fieldIDs[$key]][$optionPairs['value']] = $optionPairs['label'];
                 }
             }
             $options[$fieldIDs[$key]]['attributes']['html_type'] = $returnValues['html_type'];
             $options[$fieldIDs[$key]]['attributes']['data_type'] = $returnValues['data_type'];
             $options[$fieldIDs[$key]]['attributes']['format'] = $options[$fieldIDs[$key]]['attributes']['date_format'] = CRM_Utils_Array::value('date_format', $returnValues);
             $options[$fieldIDs[$key]]['attributes']['time_format'] = CRM_Utils_Array::value('time_format', $returnValues);
         }
         $result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE);
         if (!empty($fieldIDs)) {
             //get the group info of multi rec fields in listing view
             $fieldInput = $fieldIDs;
             $fieldIdInput = $fieldIDs[0];
         } else {
             //if no listing fields exist, take the group title for display
             $nonListingFieldIds = array_keys($multiRecordFields);
             $singleField = CRM_Core_BAO_CustomField::getKeyID($nonListingFieldIds[0]);
             $fieldIdInput = $singleField;
             $singleField = array($singleField);
             $fieldInput = $singleField;
         }
         $customGroupInfo = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldInput);
         $this->_customGroupTitle = $customGroupInfo[$fieldIdInput]['groupTitle'];
         if ($result && !empty($result)) {
             $links = self::links();
             $pageCheckSum = $this->get('pageCheckSum');
             if ($pageCheckSum) {
                 foreach ($links as $key => $link) {
                     $links[$key] = $link['qs'] . "&cs=%%cs%%";
                 }
             }
             $linkAction = array_sum(array_keys($this->links()));
             foreach ($result as $recId => &$value) {
                 foreach ($value as $fieldId => &$val) {
                     if (is_numeric($fieldId)) {
                         $customValue =& $val;
                         $customValue = CRM_Core_BAO_CustomField::getDisplayValue($customValue, $fieldId, $options);
                         if (!$customValue) {
                             $customValue = "";
                         }
                         $actionParams = array('recordId' => $recId, 'gid' => $this->_profileId, 'id' => $this->_contactId, 'onPopupClose' => $this->_onPopupClose);
                         if ($pageCheckSum) {
                             $actionParams['cs'] = $pageCheckSum;
                         }
                         $value['action'] = CRM_Core_Action::formLink($links, $linkAction, $actionParams, ts('more'), FALSE, 'profile.multiValue.row', 'customValue', $fieldId);
                     }
                 }
             }
         }
     }
     $headers = array();
     if (!empty($fieldIDs)) {
         foreach ($fieldIDs as $fieldID) {
             $headers[$fieldID] = $customGroupInfo[$fieldID]['fieldLabel'];
         }
     }
     $this->assign('customGroupTitle', $this->_customGroupTitle);
     $this->assign('headers', $headers);
     $this->assign('records', $result);
 }
Example #16
0
 /**
  * Function to set profile defaults
  *
  * @params int     $contactId      contact id
  * @params array   $fields         associative array of fields
  * @params array   $defaults       defaults array
  * @params boolean $singleProfile  true for single profile else false(batch update)
  * @params int     $componentId    id for specific components like contribute, event etc
  *
  * @return null
  * @static
  * @access public
  */
 static function setProfileDefaults($contactId, &$fields, &$defaults, $singleProfile = true, $componentId = null, $component = null)
 {
     if (!$componentId) {
         //get the contact details
         require_once 'CRM/Contact/BAO/Contact.php';
         list($contactDetails, $options) = CRM_Contact_BAO_Contact::getHierContactDetails($contactId, $fields);
         $details = $contactDetails[$contactId];
         require_once 'CRM/Contact/Form/Edit/TagsAndGroups.php';
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             //set the field name depending upon the profile mode(single/batch)
             if ($singleProfile) {
                 $fldName = $name;
             } else {
                 $fldName = "field[{$contactId}][{$name}]";
             }
             if ($name == 'group') {
                 CRM_Contact_Form_Edit_TagsAndGroups::setDefaults($contactId, $defaults, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, $fldName);
             }
             if ($name == 'tag') {
                 CRM_Contact_Form_Edit_TagsAndGroups::setDefaults($contactId, $defaults, CRM_Contact_Form_Edit_TagsAndGroups::TAG, $fldName);
             }
             if (CRM_Utils_Array::value($name, $details) || isset($details[$name])) {
                 //to handle custom data (checkbox) to be written
                 // to handle gender / suffix / prefix / greeting_type
                 if ($name == 'gender') {
                     $defaults[$fldName] = $details['gender_id'];
                 } else {
                     if ($name == 'individual_prefix') {
                         $defaults[$fldName] = $details['individual_prefix_id'];
                     } else {
                         if ($name == 'individual_suffix') {
                             $defaults[$fldName] = $details['individual_suffix_id'];
                         } else {
                             if ($name == 'birth_date' || $name == 'deceased_date') {
                                 list($defaults[$fldName]) = CRM_Utils_Date::setDateDefaults($details[$name], 'birth');
                             } else {
                                 if ($name == 'email_greeting') {
                                     $defaults[$fldName] = $details['email_greeting_id'];
                                     $defaults['email_greeting_custom'] = $details['email_greeting_custom'];
                                 } else {
                                     if ($name == 'postal_greeting') {
                                         $defaults[$fldName] = $details['postal_greeting_id'];
                                         $defaults['postal_greeting_custom'] = $details['postal_greeting_custom'];
                                     } else {
                                         if ($name == 'addressee') {
                                             $defaults[$fldName] = $details['addressee_id'];
                                             $defaults['addressee_custom'] = $details['addressee_custom'];
                                         } else {
                                             if ($name == 'preferred_communication_method') {
                                                 $v = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $details[$name]);
                                                 foreach ($v as $item) {
                                                     if ($item) {
                                                         $defaults[$fldName . "[{$item}]"] = 1;
                                                     }
                                                 }
                                             } else {
                                                 if ($name == 'world_region') {
                                                     $defaults[$fldName] = $details['worldregion_id'];
                                                 } else {
                                                     if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                                         //fix for custom fields
                                                         $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('Individual', $values));
                                                         // hack to add custom data for components
                                                         $components = array("Contribution", "Participant", "Membership");
                                                         foreach ($components as $value) {
                                                             $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFieldsForImport($value));
                                                         }
                                                         switch ($customFields[$customFieldId]['html_type']) {
                                                             case 'Multi-Select State/Province':
                                                             case 'Multi-Select Country':
                                                             case 'AdvMulti-Select':
                                                             case 'Multi-Select':
                                                                 $v = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $details[$name]);
                                                                 foreach ($v as $item) {
                                                                     if ($item) {
                                                                         $defaults[$fldName][$item] = $item;
                                                                     }
                                                                 }
                                                                 break;
                                                             case 'CheckBox':
                                                                 $v = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $details[$name]);
                                                                 foreach ($v as $item) {
                                                                     if ($item) {
                                                                         $defaults[$fldName][$item] = 1;
                                                                         // seems like we need this for QF style checkboxes in profile where its multiindexed
                                                                         // CRM-2969
                                                                         $defaults["{$fldName}[{$item}]"] = 1;
                                                                     }
                                                                 }
                                                                 break;
                                                             case 'Autocomplete-Select':
                                                                 if ($customFields[$customFieldId]['data_type'] == "ContactReference") {
                                                                     require_once 'CRM/Contact/BAO/Contact.php';
                                                                     if (is_numeric($details[$name])) {
                                                                         $defaults[$fldName . '_id'] = $details[$name];
                                                                         $defaults[$fldName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $details[$name], 'sort_name');
                                                                     }
                                                                 } else {
                                                                     $label = CRM_Core_BAO_CustomOption::getOptionLabel($customFieldId, $details[$name]);
                                                                     $defaults[$fldName . '_id'] = $details[$name];
                                                                     $defaults[$fldName] = $label;
                                                                 }
                                                                 break;
                                                             case 'Select Date':
                                                                 list($defaults[$fldName], $defaults[substr($fldName, 0, -1) . '_time]']) = CRM_Utils_Date::setDateDefaults($details[$name]);
                                                                 break;
                                                             default:
                                                                 $defaults[$fldName] = $details[$name];
                                                                 break;
                                                         }
                                                     } else {
                                                         $defaults[$fldName] = $details[$name];
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $name, 3);
                 if (is_array($details)) {
                     foreach ($details as $key => $value) {
                         // when we fixed CRM-5319 - get primary loc
                         // type as per loc field and removed below code.
                         if ($locTypeId == 'Primary') {
                             $locTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactId);
                         }
                         if (is_numeric($locTypeId)) {
                             //fixed for CRM-665
                             if ($locTypeId == CRM_Utils_Array::value('location_type_id', $value)) {
                                 if (CRM_Utils_Array::value($fieldName, $value)) {
                                     //to handle stateprovince and country
                                     if ($fieldName == 'state_province') {
                                         $defaults[$fldName] = $value['state_province_id'];
                                     } else {
                                         if ($fieldName == 'county') {
                                             $defaults[$fldName] = $value['county_id'];
                                         } else {
                                             if ($fieldName == 'country') {
                                                 $defaults[$fldName] = $value['country_id'];
                                                 if (!isset($value['country_id']) || !$value['country_id']) {
                                                     $config =& CRM_Core_Config::singleton();
                                                     if ($config->defaultContactCountry) {
                                                         $defaults[$fldName] = $config->defaultContactCountry;
                                                     }
                                                 }
                                             } else {
                                                 if ($fieldName == 'phone') {
                                                     if ($phoneTypeId) {
                                                         if ($value['phone'][$phoneTypeId]) {
                                                             $defaults[$fldName] = $value['phone'][$phoneTypeId];
                                                         }
                                                     } else {
                                                         $defaults[$fldName] = $value['phone'];
                                                     }
                                                 } else {
                                                     if ($fieldName == 'email') {
                                                         //adding the first email (currently we don't support multiple emails of same location type)
                                                         $defaults[$fldName] = $value['email'];
                                                     } else {
                                                         if ($fieldName == 'im') {
                                                             //adding the first im (currently we don't support multiple ims of same location type)
                                                             $defaults[$fldName] = $value['im'];
                                                             $defaults[$fldName . "-provider_id"] = $value['im_provider_id'];
                                                         } else {
                                                             $defaults[$fldName] = $value[$fieldName];
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (CRM_Core_Permission::access('Quest', false)) {
             require_once 'CRM/Quest/BAO/Student.php';
             // Checking whether the database contains quest_student table.
             // Now there are two different schemas for core and quest.
             // So if only core schema in use then withought following check gets the DB error.
             $student = new CRM_Quest_BAO_Student();
             $tableStudent = $student->getTableName();
             if ($tableStudent) {
                 //set student defaults
                 CRM_Quest_BAO_Student::retrieve($details, $studentDefaults, $ids);
                 $studentFields = array('educational_interest', 'college_type', 'college_interest', 'test_tutoring');
                 foreach ($studentFields as $fld) {
                     if ($studentDefaults[$fld]) {
                         $values = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $studentDefaults[$fld]);
                     }
                     $studentDefaults[$fld] = array();
                     if (is_array($values)) {
                         foreach ($values as $v) {
                             $studentDefaults[$fld][$v] = 1;
                         }
                     }
                 }
                 foreach ($fields as $name => $field) {
                     $fldName = "field[{$contactId}][{$name}]";
                     if (array_key_exists($name, $studentDefaults)) {
                         $defaults[$fldName] = $studentDefaults[$name];
                     }
                 }
             }
         }
     }
     //Handling Contribution Part of the batch profile
     if (CRM_Core_Permission::access('CiviContribute') && $component == 'Contribute') {
         self::setComponentDefaults($fields, $componentId, $component, $defaults);
     }
     //Handling Event Participation Part of the batch profile
     if (CRM_Core_Permission::access('CiviEvent') && $component == 'Event') {
         self::setComponentDefaults($fields, $componentId, $component, $defaults);
     }
     //Handling membership Part of the batch profile
     if (CRM_Core_Permission::access('CiviMember') && $component == 'Membership') {
         self::setComponentDefaults($fields, $componentId, $component, $defaults);
     }
 }
 /**
  * Function to extract the get params from the url, validate
  * and store it in session
  *
  * @param CRM_Core_Form $form the form object
  * @param string        $type the type of custom group we are using
  * @return void
  * @access public
  * @static
  */
 function extractGetParams(&$form, $type)
 {
     // if not GET params return
     if (empty($_GET)) {
         return;
     }
     $groupTree =& CRM_Core_BAO_CustomGroup::getTree($type);
     $customFields =& CRM_Core_BAO_CustomField::getFields($type);
     $customValue = array();
     $htmlType = array('CheckBox', 'Multi-Select', 'Select', 'Radio');
     foreach ($groupTree as $group) {
         foreach ($group['fields'] as $key => $field) {
             $fieldName = 'custom_' . $key;
             $value = CRM_Utils_Request::retrieve($fieldName, $form);
             if ($value) {
                 if (!in_array($customFields[$key][3], $htmlType) || $customFields[$key][2] == 'Boolean') {
                     $valid = CRM_Core_BAO_CustomValue::typecheck($customFields[$key][2], $value);
                 }
                 if ($customFields[$key][3] == 'CheckBox' || $customFields[$key][3] == 'Multi-Select') {
                     $value = str_replace("|", ",", $value);
                     $mulValues = explode(',', $value);
                     $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, true);
                     $val = array();
                     foreach ($mulValues as $v1) {
                         foreach ($customOption as $v2) {
                             if (strtolower(trim($v2['label'])) == strtolower(trim($v1))) {
                                 $val[$v2['value']] = 1;
                             }
                         }
                     }
                     if (!empty($val)) {
                         $value = $val;
                         $valid = true;
                     } else {
                         $value = null;
                     }
                 } else {
                     if ($customFields[$key][3] == 'Select' || $customFields[$key][3] == 'Radio' && $customFields[$key][2] != 'Boolean') {
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, true);
                         foreach ($customOption as $v2) {
                             if (strtolower(trim($v2['label'])) == strtolower(trim($value))) {
                                 $value = $v2['value'];
                                 $valid = true;
                             }
                         }
                     } else {
                         if ($customFields[$key][2] == 'Date') {
                             require_once 'CRM/Utils/Date.php';
                             if (is_numeric($value)) {
                                 $value = CRM_Utils_Date::unformat($value, null);
                             } else {
                                 $value = CRM_Utils_Date::unformat($value, $separator = '-');
                             }
                             $valid = true;
                         }
                     }
                 }
                 if ($valid) {
                     $customValue[$fieldName] = $value;
                 }
             }
         }
     }
     $form->set('customGetValues', $customValue);
     $form->set('groupTree', $groupTree);
 }
 /**
  * Format common params data to proper format to store.
  *
  * @param array $params
  *   Contain record values.
  * @param array $formatted
  *   Array of formatted data.
  * @param array $contactFields
  *   Contact DAO fields.
  */
 public function formatCommonData($params, &$formatted, &$contactFields)
 {
     $csType = array(CRM_Utils_Array::value('contact_type', $formatted));
     //CRM-5125
     //add custom fields for contact sub type
     if (!empty($this->_contactSubType)) {
         $csType = $this->_contactSubType;
     }
     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) {
         $csType = $relCsType;
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], FALSE, FALSE, $csType);
     $addressCustomFields = CRM_Core_BAO_CustomField::getFields('Address');
     $customFields = $customFields + $addressCustomFields;
     //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575
     $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee');
     foreach ($elements as $k => $v) {
         if (array_key_exists($k, $params) && !array_key_exists($v, $params)) {
             $label = key(CRM_Core_OptionGroup::values($v, TRUE, NULL, NULL, 'AND v.name = "Customized"'));
             $params[$v] = $label;
         }
     }
     //format date first
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
         if ($customFieldID && !array_key_exists($customFieldID, $addressCustomFields)) {
             //we should not update Date to null, CRM-4062
             if ($val && $customFields[$customFieldID]['data_type'] == 'Date') {
                 self::formatCustomDate($params, $formatted, $dateType, $key);
             } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                 if (empty($val) && !is_numeric($val) && $this->_onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
                     //retain earlier value when Import mode is `Fill`
                     unset($params[$key]);
                 } else {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'birth_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } elseif ($key == 'deceased_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } elseif ($key == 'is_deceased' && $val) {
                 $params[$key] = CRM_Utils_String::strtoboolstr($val);
             } elseif ($key == 'gender') {
                 //CRM-4360
                 $params[$key] = $this->checkGender($val);
             }
         }
     }
     //now format custom data.
     foreach ($params as $key => $field) {
         if (is_array($field)) {
             $isAddressCustomField = FALSE;
             foreach ($field as $value) {
                 $break = FALSE;
                 if (is_array($value)) {
                     foreach ($value as $name => $testForEmpty) {
                         if ($addressCustomFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                             $isAddressCustomField = TRUE;
                             break;
                         }
                         // check if $value does not contain IM provider or phoneType
                         if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == NULL)) {
                             $break = TRUE;
                             break;
                         }
                     }
                 } else {
                     $break = TRUE;
                 }
                 if (!$break) {
                     require_once 'CRM/Utils/DeprecatedUtils.php';
                     _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
                 }
             }
             if (!$isAddressCustomField) {
                 continue;
             }
         }
         $formatValues = array($key => $field);
         if ($key !== 'preferred_communication_method' && array_key_exists($key, $contactFields)) {
             // due to merging of individual table and
             // contact table, we need to avoid
             // preferred_communication_method forcefully
             $formatValues['contact_type'] = $formatted['contact_type'];
         }
         if ($key == 'id' && isset($field)) {
             $formatted[$key] = $field;
         }
         require_once 'CRM/Utils/DeprecatedUtils.php';
         _civicrm_api3_deprecated_add_formatted_param($formatValues, $formatted);
         //Handling Custom Data
         // note: Address custom fields will be handled separately inside _civicrm_api3_deprecated_add_formatted_param
         if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) && !array_key_exists($customFieldID, $addressCustomFields)) {
             $extends = CRM_Utils_Array::value('extends', $customFields[$customFieldID]);
             $htmlType = CRM_Utils_Array::value('html_type', $customFields[$customFieldID]);
             switch ($htmlType) {
                 case 'Select':
                 case 'Radio':
                 case 'Autocomplete-Select':
                     if ($customFields[$customFieldID]['data_type'] == 'String') {
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                         foreach ($customOption as $customFldID => $customValue) {
                             $val = CRM_Utils_Array::value('value', $customValue);
                             $label = CRM_Utils_Array::value('label', $customValue);
                             $label = strtolower($label);
                             $value = strtolower(trim($formatted[$key]));
                             if ($value == $label || $value == strtolower($val)) {
                                 $params[$key] = $formatted[$key] = $val;
                             }
                         }
                     }
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                     if (!empty($formatted[$key]) && !empty($params[$key])) {
                         $mulValues = explode(',', $formatted[$key]);
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                         $formatted[$key] = array();
                         $params[$key] = array();
                         foreach ($mulValues as $v1) {
                             foreach ($customOption as $v2) {
                                 if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) {
                                     if ($htmlType == 'CheckBox') {
                                         $params[$key][$v2['value']] = $formatted[$key][$v2['value']] = 1;
                                     } else {
                                         $params[$key][] = $formatted[$key][] = $v2['value'];
                                     }
                                 }
                             }
                         }
                     }
                     break;
             }
         }
     }
     if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) && !array_key_exists($customFieldID, $addressCustomFields)) {
         // @todo calling api functions directly is not supported
         _civicrm_api3_custom_format_params($params, $formatted, $extends);
     }
     // to check if not update mode and unset the fields with empty value.
     if (!$this->_updateWithId && array_key_exists('custom', $formatted)) {
         foreach ($formatted['custom'] as $customKey => $customvalue) {
             if (empty($formatted['custom'][$customKey][-1]['is_required'])) {
                 $formatted['custom'][$customKey][-1]['is_required'] = $customFields[$customKey]['is_required'];
             }
             $emptyValue = CRM_Utils_Array::value('value', $customvalue[-1]);
             if (!isset($emptyValue)) {
                 unset($formatted['custom'][$customKey]);
             }
         }
     }
     // parse street address, CRM-5450
     if ($this->_parseStreetAddress) {
         if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
             foreach ($formatted['address'] as $instance => &$address) {
                 $streetAddress = CRM_Utils_Array::value('street_address', $address);
                 if (empty($streetAddress)) {
                     continue;
                 }
                 // parse address field.
                 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress);
                 //street address consider to be parsed properly,
                 //If we get street_name and street_number.
                 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
                     $parsedFields = array_fill_keys(array_keys($parsedFields), '');
                 }
                 // merge parse address w/ main address block.
                 $address = array_merge($address, $parsedFields);
             }
         }
     }
 }
Example #19
0
 static function autocomplete($value, $options)
 {
     if ($value) {
         require_once 'CRM/Core/BAO/CustomOption.php';
         $selectOption =& CRM_Core_BAO_CustomOption::valuesByID($options['fieldID'], $options['optionGroupID']);
         if (!in_array($value, $selectOption)) {
             return false;
         }
     }
     return true;
 }
 /**
  * Function to set profile defaults
  *
  * @params int     $contactId      contact id
  * @params array   $fields         associative array of fields
  * @params array   $defaults       defaults array
  * @params boolean $singleProfile  true for single profile else false(batch update)
  * @params int     $componentId    id for specific components like contribute, event etc
  *
  * @return null
  * @static
  * @access public
  */
 static function setProfileDefaults($contactId, &$fields, &$defaults, $singleProfile = TRUE, $componentId = NULL, $component = NULL)
 {
     if (!$componentId) {
         //get the contact details
         list($contactDetails, $options) = CRM_Contact_BAO_Contact::getHierContactDetails($contactId, $fields);
         $details = CRM_Utils_Array::value($contactId, $contactDetails);
         $multipleFields = array('website' => 'url');
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             // skip pseudo fields
             if (substr($name, 0, 9) == 'phone_ext') {
                 continue;
             }
             //set the field name depending upon the profile mode(single/batch)
             if ($singleProfile) {
                 $fldName = $name;
             } else {
                 $fldName = "field[{$contactId}][{$name}]";
             }
             if ($name == 'group') {
                 CRM_Contact_Form_Edit_TagsAndGroups::setDefaults($contactId, $defaults, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, $fldName);
             }
             if ($name == 'tag') {
                 CRM_Contact_Form_Edit_TagsAndGroups::setDefaults($contactId, $defaults, CRM_Contact_Form_Edit_TagsAndGroups::TAG, $fldName);
             }
             if (CRM_Utils_Array::value($name, $details) || isset($details[$name])) {
                 //to handle custom data (checkbox) to be written
                 // to handle birth/deceased date, greeting_type and few other fields
                 if ($name == 'birth_date' || $name == 'deceased_date') {
                     list($defaults[$fldName]) = CRM_Utils_Date::setDateDefaults($details[$name], 'birth');
                 } elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)) {
                     $defaults[$fldName] = $details[$name . '_id'];
                     $defaults[$name . '_custom'] = $details[$name . '_custom'];
                 } elseif ($name == 'preferred_communication_method') {
                     $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details[$name]);
                     foreach ($v as $item) {
                         if ($item) {
                             $defaults[$fldName . "[{$item}]"] = 1;
                         }
                     }
                 } elseif ($name == 'world_region') {
                     $defaults[$fldName] = $details['worldregion_id'];
                 } elseif ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($name)) {
                     //fix for custom fields
                     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $details));
                     // hack to add custom data for components
                     $components = array('Contribution', 'Participant', 'Membership', 'Activity');
                     foreach ($components as $value) {
                         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFieldsForImport($value));
                     }
                     switch ($customFields[$customFieldId]['html_type']) {
                         case 'Multi-Select State/Province':
                         case 'Multi-Select Country':
                         case 'AdvMulti-Select':
                         case 'Multi-Select':
                             $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details[$name]);
                             foreach ($v as $item) {
                                 if ($item) {
                                     $defaults[$fldName][$item] = $item;
                                 }
                             }
                             break;
                         case 'CheckBox':
                             $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details[$name]);
                             foreach ($v as $item) {
                                 if ($item) {
                                     $defaults[$fldName][$item] = 1;
                                     // seems like we need this for QF style checkboxes in profile where its multiindexed
                                     // CRM-2969
                                     $defaults["{$fldName}[{$item}]"] = 1;
                                 }
                             }
                             break;
                         case 'Autocomplete-Select':
                             if ($customFields[$customFieldId]['data_type'] == 'ContactReference') {
                                 if (is_numeric($details[$name])) {
                                     $defaults[$fldName . '_id'] = $details[$name];
                                     $defaults[$fldName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $details[$name], 'sort_name');
                                 }
                             } else {
                                 $label = CRM_Core_BAO_CustomOption::getOptionLabel($customFieldId, $details[$name]);
                                 $defaults[$fldName . '_id'] = $details[$name];
                                 $defaults[$fldName] = $label;
                             }
                             break;
                         case 'Select Date':
                             // CRM-6681, set defult values according to date and time format (if any).
                             $dateFormat = NULL;
                             if (CRM_Utils_Array::value('date_format', $customFields[$customFieldId])) {
                                 $dateFormat = $customFields[$customFieldId]['date_format'];
                             }
                             if (!CRM_Utils_Array::value('time_format', $customFields[$customFieldId])) {
                                 list($defaults[$fldName]) = CRM_Utils_Date::setDateDefaults($details[$name], NULL, $dateFormat);
                             } else {
                                 $timeElement = $fldName . '_time';
                                 if (substr($fldName, -1) == ']') {
                                     $timeElement = substr($fldName, 0, -1) . '_time]';
                                 }
                                 list($defaults[$fldName], $defaults[$timeElement]) = CRM_Utils_Date::setDateDefaults($details[$name], NULL, $dateFormat, $customFields[$customFieldId]['time_format']);
                             }
                             break;
                         default:
                             $defaults[$fldName] = $details[$name];
                             break;
                     }
                 } else {
                     $defaults[$fldName] = $details[$name];
                 }
             } else {
                 $blocks = array('email', 'phone', 'im', 'openid');
                 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $name, 3);
                 if (!in_array($fieldName, $multipleFields)) {
                     if (is_array($details)) {
                         foreach ($details as $key => $value) {
                             // when we fixed CRM-5319 - get primary loc
                             // type as per loc field and removed below code.
                             $primaryLocationType = FALSE;
                             if ($locTypeId == 'Primary') {
                                 if (is_array($value) && array_key_exists($fieldName, $value)) {
                                     $primaryLocationType = TRUE;
                                     if (in_array($fieldName, $blocks)) {
                                         $locTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactId, FALSE, $fieldName);
                                     } else {
                                         $locTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactId, FALSE, 'address');
                                     }
                                 }
                             }
                             // fixed for CRM-665
                             if (is_numeric($locTypeId)) {
                                 if ($primaryLocationType || $locTypeId == CRM_Utils_Array::value('location_type_id', $value)) {
                                     if (CRM_Utils_Array::value($fieldName, $value)) {
                                         //to handle stateprovince and country
                                         if ($fieldName == 'state_province') {
                                             $defaults[$fldName] = $value['state_province_id'];
                                         } elseif ($fieldName == 'county') {
                                             $defaults[$fldName] = $value['county_id'];
                                         } elseif ($fieldName == 'country') {
                                             if (!isset($value['country_id']) || !$value['country_id']) {
                                                 $config = CRM_Core_Config::singleton();
                                                 if ($config->defaultContactCountry) {
                                                     $defaults[$fldName] = $config->defaultContactCountry;
                                                 }
                                             } else {
                                                 $defaults[$fldName] = $value['country_id'];
                                             }
                                         } elseif ($fieldName == 'phone') {
                                             if ($phoneTypeId) {
                                                 if (isset($value['phone'][$phoneTypeId])) {
                                                     $defaults[$fldName] = $value['phone'][$phoneTypeId];
                                                 }
                                                 if (isset($value['phone_ext'][$phoneTypeId])) {
                                                     $defaults[str_replace('phone', 'phone_ext', $fldName)] = $value['phone_ext'][$phoneTypeId];
                                                 }
                                             } else {
                                                 $phoneDefault = CRM_Utils_Array::value('phone', $value);
                                                 // CRM-9216
                                                 if (!is_array($phoneDefault)) {
                                                     $defaults[$fldName] = $phoneDefault;
                                                 }
                                             }
                                         } elseif ($fieldName == 'email') {
                                             //adding the first email (currently we don't support multiple emails of same location type)
                                             $defaults[$fldName] = $value['email'];
                                         } elseif ($fieldName == 'im') {
                                             //adding the first im (currently we don't support multiple ims of same location type)
                                             $defaults[$fldName] = $value['im'];
                                             $defaults[$fldName . '-provider_id'] = $value['im_provider_id'];
                                         } else {
                                             $defaults[$fldName] = $value[$fieldName];
                                         }
                                     } elseif (substr($fieldName, 0, 14) === 'address_custom' && CRM_Utils_Array::value(substr($fieldName, 8), $value)) {
                                         $defaults[$fldName] = $value[substr($fieldName, 8)];
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     if (is_array($details)) {
                         if ($fieldName === 'url') {
                             if (!empty($details['website'])) {
                                 foreach ($details['website'] as $val) {
                                     $defaults[$fldName] = CRM_Utils_Array::value('url', $val);
                                     $defaults[$fldName . '-website_type_id'] = $val['website_type_id'];
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     //Handling Contribution Part of the batch profile
     if (CRM_Core_Permission::access('CiviContribute') && $component == 'Contribute') {
         self::setComponentDefaults($fields, $componentId, $component, $defaults);
     }
     //Handling Event Participation Part of the batch profile
     if (CRM_Core_Permission::access('CiviEvent') && $component == 'Event') {
         self::setComponentDefaults($fields, $componentId, $component, $defaults);
     }
     //Handling membership Part of the batch profile
     if (CRM_Core_Permission::access('CiviMember') && $component == 'Membership') {
         self::setComponentDefaults($fields, $componentId, $component, $defaults);
     }
     //Handling Activity Part of the batch profile
     if ($component == 'Activity') {
         self::setComponentDefaults($fields, $componentId, $component, $defaults);
     }
 }
 /**
  * Extract the get params from the url, validate and store it in session.
  *
  * @param CRM_Core_Form $form
  *   The form object.
  * @param string $type
  *   The type of custom group we are using.
  *
  * @return array
  */
 public static function extractGetParams(&$form, $type)
 {
     if (empty($_GET)) {
         return array();
     }
     $groupTree = CRM_Core_BAO_CustomGroup::getTree($type);
     $customValue = array();
     $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
     foreach ($groupTree as $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $key => $field) {
             $fieldName = 'custom_' . $key;
             $value = CRM_Utils_Request::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
             if ($value) {
                 $valid = FALSE;
                 if (!in_array($field['html_type'], $htmlType) || $field['data_type'] == 'Boolean') {
                     $valid = CRM_Core_BAO_CustomValue::typecheck($field['data_type'], $value);
                 }
                 if ($field['html_type'] == 'CheckBox' || $field['html_type'] == 'AdvMulti-Select' || $field['html_type'] == 'Multi-Select') {
                     $value = str_replace("|", ",", $value);
                     $mulValues = explode(',', $value);
                     $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
                     $val = array();
                     foreach ($mulValues as $v1) {
                         foreach ($customOption as $coID => $coValue) {
                             if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
                                 $val[$coValue['value']] = 1;
                             }
                         }
                     }
                     if (!empty($val)) {
                         $value = $val;
                         $valid = TRUE;
                     } else {
                         $value = NULL;
                     }
                 } elseif ($field['html_type'] == 'Select' || $field['html_type'] == 'Radio' && $field['data_type'] != 'Boolean') {
                     $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
                     foreach ($customOption as $customID => $coValue) {
                         if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
                             $value = $coValue['value'];
                             $valid = TRUE;
                         }
                     }
                 } elseif ($field['data_type'] == 'Date') {
                     if (!empty($value)) {
                         $time = NULL;
                         if (!empty($field['time_format'])) {
                             $time = CRM_Utils_Request::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
                         }
                         list($value, $time) = CRM_Utils_Date::setDateDefaults($value . ' ' . $time);
                         if (!empty($field['time_format'])) {
                             $customValue[$fieldName . '_time'] = $time;
                         }
                     }
                     $valid = TRUE;
                 }
                 if ($valid) {
                     $customValue[$fieldName] = $value;
                 }
             }
         }
     }
     return $customValue;
 }
Example #22
0
function _crm_format_custom_params(&$params, &$values, $extends)
{
    $values['custom'] = array();
    $customFields = CRM_Core_BAO_CustomField::getFields($extends);
    foreach ($params as $key => $value) {
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            /* check if it's a valid custom field id */
            if (!array_key_exists($customFieldID, $customFields)) {
                return _crm_error('Invalid custom field ID');
            }
            $fieldType = null;
            // modified for CRM-1586
            // check data type for importing custom field (labels) with data type Integer/Float/Money
            /* validate the data against the CF type */
            if ($customFields[$customFieldID]['data_type'] == "Int" || $customFields[$customFieldID]['data_type'] == "Float" || $customFields[$customFieldID]['data_type'] == "Money") {
                if ($customFields[$customFieldID]['html_type'] == "Text") {
                    $fieldType = $customFields[$customFieldID]['data_type'];
                } else {
                    $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID);
                    foreach ($customOption as $customValue => $customLabel) {
                        //check wether $value is label or value
                        if (strtolower($customValue) == strtolower(trim($value))) {
                            $fieldType = "String";
                        } else {
                            if (strtolower($customValue) == strtolower(trim($value))) {
                                $fieldType = $customFields[$customFieldID]['data_type'];
                            }
                        }
                    }
                }
            } else {
                //set the Field type
                $fieldType = $customFields[$customFieldID]['data_type'];
            }
            $valid = null;
            //Validate the datatype of $value
            $valid = CRM_Core_BAO_CustomValue::typecheck($fieldType, $value);
            //return error, if not valid custom field
            if (!$valid) {
                return _crm_error('Invalid value for custom field ' . $customFields[$customFieldID][1]);
            }
            // fix the date field if so
            if ($customFields[$customFieldID]['data_type'] == 'Date') {
                $value = str_replace('-', '', $value);
            }
            // fixed for checkbox and multiselect
            $newMulValues = array();
            if ($customFields[$customFieldID]['html_type'] == 'CheckBox' || $customFields[$customFieldID]['html_type'] == 'Multi-Select') {
                $value = str_replace(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, ',', trim($value, CRM_Core_BAO_CustomOption::VALUE_SEPERATOR));
                $value = str_replace("|", ",", $value);
                $mulValues = explode(',', $value);
                $custumOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                foreach ($mulValues as $v1) {
                    foreach ($customOption as $customValue => $customLabel) {
                        if (strtolower($customLabel) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            $newMulValues[] = $customValue;
                        }
                    }
                }
                $value = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $newMulValues) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
            } else {
                if ($customFields[$customFieldID]['html_type'] == 'Select' || $customFields[$customFieldID]['html_type'] == 'Radio') {
                    $custumOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                    foreach ($customOption as $customValue => $customLabel) {
                        if (strtolower($customLabel) == strtolower(trim($value)) || strtolower($customValue) == strtolower(trim($value))) {
                            $value = $customValue;
                            break;
                        }
                    }
                }
            }
            $values['custom'][$customFieldID] = array('value' => $value, 'extends' => $customFields[$customFieldID]['extends'], 'type' => $customFields[$customFieldID]['data_type'], 'custom_field_id' => $customFieldID);
        }
    }
}
Example #23
0
 /**
  * Function to set default values for custom data used in profile
  *
  * @params int    $customFieldId custom field id
  * @params string $elementName   custom field name
  * @params array  $defaults      associated array of fields
  * @params int    $contactId     contact id
  * @param  int    $mode          profile mode
  * 
  * @static
  * @access public
  */
 static function setProfileDefaults($customFieldId, $elementName, &$defaults, $contactId = null, $mode = null)
 {
     //get the type of custom field
     $customField =& new CRM_Core_BAO_CustomField();
     $customField->id = $customFieldId;
     $customField->find(true);
     require_once "CRM/Profile/Form.php";
     $value = null;
     if (!$contactId) {
         if ($mode == CRM_Profile_Form::MODE_CREATE) {
             $value = $customField->default_value;
         }
     } else {
         $info = self::getTableColumnGroup($customFieldId);
         $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
         $result = CRM_Core_DAO::executeQuery($query);
         if ($result->fetch()) {
             $value = $result->value;
         }
         if ($customField->data_type == 'Country') {
             if (!$value) {
                 $config =& CRM_Core_Config::singleton();
                 if ($config->defaultContactCountry) {
                     $value = $config->defaultContactCountry();
                 }
             }
         }
     }
     //set defaults if mode is registration / edit
     if (!trim($value) && $value !== 0 && $mode != CRM_Profile_Form::MODE_SEARCH) {
         $value = $customField->default_value;
     }
     if ($customField->data_type == 'Money' && isset($value)) {
         $value = number_format($value, 2);
     }
     switch ($customField->html_type) {
         case 'CheckBox':
         case 'AdvMulti-Select':
         case 'Multi-Select':
             $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, false);
             $defaults[$elementName] = array();
             $checkedValue = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($value, 1, -1));
             foreach ($customOption as $val) {
                 if (in_array($val['value'], $checkedValue)) {
                     if ($customField->html_type == 'CheckBox') {
                         $defaults[$elementName][$val['value']] = 1;
                     } elseif ($customField->html_type == 'Multi-Select' || $customField->html_type == 'AdvMulti-Select') {
                         $defaults[$elementName][$val['value']] = $val['value'];
                     }
                 }
             }
             break;
         case 'Select Date':
             if ($value) {
                 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults($value, null, $customField->date_format, $customField->time_format);
             }
             break;
         default:
             $defaults[$elementName] = $value;
     }
 }
/**
 *
 * delete one or more option values
 *
 * @param $option  object   A valid custom field option object 
 *
 * @return null  if success
 *
 * @access public 
 *
 */
function crm_delete_option_value($option)
{
    _crm_initialize();
    if (!isset($option->id)) {
        return _crm_error("id of the custom option is not set.");
    }
    require_once 'CRM/Core/BAO/CustomOption.php';
    return CRM_Core_BAO_CustomOption::del($option->id);
}
Example #25
0
 static function autocomplete($value, $options)
 {
     if ($value) {
         $selectOption = CRM_Core_BAO_CustomOption::valuesByID($options['fieldID'], $options['optionGroupID']);
         if (!in_array($value, $selectOption)) {
             return FALSE;
         }
     }
     return TRUE;
 }
 /**
  * Function to fetch the values
  */
 static function autocomplete()
 {
     $fieldID = CRM_Utils_Type::escape($_GET['cfid'], 'Integer');
     $optionGroupID = CRM_Utils_Type::escape($_GET['ogid'], 'Integer');
     $label = CRM_Utils_Type::escape($_GET['s'], 'String');
     $selectOption = CRM_Core_BAO_CustomOption::valuesByID($fieldID, $optionGroupID);
     $completeList = NULL;
     foreach ($selectOption as $id => $value) {
         if (strtolower($label) == strtolower(substr($value, 0, strlen($label)))) {
             echo $completeList = "{$value}|{$id}\n";
         }
     }
     CRM_Utils_System::civiExit();
 }
Example #27
0
 /**
  * format common params data to proper format to store.
  *
  * @param array  $params        contain record values.
  * @param array  $formatted     array of formatted data.
  * @param array  $contactFields contact DAO fields.
  * @static
  */
 function formatCommonData($params, &$formatted, &$contactFields)
 {
     $csType = array(CRM_Utils_Array::value('contact_type', $formatted));
     //CRM-5125
     //add custom fields for contact sub type
     if (!empty($this->_contactSubType)) {
         $csType = $this->_contactSubType;
     }
     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) {
         $csType = $relCsType;
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], false, false, $csType);
     //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575
     $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee');
     foreach ($elements as $k => $v) {
         if (array_key_exists($k, $params) && !array_key_exists($v, $params)) {
             $label = key(CRM_Core_OptionGroup::values($v, true, null, null, 'AND v.name = "Customized"'));
             $params[$v] = $label;
         }
     }
     //format date first
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             //we should not update Date to null, CRM-4062
             if ($val && $customFields[$customFieldID]['data_type'] == 'Date') {
                 self::formatCustomDate($params, $formatted, $dateType, $key);
                 unset($params[$key]);
             } else {
                 if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
         if ($key == 'birth_date' && $val) {
             CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
         } else {
             if ($key == 'deceased_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } else {
                 if ($key == 'is_deceased' && $val) {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 } else {
                     if ($key == 'gender') {
                         //CRM-4360
                         $params[$key] = $this->checkGender($val);
                     }
                 }
             }
         }
     }
     //now format custom data.
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         if (is_array($field)) {
             foreach ($field as $value) {
                 $break = false;
                 if (is_array($value)) {
                     foreach ($value as $name => $testForEmpty) {
                         // check if $value does not contain IM provider or phoneType
                         if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == null)) {
                             $break = true;
                             break;
                         }
                     }
                 } else {
                     $break = true;
                 }
                 if (!$break) {
                     _civicrm_add_formatted_param($value, $formatted);
                 }
             }
             continue;
         }
         $formatValues = array($key => $field);
         if ($key !== 'preferred_communication_method' && array_key_exists($key, $contactFields)) {
             // due to merging of individual table and
             // contact table, we need to avoid
             // preferred_communication_method forcefully
             $formatValues['contact_type'] = $formatted['contact_type'];
         }
         if ($key == 'id' && isset($field)) {
             $formatted[$key] = $field;
         }
         _civicrm_add_formatted_param($formatValues, $formatted);
         //Handling Custom Data
         if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields)) {
             //get the html type.
             $type = $customFields[$customFieldID]['html_type'];
             switch ($type) {
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                     $mulValues = explode(',', $field);
                     $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                     $formatted[$key] = array();
                     foreach ($mulValues as $v1) {
                         foreach ($customOption as $v2) {
                             if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) {
                                 if ($type == 'CheckBox') {
                                     $formatted[$key][$v2['value']] = 1;
                                 } else {
                                     $formatted[$key][] = $v2['value'];
                                 }
                             }
                         }
                     }
                     break;
                 case 'Select':
                 case 'Radio':
                     $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                     foreach ($customOption as $v2) {
                         if (strtolower($v2['label']) == strtolower(trim($field)) || strtolower($v2['value']) == strtolower(trim($field))) {
                             $formatted[$key] = $v2['value'];
                         }
                     }
                     break;
                 case 'Multi-Select State/Province':
                     $mulValues = explode(',', $field);
                     $stateAbbr = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
                     $stateName = CRM_Core_PseudoConstant::stateProvince();
                     $formatted[$key] = $stateValues = array();
                     foreach ($mulValues as $values) {
                         if ($val = CRM_Utils_Array::key($values, $stateAbbr)) {
                             $formatted[$key][] = $val;
                         } else {
                             if ($val = CRM_Utils_Array::key($values, $stateName)) {
                                 $formatted[$key][] = $val;
                             }
                         }
                     }
                     break;
                 case 'Multi-Select Country':
                     $config =& CRM_Core_Config::singleton();
                     $limitCodes = $config->countryLimit();
                     $mulValues = explode(',', $field);
                     $formatted[$key] = array();
                     CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', true, 'name', 'is_active');
                     CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', true, 'iso_code');
                     foreach ($mulValues as $values) {
                         if ($val = CRM_Utils_Array::key($values, $countryNames)) {
                             $formatted[$key][] = $val;
                         } else {
                             if ($val = CRM_Utils_Array::key($values, $countryIsoCodes)) {
                                 $formatted[$key][] = $val;
                             } else {
                                 if ($val = CRM_Utils_Array::key($values, $limitCodes)) {
                                     $formatted[$key][] = $val;
                                 }
                             }
                         }
                     }
                     break;
             }
         }
     }
     // check for primary location type, whether it is already present for the contact or not, CRM-4423
     if (CRM_Utils_Array::value('id', $formatted) && isset($formatted['location'])) {
         $primaryLocationTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($formatted['id'], true);
         if (isset($primaryLocationTypeId)) {
             foreach ($formatted['location'] as $loc => $details) {
                 if ($primaryLocationTypeId == CRM_Utils_Array::value('location_type_id', $details)) {
                     $formatted['location'][$loc]['is_primary'] = 1;
                     break;
                 } else {
                     $formatted['location'][$loc]['is_primary'] = 0;
                 }
             }
         }
     }
     // parse street address, CRM-5450
     if ($this->_parseStreetAddress) {
         require_once 'CRM/Core/BAO/Address.php';
         if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
             foreach ($formatted['address'] as $instance => &$address) {
                 $streetAddress = CRM_Utils_Array::value('street_address', $address);
                 if (empty($streetAddress)) {
                     continue;
                 }
                 // parse address field.
                 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress);
                 //street address consider to be parsed properly,
                 //If we get street_name and street_number.
                 if (!CRM_Utils_Array::value('street_name', $parsedFields) || !CRM_Utils_Array::value('street_number', $parsedFields)) {
                     $parsedFields = array_fill_keys(array_keys($parsedFields), '');
                 }
                 // merge parse address w/ main address block.
                 $address = array_merge($address, $parsedFields);
             }
         }
     }
 }
/**
 * This function format location blocks w/ v3.0 format.
 *
 * @param array $values
 *   The variable(s) to be added.
 * @param array $params
 *   The structured parameter list.
 *
 * @return bool
 */
function _civicrm_api3_deprecated_add_formatted_location_blocks(&$values, &$params)
{
    static $fields = NULL;
    if ($fields == NULL) {
        $fields = array();
    }
    foreach (array('Phone', 'Email', 'IM', 'OpenID', 'Phone_Ext') as $block) {
        $name = strtolower($block);
        if (!array_key_exists($name, $values)) {
            continue;
        }
        if ($name == 'phone_ext') {
            $block = 'Phone';
        }
        // block present in value array.
        if (!array_key_exists($name, $params) || !is_array($params[$name])) {
            $params[$name] = array();
        }
        if (!array_key_exists($block, $fields)) {
            $className = "CRM_Core_DAO_{$block}";
            $fields[$block] =& $className::fields();
        }
        $blockCnt = count($params[$name]);
        // copy value to dao field name.
        if ($name == 'im') {
            $values['name'] = $values[$name];
        }
        _civicrm_api3_store_values($fields[$block], $values, $params[$name][++$blockCnt]);
        if (empty($params['id']) && $blockCnt == 1) {
            $params[$name][$blockCnt]['is_primary'] = TRUE;
        }
        // we only process single block at a time.
        return TRUE;
    }
    // handle address fields.
    if (!array_key_exists('address', $params) || !is_array($params['address'])) {
        $params['address'] = array();
    }
    $addressCnt = 1;
    foreach ($params['address'] as $cnt => $addressBlock) {
        if (CRM_Utils_Array::value('location_type_id', $values) == CRM_Utils_Array::value('location_type_id', $addressBlock)) {
            $addressCnt = $cnt;
            break;
        }
        $addressCnt++;
    }
    if (!array_key_exists('Address', $fields)) {
        require_once 'CRM/Core/DAO/Address.php';
        $fields['Address'] = CRM_Core_DAO_Address::fields();
    }
    // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
    // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
    // the address in CRM_Core_BAO_Address::create method
    if (!empty($values['location_type_id'])) {
        static $customFields = array();
        if (empty($customFields)) {
            $customFields = CRM_Core_BAO_CustomField::getFields('Address');
        }
        // make a copy of values, as we going to make changes
        $newValues = $values;
        foreach ($values as $key => $val) {
            $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
            if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
                // mark an entry in fields array since we want the value of custom field to be copied
                $fields['Address'][$key] = NULL;
                $htmlType = CRM_Utils_Array::value('html_type', $customFields[$customFieldID]);
                switch ($htmlType) {
                    case 'CheckBox':
                    case 'AdvMulti-Select':
                    case 'Multi-Select':
                        if ($val) {
                            $mulValues = explode(',', $val);
                            $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                            $newValues[$key] = array();
                            foreach ($mulValues as $v1) {
                                foreach ($customOption as $v2) {
                                    if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) {
                                        if ($htmlType == 'CheckBox') {
                                            $newValues[$key][$v2['value']] = 1;
                                        } else {
                                            $newValues[$key][] = $v2['value'];
                                        }
                                    }
                                }
                            }
                        }
                        break;
                }
            }
        }
        // consider new values
        $values = $newValues;
    }
    _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
    $addressFields = array('county', 'country', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name');
    foreach ($addressFields as $field) {
        if (array_key_exists($field, $values)) {
            if (!array_key_exists('address', $params)) {
                $params['address'] = array();
            }
            $params['address'][$addressCnt][$field] = $values[$field];
        }
    }
    if ($addressCnt == 1) {
        $params['address'][$addressCnt]['is_primary'] = TRUE;
    }
    return TRUE;
}
 /**
  * @deprecated - this function formats params according to v2 standards but
  * need to be sure about the impact of not calling it so retaining on the import class
  * take the input parameter list as specified in the data model and
  * convert it into the same format that we use in QF and BAO object
  *
  * @param array  $params       Associative array of property name/value
  *                             pairs to insert in new contact.
  * @param array  $values       The reformatted properties that we can use internally
  *
  * @param array  $create       Is the formatted Values array going to
  *                             be used for CRM_Member_BAO_Membership:create()
  *
  * @return array|error
  * @access public
  */
 function membership_format_params($params, &$values, $create = FALSE)
 {
     require_once 'api/v3/utils.php';
     $fields = CRM_Member_DAO_Membership::fields();
     _civicrm_api3_store_values($fields, $params, $values);
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
     foreach ($params as $key => $value) {
         // ignore empty values or empty arrays etc
         if (CRM_Utils_System::isNull($value)) {
             continue;
         }
         //Handling Custom Data
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             $values[$key] = $value;
             $type = $customFields[$customFieldID]['html_type'];
             if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
                 $mulValues = explode(',', $value);
                 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                 $values[$key] = array();
                 foreach ($mulValues as $v1) {
                     foreach ($customOption as $customValueID => $customLabel) {
                         $customValue = $customLabel['value'];
                         if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                             if ($type == 'CheckBox') {
                                 $values[$key][$customValue] = 1;
                             } else {
                                 $values[$key][] = $customValue;
                             }
                         }
                     }
                 }
             }
         }
         switch ($key) {
             case 'membership_contact_id':
                 if (!CRM_Utils_Rule::integer($value)) {
                     throw new Exception("contact_id not valid: {$value}");
                 }
                 $dao = new CRM_Core_DAO();
                 $qParams = array();
                 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams);
                 if (!$svq) {
                     throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                 }
                 $values['contact_id'] = $values['membership_contact_id'];
                 unset($values['membership_contact_id']);
                 break;
             case 'membership_type_id':
                 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) {
                     throw new Exception('Invalid Membership Type Id');
                 }
                 $values[$key] = $value;
                 break;
             case 'membership_type':
                 $membershipTypeId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipType());
                 if ($membershipTypeId) {
                     if (CRM_Utils_Array::value('membership_type_id', $values) && $membershipTypeId != $values['membership_type_id']) {
                         throw new Exception('Mismatched membership Type and Membership Type Id');
                     }
                 } else {
                     throw new Exception('Invalid Membership Type');
                 }
                 $values['membership_type_id'] = $membershipTypeId;
                 break;
             case 'status_id':
                 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) {
                     throw new Exception('Invalid Membership Status Id');
                 }
                 $values[$key] = $value;
                 break;
             case 'membership_status':
                 $membershipStatusId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipStatus());
                 if ($membershipStatusId) {
                     if (CRM_Utils_Array::value('status_id', $values) && $membershipStatusId != $values['status_id']) {
                         throw new Exception('Mismatched membership Status and Membership Status Id');
                     }
                 } else {
                     throw new Exception('Invalid Membership Status');
                 }
                 $values['status_id'] = $membershipStatusId;
                 break;
             default:
                 break;
         }
     }
     _civicrm_api3_custom_format_params($params, $values, 'Membership');
     if ($create) {
         // CRM_Member_BAO_Membership::create() handles membership_start_date,
         // membership_end_date and membership_source. So, if $values contains
         // membership_start_date, membership_end_date  or membership_source,
         // convert it to start_date, end_date or source
         $changes = array('membership_start_date' => 'start_date', 'membership_end_date' => 'end_date', 'membership_source' => 'source');
         foreach ($changes as $orgVal => $changeVal) {
             if (isset($values[$orgVal])) {
                 $values[$changeVal] = $values[$orgVal];
                 unset($values[$orgVal]);
             }
         }
     }
     return NULL;
 }
 /**
  * Set default values for custom data used in profile.
  *
  * @param int $customFieldId
  *   Custom field id.
  * @param string $elementName
  *   Custom field name.
  * @param array $defaults
  *   Associated array of fields.
  * @param int $contactId
  *   Contact id.
  * @param int $mode
  *   Profile mode.
  * @param mixed $value
  *   If passed - dont fetch value from db,.
  *                               just format the given value
  *
  */
 public static function setProfileDefaults($customFieldId, $elementName, &$defaults, $contactId = NULL, $mode = NULL, $value = NULL)
 {
     //get the type of custom field
     $customField = new CRM_Core_BAO_CustomField();
     $customField->id = $customFieldId;
     $customField->find(TRUE);
     if (!$contactId) {
         if ($mode == CRM_Profile_Form::MODE_CREATE) {
             $value = $customField->default_value;
         }
     } else {
         if (!isset($value)) {
             $info = self::getTableColumnGroup($customFieldId);
             $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
             $result = CRM_Core_DAO::executeQuery($query);
             if ($result->fetch()) {
                 $value = $result->value;
             }
         }
         if ($customField->data_type == 'Country') {
             if (!$value) {
                 $config = CRM_Core_Config::singleton();
                 if ($config->defaultContactCountry) {
                     $value = $config->defaultContactCountry();
                 }
             }
         }
     }
     //set defaults if mode is registration
     if (!trim($value) && $value !== 0 && !in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH))) {
         $value = $customField->default_value;
     }
     if ($customField->data_type == 'Money' && isset($value)) {
         $value = number_format($value, 2);
     }
     switch ($customField->html_type) {
         case 'CheckBox':
         case 'AdvMulti-Select':
         case 'Multi-Select':
             $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
             $defaults[$elementName] = array();
             $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
             foreach ($customOption as $val) {
                 if (in_array($val['value'], $checkedValue)) {
                     if ($customField->html_type == 'CheckBox') {
                         $defaults[$elementName][$val['value']] = 1;
                     } elseif ($customField->html_type == 'Multi-Select' || $customField->html_type == 'AdvMulti-Select') {
                         $defaults[$elementName][$val['value']] = $val['value'];
                     }
                 }
             }
             break;
         case 'Select Date':
             if ($value) {
                 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults($value, NULL, $customField->date_format, $customField->time_format);
             }
             break;
         case 'Autocomplete-Select':
             if ($customField->data_type == 'ContactReference') {
                 if (is_numeric($value)) {
                     $defaults[$elementName . '_id'] = $value;
                     $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
                 }
             } else {
                 $defaults[$elementName] = $value;
             }
             break;
         default:
             $defaults[$elementName] = $value;
     }
 }