Ejemplo n.º 1
0
 /**
  * @param string $name
  *   Symbolic name for the check.
  * @param string $message
  *   Printable message (short or long).
  * @param string $title
  *   Printable message (short).
  * @param string $level
  *   The severity of the message. Use PSR-3 log levels.
  *
  * @see Psr\Log\LogLevel
  */
 public function __construct($name, $message, $title, $level = \Psr\Log\LogLevel::WARNING)
 {
     $this->name = $name;
     $this->message = $message;
     $this->title = $title;
     // Handle non-integer severity levels.
     if (!CRM_Utils_Rule::integer($level)) {
         $level = CRM_Utils_Check::severityMap($level);
     }
     $this->level = $level;
 }
Ejemplo n.º 2
0
/**
 * Delete a relationship.
 *
 * @param array $params
 *
 * @return array
 *   API Result Array
 */
function civicrm_api3_relationship_delete($params)
{
    if (!CRM_Utils_Rule::integer($params['id'])) {
        return civicrm_api3_create_error('Invalid value for relationship ID');
    }
    $relationBAO = new CRM_Contact_BAO_Relationship();
    $relationBAO->id = $params['id'];
    if (!$relationBAO->find(TRUE)) {
        return civicrm_api3_create_error('Relationship id is not valid');
    } else {
        $relationBAO->del($params['id']);
        return civicrm_api3_create_success('Deleted relationship successfully');
    }
}
Ejemplo n.º 3
0
 /**
  * Validate a value against a CustomField type.
  *
  * @param string $type
  *   The type of the data.
  * @param string $value
  *   The data to be validated.
  *
  * @return bool
  *   True if the value is of the specified type
  */
 public static function typecheck($type, $value)
 {
     switch ($type) {
         case 'Memo':
             return TRUE;
         case 'String':
             return CRM_Utils_Rule::string($value);
         case 'Int':
             return CRM_Utils_Rule::integer($value);
         case 'Float':
         case 'Money':
             return CRM_Utils_Rule::numeric($value);
         case 'Date':
             if (is_numeric($value)) {
                 return CRM_Utils_Rule::dateTime($value);
             } else {
                 return CRM_Utils_Rule::date($value);
             }
         case 'Boolean':
             return CRM_Utils_Rule::boolean($value);
         case 'ContactReference':
             return CRM_Utils_Rule::validContact($value);
         case 'StateProvince':
             //fix for multi select state, CRM-3437
             $valid = FALSE;
             $mulValues = explode(',', $value);
             foreach ($mulValues as $key => $state) {
                 $valid = array_key_exists(strtolower(trim($state)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::stateProvinceAbbreviation()), CASE_LOWER)) || array_key_exists(strtolower(trim($state)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::stateProvince()), CASE_LOWER));
                 if (!$valid) {
                     break;
                 }
             }
             return $valid;
         case 'Country':
             //fix multi select country, CRM-3437
             $valid = FALSE;
             $mulValues = explode(',', $value);
             foreach ($mulValues as $key => $country) {
                 $valid = array_key_exists(strtolower(trim($country)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::countryIsoCode()), CASE_LOWER)) || array_key_exists(strtolower(trim($country)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::country()), CASE_LOWER));
                 if (!$valid) {
                     break;
                 }
             }
             return $valid;
         case 'Link':
             return CRM_Utils_Rule::url($value);
     }
     return FALSE;
 }
/**
 * Create a new Action Schedule
 *
 * @param array $params
 *
 * @return array
 *
 * {@getfields action_schedule_create}
 */
function civicrm_api3_action_schedule_create($params)
{
    if (empty($params['id'])) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('title', 'mapping_id', 'entity_status', 'entity_value'));
    }
    $ids = array();
    if (isset($params['id']) && !CRM_Utils_Rule::integer($params['id'])) {
        return civicrm_api3_create_error('Invalid value for ID');
    }
    if (!array_key_exists('name', $params) && !array_key_exists('id', $params)) {
        $params['name'] = CRM_Utils_String::munge($params['title']);
    }
    $actionSchedule = new CRM_Core_BAO_ActionSchedule();
    $actionSchedule = CRM_Core_BAO_ActionSchedule::add($params, $ids);
    $actSchedule = array();
    _civicrm_api3_object_to_array($actionSchedule, $actSchedule[$actionSchedule->id]);
    return civicrm_api3_create_success($actSchedule, $params, 'action_schedule', 'create', $actionSchedule);
}
Ejemplo n.º 5
0
/**
 * Create relationship type.
 *
 * @param array $params
 *   Array per getfields metadata.
 *
 * @return array
 */
function civicrm_api3_relationship_type_create($params)
{
    if (!isset($params['label_a_b'])) {
        $params['label_a_b'] = $params['name_a_b'];
    }
    if (!isset($params['label_b_a'])) {
        $params['label_b_a'] = $params['name_b_a'];
    }
    $ids = array();
    if (isset($params['id']) && !CRM_Utils_Rule::integer($params['id'])) {
        return civicrm_api3_create_error('Invalid value for relationship type ID');
    } else {
        $ids['relationshipType'] = CRM_Utils_Array::value('id', $params);
    }
    $relationType = CRM_Contact_BAO_RelationshipType::add($params, $ids);
    $relType = array();
    _civicrm_api3_object_to_array($relationType, $relType[$relationType->id]);
    return civicrm_api3_create_success($relType, $params, 'RelationshipType', 'create', $relationType);
}
Ejemplo n.º 6
0
 /**
  * Create or update a Status Preference entry.
  *
  * @param array $params
  *
  * @return array
  */
 public static function create($params)
 {
     $statusPreference = new CRM_Core_BAO_StatusPreference();
     // Default severity level to ignore is 0 (DEBUG).
     if (!isset($params['ignore_severity'])) {
         $params['ignore_severity'] = 0;
     }
     // Severity can be either text ('critical') or an integer <= 7.
     // It's a magic number, but based on PSR-3 standards.
     if (!CRM_Utils_Rule::integer($params['ignore_severity'])) {
         $params['ignore_severity'] = CRM_Utils_Check::severityMap($params['ignore_severity']);
     }
     if ($params['ignore_severity'] > 7) {
         CRM_Core_Error::fatal(ts('You can not pass a severity level higher than 7.'));
     }
     // If severity is now blank, you have an invalid severity string.
     if (is_null($params['ignore_severity'])) {
         CRM_Core_Error::fatal(ts('Invalid string passed as severity level.'));
     }
     // Check if this StatusPreference already exists.
     if (empty($params['id']) && CRM_Utils_Array::value('name', $params)) {
         $statusPreference->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
         $statusPreference->name = $params['name'];
         $statusPreference->find(TRUE);
     }
     $statusPreference->copyValues($params);
     $edit = $statusPreference->id ? TRUE : FALSE;
     if ($edit) {
         CRM_Utils_Hook::pre('edit', 'StatusPreference', $statusPreference->id, $statusPreference);
     } else {
         CRM_Utils_Hook::pre('create', 'StatusPreference', NULL, $statusPreference);
     }
     $statusPreference->save();
     if ($edit) {
         CRM_Utils_Hook::post('edit', 'StatusPreference', $statusPreference->id, $statusPreference);
     } else {
         CRM_Utils_Hook::post('create', 'StatusPreference', NULL, $statusPreference);
     }
     return $statusPreference;
 }
Ejemplo n.º 7
0
 /**
  * Get group type values of the profile.
  *
  * @param int $profileId
  * @param string $groupType
  *
  * @return array
  *   group type values
  */
 public static function groupTypeValues($profileId, $groupType = NULL)
 {
     $groupTypeValue = array();
     $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileId, 'group_type');
     $groupTypeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $groupTypes);
     if (empty($groupTypeParts[1])) {
         return $groupTypeValue;
     }
     $participantExtends = array('ParticipantRole', 'ParticipantEventName', 'ParticipantEventType');
     foreach (explode(',', $groupTypeParts[1]) as $groupTypeValues) {
         $values = array();
         $valueParts = explode(':', $groupTypeValues);
         if ($groupType && ($valueParts[0] != "{$groupType}Type" || $groupType == 'Participant' && !in_array($valueParts[0], $participantExtends))) {
             continue;
         }
         foreach ($valueParts as $val) {
             if (CRM_Utils_Rule::integer($val)) {
                 $values[$val] = $val;
             }
         }
         if (!empty($values)) {
             $typeName = substr($valueParts[0], 0, -4);
             if (in_array($valueParts[0], $participantExtends)) {
                 $typeName = $valueParts[0];
             }
             $groupTypeValue[$typeName] = $values;
         }
     }
     return $groupTypeValue;
 }
Ejemplo n.º 8
0
/**
 * Deletes a contact location.
 * 
 * @param object $contact        A valid Contact object (passed by reference).
 * @param string $location_id    A valid location ID.
 *
 * @return  null, if successful. CRM error object, if 'contact' or 'location_id' is invalid, permissions are insufficient, etc.
 *
 * @access public
 *
 */
function civicrm_location_delete(&$contact)
{
    _civicrm_initialize();
    if (!is_array($contact)) {
        return civicrm_create_error('Params need to be of type array!');
    }
    if (!isset($contact['contact_id'])) {
        return civicrm_create_error(ts('$contact is not valid contact datatype'));
    }
    require_once 'CRM/Utils/Rule.php';
    $locationTypeID = CRM_Utils_Array::value('location_type', $contact);
    if (!$locationTypeID || !CRM_Utils_Rule::integer($locationTypeID)) {
        return civicrm_create_error(ts('missing or invalid location'));
    }
    $result =& _civicrm_location_delete($contact);
    return $result;
}
Ejemplo n.º 9
0
 static function extractGroupTypes($groupType)
 {
     $returnGroupTypes = array();
     if (!$groupType) {
         return $returnGroupTypes;
     }
     $groupTypeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $groupType);
     foreach (explode(',', $groupTypeParts[0]) as $type) {
         $returnGroupTypes[$type] = $type;
     }
     if (CRM_Utils_Array::value(1, $groupTypeParts)) {
         foreach (explode(',', $groupTypeParts[1]) as $typeValue) {
             $groupTypeValues = $valueLabels = array();
             $valueParts = explode(':', $typeValue);
             $typeName = NULL;
             switch ($valueParts[0]) {
                 case 'ContributionType':
                     $typeName = 'Contribution';
                     $valueLabels = CRM_Contribute_PseudoConstant::financialType();
                     break;
                 case 'ParticipantRole':
                     $typeName = 'Participant';
                     $valueLabels = CRM_Event_PseudoConstant::participantRole();
                     break;
                 case 'ParticipantEventName':
                     $typeName = 'Participant';
                     $valueLabels = CRM_Event_PseudoConstant::event();
                     break;
                 case 'ParticipantEventType':
                     $typeName = 'Participant';
                     $valueLabels = CRM_Event_PseudoConstant::eventType();
                     break;
                 case 'MembershipType':
                     $typeName = 'Membership';
                     $valueLabels = CRM_Member_PseudoConstant::membershipType();
                     break;
                 case 'ActivityType':
                     $typeName = 'Activity';
                     $valueLabels = CRM_Core_PseudoConstant::ActivityType(TRUE, TRUE, FALSE, 'label', TRUE);
                     break;
             }
             foreach ($valueParts as $val) {
                 if (CRM_Utils_Rule::integer($val)) {
                     $groupTypeValues[$val] = CRM_Utils_Array::value($val, $valueLabels);
                 }
             }
             if (!is_array($returnGroupTypes[$typeName])) {
                 $returnGroupTypes[$typeName] = array();
             }
             $returnGroupTypes[$typeName][$valueParts[0]] = $groupTypeValues;
         }
     }
     return $returnGroupTypes;
 }
Ejemplo n.º 10
0
 /**
  * Handle the values in import mode.
  *
  * @param int $onDuplicate
  *   The code for what action to take on duplicates.
  * @param array $values
  *   The array of values belonging to this line.
  *
  * @return bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array('version' => 3);
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'participant_register_date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
                 $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
             }
         }
     }
     if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
         if (!empty($params['event_id'])) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $indieFields = CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant');
             if ($dao->find(TRUE)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $participantValues = array();
                 //@todo calling api functions directly is not supported
                 $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Import_Parser::ERROR;
                 }
                 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
                 if (!empty($formatted['fee_level'])) {
                     $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id);
                     CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
                 }
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Import_Parser::VALID;
             } else {
                 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $formatValues['version'] = 3;
         $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $formatted['version'] = 3;
                     $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = '';
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($formatValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Import_Parser::DUPLICATE;
             } elseif ($newParticipant['error_message']) {
                 array_unshift($values, $newParticipant['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
             return CRM_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
     }
     return CRM_Import_Parser::VALID;
 }
Ejemplo n.º 11
0
 /**
  * global validation rules for the form
  *
  * @param array $fields posted values of the form
  *
  * @return array list of errors to be posted back to the form
  * @static
  * @access public
  */
 static function formRule(&$fields, &$files, &$form)
 {
     $optionLabel = CRM_Utils_Type::escape($fields['label'], 'String');
     $optionValue = CRM_Utils_Type::escape($fields['value'], 'String');
     $fieldId = $form->_fid;
     $optionGroupId = $form->_optionGroupID;
     $temp = array();
     if (empty($form->_id)) {
         $query = "\nSELECT count(*) \n  FROM civicrm_option_value\n WHERE option_group_id = %1\n   AND label = %2";
         $params = array(1 => array($optionGroupId, 'Integer'), 2 => array($optionLabel, 'String'));
         if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
             $errors['label'] = ts('There is an entry with the same label.');
         }
         $query = "\nSELECT count(*) \n  FROM civicrm_option_value\n WHERE option_group_id = %1\n   AND value = %2";
         $params = array(1 => array($optionGroupId, 'Integer'), 2 => array($optionValue, 'String'));
         if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
             $errors['value'] = ts('There is an entry with the same value.');
         }
     } else {
         //capture duplicate entries while updating Custom Options
         $optionId = CRM_Utils_Type::escape($fields['optionId'], 'Integer');
         //check label duplicates within a custom field
         $query = "\nSELECT count(*) \n  FROM civicrm_option_value\n WHERE option_group_id = %1\n   AND id != %2\n   AND label = %3";
         $params = array(1 => array($optionGroupId, 'Integer'), 2 => array($optionId, 'Integer'), 3 => array($optionLabel, 'String'));
         if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
             $errors['label'] = ts('There is an entry with the same label.');
         }
         //check value duplicates within a custom field
         $query = "\nSELECT count(*) \n  FROM civicrm_option_value\n WHERE option_group_id = %1\n   AND id != %2\n   AND value = %3";
         $params = array(1 => array($optionGroupId, 'Integer'), 2 => array($optionId, 'Integer'), 3 => array($optionValue, 'String'));
         if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
             $errors['value'] = ts('There is an entry with the same value.');
         }
     }
     $query = "\nSELECT data_type \n  FROM civicrm_custom_field\n WHERE id = %1";
     $params = array(1 => array($fieldId, 'Integer'));
     $dao =& CRM_Core_DAO::executeQuery($query, $params);
     if ($dao->fetch()) {
         switch ($dao->data_type) {
             case 'Int':
                 if (!CRM_Utils_Rule::integer($fields["value"])) {
                     $errors['value'] = ts('Please enter a valid integer value.');
                 }
                 break;
             case 'Float':
                 //     case 'Money':
                 if (!CRM_Utils_Rule::numeric($fields["value"])) {
                     $errors['value'] = ts('Please enter a valid number value.');
                 }
                 break;
             case 'Money':
                 if (!CRM_Utils_Rule::money($fields["value"])) {
                     $errors['value'] = ts('Please enter a valid value.');
                 }
                 break;
             case 'Date':
                 if (!CRM_Utils_Rule::date($fields["value"])) {
                     $errors['value'] = ts('Please enter a valid date using YYYY-MM-DD format. Example: 2004-12-31.');
                 }
                 break;
             case 'Boolean':
                 if (!CRM_Utils_Rule::integer($fields["value"]) && ($fields["value"] != '1' || $fields["value"] != '0')) {
                     $errors['value'] = ts('Please enter 1 or 0 as value.');
                 }
                 break;
             case 'Country':
                 if (!empty($fields["value"])) {
                     $params = array(1 => array($fields['value'], 'String'));
                     $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
                     if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
                         $errors['value'] = ts('Invalid default value for country.');
                     }
                 }
                 break;
             case 'StateProvince':
                 if (!empty($fields["value"])) {
                     $params = array(1 => array($fields['value'], 'String'));
                     $query = "\nSELECT count(*) \n  FROM civicrm_state_province\n WHERE name = %1\n    OR abbreviation = %1";
                     if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
                         $errors['value'] = ts('The invalid value for State/Province data type');
                     }
                 }
                 break;
         }
     }
     return empty($errors) ? true : $errors;
 }
Ejemplo n.º 12
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|bool $create Is the formatted Values array going to
 *                             be used for CRM_Activity_BAO_Activity::create()
 *
 * @return array|CRM_Error
 */
function _civicrm_api3_deprecated_activity_formatted_param(&$params, &$values, $create = FALSE)
{
    // copy all the activity fields as is
    $fields = CRM_Activity_DAO_Activity::fields();
    _civicrm_api3_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(trim($customLabel['label'])) == strtolower(trim($v1)) || strtolower(trim($customValue)) == strtolower(trim($v1))) {
                            if ($type == 'CheckBox') {
                                $values[$key][$customValue] = 1;
                            } else {
                                $values[$key][] = $customValue;
                            }
                        }
                    }
                }
            } elseif ($type == 'Select' || $type == 'Radio') {
                $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($value));
                    if ($value == $label || $value == strtolower($val)) {
                        $values[$key] = $val;
                    }
                }
            }
        }
        if ($key == 'target_contact_id') {
            if (!CRM_Utils_Rule::integer($value)) {
                return civicrm_api3_create_error("contact_id not valid: {$value}");
            }
            $contactID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}");
            if (!$contactID) {
                return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
            }
        }
    }
    return NULL;
}
Ejemplo n.º 13
0
/**
 * Get sort, limit etc options from the params - supporting old & new formats.
 *
 * Get returnProperties for legacy
 *
 * @param array $params
 *   Params array as passed into civicrm_api.
 * @param bool $queryObject
 *   Is this supporting a queryObject api (e.g contact) - if so we support more options.
 *   for legacy report & return a unique fields array
 *
 * @param string $entity
 * @param string $action
 *
 * @throws API_Exception
 * @return array
 *   options extracted from params
 */
function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '')
{
    $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
    $is_count = FALSE;
    $sort = CRM_Utils_Array::value('sort', $params, 0);
    $sort = CRM_Utils_Array::value('option.sort', $params, $sort);
    $sort = CRM_Utils_Array::value('option_sort', $params, $sort);
    $offset = CRM_Utils_Array::value('offset', $params, 0);
    $offset = CRM_Utils_Array::value('option.offset', $params, $offset);
    // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
    $offset = CRM_Utils_Array::value('option_offset', $params, $offset);
    $limit = CRM_Utils_Array::value('rowCount', $params, 25);
    $limit = CRM_Utils_Array::value('option.limit', $params, $limit);
    $limit = CRM_Utils_Array::value('option_limit', $params, $limit);
    if (is_array(CRM_Utils_Array::value('options', $params))) {
        // is count is set by generic getcount not user
        $is_count = CRM_Utils_Array::value('is_count', $params['options']);
        $offset = CRM_Utils_Array::value('offset', $params['options'], $offset);
        $limit = CRM_Utils_Array::value('limit', $params['options'], $limit);
        $sort = CRM_Utils_Array::value('sort', $params['options'], $sort);
    }
    $returnProperties = array();
    // handle the format return =sort_name,display_name...
    if (array_key_exists('return', $params)) {
        if (is_array($params['return'])) {
            $returnProperties = array_fill_keys($params['return'], 1);
        } else {
            $returnProperties = explode(',', str_replace(' ', '', $params['return']));
            $returnProperties = array_fill_keys($returnProperties, 1);
        }
    }
    if ($entity && $action == 'get') {
        if (!empty($returnProperties['id'])) {
            $returnProperties[$lowercase_entity . '_id'] = 1;
            unset($returnProperties['id']);
        }
        switch (trim(strtolower($sort))) {
            case 'id':
            case 'id desc':
            case 'id asc':
                $sort = str_replace('id', $lowercase_entity . '_id', $sort);
        }
    }
    $options = array('offset' => CRM_Utils_Rule::integer($offset) ? $offset : NULL, 'sort' => CRM_Utils_Rule::string($sort) ? $sort : NULL, 'limit' => CRM_Utils_Rule::integer($limit) ? $limit : NULL, 'is_count' => $is_count, 'return' => !empty($returnProperties) ? $returnProperties : array());
    if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
        throw new API_Exception('invalid string in sort options');
    }
    if (!$queryObject) {
        return $options;
    }
    //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
    // if the queryobject is being used this should be used
    $inputParams = array();
    $legacyreturnProperties = array();
    $otherVars = array('sort', 'offset', 'rowCount', 'options', 'return', 'version', 'prettyprint', 'check_permissions', 'sequential');
    foreach ($params as $n => $v) {
        if (substr($n, 0, 7) == 'return.') {
            $legacyreturnProperties[substr($n, 7)] = $v;
        } elseif ($n == 'id') {
            $inputParams[$lowercase_entity . '_id'] = $v;
        } elseif (in_array($n, $otherVars)) {
        } else {
            $inputParams[$n] = $v;
            if ($v && !is_array($v) && stristr($v, 'SELECT')) {
                throw new API_Exception('invalid string');
            }
        }
    }
    $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
    $options['input_params'] = $inputParams;
    return $options;
}
Ejemplo n.º 14
0
 /**
  * Process that send e-mails
  *
  * @param int $contactID
  * @param $values
  * @param int $participantId
  * @param bool $isTest
  * @param bool $returnMessageText
  *
  * @return void
  */
 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE)
 {
     $template = CRM_Core_Smarty::singleton();
     $gIds = array('custom_pre_id' => $values['custom_pre_id'], 'custom_post_id' => $values['custom_post_id']);
     //get the params submitted by participant.
     $participantParams = CRM_Utils_Array::value($participantId, $values['params'], array());
     if (!$returnMessageText) {
         //send notification email if field values are set (CRM-1941)
         foreach ($gIds as $key => $gIdValues) {
             if ($gIdValues) {
                 if (!is_array($gIdValues)) {
                     $gIdValues = array($gIdValues);
                 }
                 foreach ($gIdValues as $gId) {
                     $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
                     if ($email) {
                         //get values of corresponding profile fields for notification
                         list($profileValues) = self::buildCustomDisplay($gId, NULL, $contactID, $template, $participantId, $isTest, TRUE, $participantParams);
                         list($profileValues) = $profileValues;
                         $val = array('id' => $gId, 'values' => $profileValues, 'email' => $email);
                         CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
                     }
                 }
             }
         }
     }
     if ($values['event']['is_email_confirm'] || $returnMessageText) {
         list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
         //send email only when email is present
         if (isset($email) || $returnMessageText) {
             $preProfileID = CRM_Utils_Array::value('custom_pre_id', $values);
             $postProfileID = CRM_Utils_Array::value('custom_post_id', $values);
             if (!empty($values['params']['additionalParticipant'])) {
                 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values, $preProfileID);
                 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values, $postProfileID);
             }
             self::buildCustomDisplay($preProfileID, 'customPre', $contactID, $template, $participantId, $isTest, NULL, $participantParams);
             self::buildCustomDisplay($postProfileID, 'customPost', $contactID, $template, $participantId, $isTest, NULL, $participantParams);
             $sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId);
             $tplParams = array_merge($values, $participantParams, array('email' => $email, 'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $values['event']), 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $values['event']), 'contributeMode' => CRM_Utils_Array::value('contributeMode', $template->_tpl_vars), 'participantID' => $participantId, 'conference_sessions' => $sessions, 'credit_card_number' => CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $participantParams)), 'credit_card_exp_date' => CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $participantParams)))));
             // CRM-13890 : NOTE wait list condition need to be given so that
             // wait list message is shown properly in email i.e. WRT online event registration template
             if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
                 $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
                 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($statusId, NULL, 'label');
             } elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule::integer($tplParams['participant_status'])) {
                 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($tplParams['participant_status'], NULL, 'label');
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_online_receipt', 'contactId' => $contactID, 'isTest' => $isTest, 'tplParams' => $tplParams, 'PDFFilename' => ts('confirmation') . '.pdf');
             // address required during receipt processing (pdf and email receipt)
             if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
                 $sendTemplateParams['tplParams']['address'] = $displayAddress;
                 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
             }
             // set lineItem details
             if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) {
                 // check if additional prticipant, if so filter only to relevant ones
                 // CRM-9902
                 if (!empty($values['params']['additionalParticipant'])) {
                     $ownLineItems = array();
                     foreach ($lineItem as $liKey => $liValue) {
                         $firstElement = array_pop($liValue);
                         if ($firstElement['entity_id'] == $participantId) {
                             $ownLineItems[0] = $lineItem[$liKey];
                             break;
                         }
                     }
                     if (!empty($ownLineItems)) {
                         $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
                     }
                 } else {
                     $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
                 }
             }
             if ($returnMessageText) {
                 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
                 return array('subject' => $subject, 'body' => $message, 'to' => $displayName, 'html' => $html);
             } else {
                 $sendTemplateParams['from'] = CRM_Utils_Array::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array::value('confirm_from_email', $values['event']) . ">";
                 $sendTemplateParams['toName'] = $displayName;
                 $sendTemplateParams['toEmail'] = $email;
                 $sendTemplateParams['autoSubmitted'] = TRUE;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values['event']);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values['event']);
                 // append invoice pdf to email
                 $template = CRM_Core_Smarty::singleton();
                 $taxAmt = $template->get_template_vars('totalTaxAmount');
                 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
                 if (isset($invoicing) && isset($prefixValue['is_email_pdf']) && !empty($values['contributionId'])) {
                     $sendTemplateParams['isEmailPdf'] = TRUE;
                     $sendTemplateParams['contributionId'] = $values['contributionId'];
                 }
                 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             }
         }
     }
 }
Ejemplo n.º 15
0
 /**
  * Format custom fields before inserting.
  *
  * @param int $customFieldId
  *   Custom field id.
  * @param array $customFormatted
  *   Formatted array.
  * @param mixed $value
  *   Value of custom field.
  * @param string $customFieldExtend
  *   Custom field extends.
  * @param int $customValueId
  *   Custom option value id.
  * @param int $entityId
  *   Entity id (contribution, membership...).
  * @param bool $inline
  *   Consider inline custom groups only.
  * @param bool $checkPermission
  *   If false, do not include permissioning clause.
  * @param bool $includeViewOnly
  *   If true, fields marked 'View Only' are included. Required for APIv3.
  *
  * @return array|NULL
  *   formatted custom field array
  */
 public static function formatCustomField($customFieldId, &$customFormatted, $value, $customFieldExtend, $customValueId = NULL, $entityId = NULL, $inline = FALSE, $checkPermission = TRUE, $includeViewOnly = FALSE)
 {
     //get the custom fields for the entity
     //subtype and basic type
     $customDataSubType = NULL;
     if ($customFieldExtend) {
         // This is the case when getFieldsForImport() requires fields
         // of subtype and its parent.CRM-5143
         // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
         $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
         if (!empty($customDataSubType) && is_array($customDataSubType)) {
             $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
             if (is_array($customFieldExtend)) {
                 $customFieldExtend = array_unique(array_values($customFieldExtend));
             }
         }
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend, FALSE, $inline, $customDataSubType, NULL, FALSE, FALSE, $checkPermission);
     if (!array_key_exists($customFieldId, $customFields)) {
         return NULL;
     }
     // return if field is a 'code' field
     if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
         return NULL;
     }
     list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
     if (!$customValueId && !$customFields[$customFieldId]['is_multiple'] && $entityId) {
         $query = "\nSELECT id\n  FROM {$tableName}\n WHERE entity_id={$entityId}";
         $customValueId = CRM_Core_DAO::singleValueQuery($query);
     }
     //fix checkbox, now check box always submits values
     if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
         if ($value) {
             // Note that only during merge this is not an array, and you can directly use value
             if (is_array($value)) {
                 $selectedValues = array();
                 foreach ($value as $selId => $val) {
                     if ($val) {
                         $selectedValues[] = $selId;
                     }
                 }
                 if (!empty($selectedValues)) {
                     $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $selectedValues) . CRM_Core_DAO::VALUE_SEPARATOR;
                 } else {
                     $value = '';
                 }
             }
         }
     }
     if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' || $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select') {
         if ($value) {
             $value = CRM_Utils_Array::implodePadded($value);
         } else {
             $value = '';
         }
     }
     if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' || $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' || $customFields[$customFieldId]['html_type'] == 'CheckBox') && $customFields[$customFieldId]['data_type'] == 'String' && !empty($customFields[$customFieldId]['text_length']) && !empty($value)) {
         // lets make sure that value is less than the length, else we'll
         // be losing some data, CRM-7481
         if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
             // need to do a few things here
             // 1. lets find a new length
             $newLength = $customFields[$customFieldId]['text_length'];
             $minLength = strlen($value);
             while ($newLength < $minLength) {
                 $newLength = $newLength * 2;
             }
             // set the custom field meta data to have a length larger than value
             // alter the custom value table column to match this length
             CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
         }
     }
     $date = NULL;
     if ($customFields[$customFieldId]['data_type'] == 'Date') {
         if (!CRM_Utils_System::isNull($value)) {
             $format = $customFields[$customFieldId]['date_format'];
             $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
         }
         $value = $date;
     }
     if ($customFields[$customFieldId]['data_type'] == 'Float' || $customFields[$customFieldId]['data_type'] == 'Money') {
         if (!$value) {
             $value = 0;
         }
         if ($customFields[$customFieldId]['data_type'] == 'Money') {
             $value = CRM_Utils_Rule::cleanMoney($value);
         }
     }
     if (($customFields[$customFieldId]['data_type'] == 'StateProvince' || $customFields[$customFieldId]['data_type'] == 'Country') && empty($value)) {
         // CRM-3415
         $value = 0;
     }
     $fileId = NULL;
     if ($customFields[$customFieldId]['data_type'] == 'File') {
         if (empty($value)) {
             return;
         }
         $config = CRM_Core_Config::singleton();
         $fName = $value['name'];
         $mimeType = $value['type'];
         // If we are already passing the file id as a value then retrieve and set the file data
         if (CRM_Utils_Rule::integer($value)) {
             $fileDAO = new CRM_Core_DAO_File();
             $fileDAO->id = $value;
             $fileDAO->find(TRUE);
             if ($fileDAO->N) {
                 $fileID = $value;
                 $fName = $fileDAO->uri;
                 $mimeType = $fileDAO->mime_type;
             }
         }
         $filename = pathinfo($fName, PATHINFO_BASENAME);
         // rename this file to go into the secure directory only if
         // user has uploaded new file not existing verfied on the basis of $fileID
         if (empty($fileID) && !rename($fName, $config->customFileUploadDir . $filename)) {
             CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
         }
         if ($customValueId && empty($fileID)) {
             $query = "\nSELECT {$columnName}\n  FROM {$tableName}\n WHERE id = %1";
             $params = array(1 => array($customValueId, 'Integer'));
             $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
         }
         $fileDAO = new CRM_Core_DAO_File();
         if ($fileId) {
             $fileDAO->id = $fileId;
         }
         $fileDAO->uri = $filename;
         $fileDAO->mime_type = $mimeType;
         $fileDAO->upload_date = date('Ymdhis');
         $fileDAO->save();
         $fileId = $fileDAO->id;
         $value = $filename;
     }
     if (!is_array($customFormatted)) {
         $customFormatted = array();
     }
     if (!array_key_exists($customFieldId, $customFormatted)) {
         $customFormatted[$customFieldId] = array();
     }
     $index = -1;
     if ($customValueId) {
         $index = $customValueId;
     }
     if (!array_key_exists($index, $customFormatted[$customFieldId])) {
         $customFormatted[$customFieldId][$index] = array();
     }
     $customFormatted[$customFieldId][$index] = array('id' => $customValueId > 0 ? $customValueId : NULL, 'value' => $value, 'type' => $customFields[$customFieldId]['data_type'], 'custom_field_id' => $customFieldId, 'custom_group_id' => $groupID, 'table_name' => $tableName, 'column_name' => $columnName, 'file_id' => $fileId, 'is_multiple' => $customFields[$customFieldId]['is_multiple']);
     //we need to sort so that custom fields are created in the order of entry
     krsort($customFormatted[$customFieldId]);
     return $customFormatted;
 }
Ejemplo n.º 16
0
 /**
  * global validation rules for the form
  *
  */
 static function formRule($fields, $files, $form)
 {
     $errors = array();
     if (CRM_Utils_Array::value('option_label', $fields) && CRM_Utils_Array::value('option_value', $fields) && count(array_filter($fields['option_label'])) == 0 && count(array_filter($fields['option_value'])) == 0) {
         $errors['option_label[1]'] = ts('Enter atleast one response option.');
         return $errors;
     } else {
         if (!CRM_Utils_Array::value('option_label', $fields) && !CRM_Utils_Array::value('option_value', $fields)) {
             return $errors;
         }
     }
     if ($fields['option_type'] == 2 && !CRM_Utils_Array::value('option_group_id', $fields)) {
         $errors['option_group_id'] = ts("Please select Survey Response set.");
         return $errors;
     }
     $_flagOption = $_rowError = 0;
     $_showHide = new CRM_Core_ShowHideBlocks('', '');
     //capture duplicate Custom option values
     if (!empty($fields['option_value'])) {
         $countValue = count($fields['option_value']);
         $uniqueCount = count(array_unique($fields['option_value']));
         if ($countValue > $uniqueCount) {
             $start = 1;
             while ($start < self::NUM_OPTION) {
                 $nextIndex = $start + 1;
                 while ($nextIndex <= self::NUM_OPTION) {
                     if ($fields['option_value'][$start] == $fields['option_value'][$nextIndex] && !empty($fields['option_value'][$nextIndex])) {
                         $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
                         $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
                         $_flagOption = 1;
                     }
                     $nextIndex++;
                 }
                 $start++;
             }
         }
     }
     //capture duplicate Custom Option label
     if (!empty($fields['option_label'])) {
         $countValue = count($fields['option_label']);
         $uniqueCount = count(array_unique($fields['option_label']));
         if ($countValue > $uniqueCount) {
             $start = 1;
             while ($start < self::NUM_OPTION) {
                 $nextIndex = $start + 1;
                 while ($nextIndex <= self::NUM_OPTION) {
                     if ($fields['option_label'][$start] == $fields['option_label'][$nextIndex] && !empty($fields['option_label'][$nextIndex])) {
                         $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
                         $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
                         $_flagOption = 1;
                     }
                     $nextIndex++;
                 }
                 $start++;
             }
         }
     }
     for ($i = 1; $i <= self::NUM_OPTION; $i++) {
         if (!$fields['option_label'][$i]) {
             if ($fields['option_value'][$i]) {
                 $errors['option_label[' . $i . ']'] = ts('Option label cannot be empty');
                 $_flagOption = 1;
             } else {
                 $_emptyRow = 1;
             }
         } else {
             if (!strlen(trim($fields['option_value'][$i]))) {
                 if (!$fields['option_value'][$i]) {
                     $errors['option_value[' . $i . ']'] = ts('Option value cannot be empty');
                     $_flagOption = 1;
                 }
             }
         }
         if (CRM_Utils_Array::value($i, $fields['option_interval']) && !CRM_Utils_Rule::integer($fields['option_interval'][$i])) {
             $_flagOption = 1;
             $errors['option_interval[' . $i . ']'] = ts('Please enter a valid integer.');
         }
         $showBlocks = 'optionField_' . $i;
         if ($_flagOption) {
             $_showHide->addShow($showBlocks);
             $_rowError = 1;
         }
         if (!empty($_emptyRow)) {
             $_showHide->addHide($showBlocks);
         } else {
             $_showHide->addShow($showBlocks);
         }
         if ($i == self::NUM_OPTION) {
             $hideBlock = 'additionalOption';
             $_showHide->addHide($hideBlock);
         }
         $_flagOption = $_emptyRow = 0;
     }
     $_showHide->addToTemplate();
     return empty($errors) ? true : $errors;
 }
Ejemplo n.º 17
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Event_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($key == 'participant_register_date') {
                 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                     if (!CRM_Utils_Rule::date($params[$key])) {
                         CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                     }
                 } else {
                     CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                 }
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     if (!($params['participant_role_id'] || $params['participant_role'])) {
         if ($params['event_id']) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Event/BAO/Participant.php';
         $indieFields =& CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_participant_formatted_param($formatValues, $formatted, true);
     require_once "api/v2/Participant.php";
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Event_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Event_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Event_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             require_once 'CRM/Event/BAO/Participant.php';
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['participant_id'], 'Participant');
             if ($dao->find(true)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $newParticipant = civicrm_participant_check_params($formatted, false);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
                 $newParticipant =& CRM_Event_BAO_Participant::create($formatted, $ids);
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Event_Import_Parser::VALID;
             } else {
                 array_unshift($values, "Matching Participant record not found for Participant ID " . $formatValues['participant_id'] . ". Row was skipped.");
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Event_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
         $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Event_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant['error_data']);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant['error_data']);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", true);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Event_Import_Parser::DUPLICATE;
             } else {
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
             }
             return CRM_Event_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = $newParticipant['id'];
     }
     return CRM_Event_Import_Parser::VALID;
 }
Ejemplo n.º 18
0
 /**
  * update the custom calue for a given contact id and field id
  *
  * @param int    $contactId contact id
  * @param int    $cfId      custom field id
  * @param string $value     the value to set the field
  *
  * @return void
  * @access public
  * @static
  */
 function updateValue($contactId, $cfId, $value)
 {
     $customValue =& new CRM_Core_BAO_CustomValue();
     $customValue->custom_field_id = $cfId;
     $customValue->entity_table = 'civicrm_contact';
     $customValue->entity_id = $contactId;
     $customValue->find(true);
     $cf =& new CRM_Core_BAO_CustomField();
     $cf->id = $cfId;
     $cf->find(true);
     if ($cf->data_type == 'StateProvince') {
         $states =& CRM_Core_PseudoConstant::stateProvince();
         if (CRM_Utils_Rule::integer($value)) {
             $customValue->int_data = $value;
             $customValue->char_data = CRM_Utils_Array::value($value, $states);
         } else {
             $customValue->int_data = CRM_Utils_Array::key($value, $states);
             $customValue->char_data = $value;
         }
     } elseif ($cf->data_type == 'Country') {
         $countries =& CRM_Core_PseudoConstant::country();
         if (CRM_Utils_Rule::integer($value)) {
             $customValue->int_data = $value;
             $customValue->char_data = CRM_Utils_Array::value($value, $countries);
         } else {
             $customValue->int_data = CRM_Utils_Array::key($value, $countries);
             $customValue->char_data = $value;
         }
     } else {
         $isBool = false;
         $field = $customValue->getField($isBool, $cf);
         if ($isBool) {
             $value = CRM_Utils_String::strtobool($value);
         }
         $customValue->{$field} = $value;
     }
     $customValue->save();
 }
Ejemplo n.º 19
0
/**
 * Helper function to validate custom field value
 *
 * @params String $fieldName    Custom field name (eg: custom_8 )
 * @params Mixed  $value        Field value to be validate
 * @params Array  $fieldDetails Field Details
 * @params Array  $errors       Collect validation  errors
 *
 * @param $fieldName
 * @param $value
 * @param $fieldDetails
 * @param array $errors
 *
 * @return Array  Validation errors
 * @todo remove this function - not in use but need to review functionality before
 * removing as it might be useful in wrapper layer
 */
function _civicrm_api3_custom_field_validate_field($fieldName, $value, $fieldDetails, &$errors = array())
{
    return;
    //see comment block
    if (!$value) {
        return $errors;
    }
    $dataType = $fieldDetails['data_type'];
    $htmlType = $fieldDetails['html_type'];
    switch ($dataType) {
        case 'Int':
            if (!CRM_Utils_Rule::integer($value)) {
                $errors[$fieldName] = 'Invalid integer value for ' . $fieldName;
            }
            break;
        case 'Float':
            if (!CRM_Utils_Rule::numeric($value)) {
                $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
            }
            break;
        case 'Money':
            if (!CRM_Utils_Rule::money($value)) {
                $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
            }
            break;
        case 'Link':
            if (!CRM_Utils_Rule::url($value)) {
                $errors[$fieldName] = 'Invalid link for ' . $fieldName;
            }
            break;
        case 'Boolean':
            if ($value != '1' && $value != '0') {
                $errors[$fieldName] = 'Invalid boolean (use 1 or 0) value for ' . $fieldName;
            }
            break;
        case 'Country':
            if (empty($value)) {
                break;
            }
            if ($htmlType != 'Multi-Select Country' && is_array($value)) {
                $errors[$fieldName] = 'Invalid country for ' . $fieldName;
                break;
            }
            if (!is_array($value)) {
                $value = array($value);
            }
            $query = "SELECT count(*) FROM civicrm_country WHERE id IN (" . implode(',', $value) . ")";
            if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
                $errors[$fieldName] = 'Invalid country(s) for ' . $fieldName;
            }
            break;
        case 'StateProvince':
            if (empty($value)) {
                break;
            }
            if ($htmlType != 'Multi-Select State/Province' && is_array($value)) {
                $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
                break;
            }
            if (!is_array($value)) {
                $value = array($value);
            }
            $query = "\nSELECT count(*)\n  FROM civicrm_state_province\n WHERE id IN ('" . implode("','", $value) . "')";
            if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
                $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
            }
            break;
        case 'ContactReference':
            //FIX ME
            break;
    }
    if (in_array($htmlType, array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select')) && !isset($errors[$fieldName])) {
        $options = CRM_Core_OptionGroup::valuesByID($fieldDetails['option_group_id']);
        if (!is_array($value)) {
            $value = array($value);
        }
        $invalidOptions = array_diff($value, array_keys($options));
        if (!empty($invalidOptions)) {
            $errors[$fieldName] = "Invalid option(s) for field '{$fieldName}': " . implode(',', $invalidOptions);
        }
    }
    return $errors;
}
Ejemplo n.º 20
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_Member_BAO_Membership:create()
 *
 * @return array|error
 * @access public
 */
function _civicrm_membership_format_params(&$params, &$values, $create = false)
{
    require_once "CRM/Member/DAO/Membership.php";
    $fields =& CRM_Member_DAO_Membership::fields();
    _civicrm_store_values($fields, $params, $values);
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        switch ($key) {
            case 'membership_contact_id':
                if (!CRM_Utils_Rule::integer($value)) {
                    return civicrm_create_error("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) {
                    return civicrm_create_error("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 'join_date':
            case 'membership_start_date':
            case 'membership_end_date':
                if (!CRM_Utils_Rule::date($value)) {
                    return civicrm_create_error("{$key} not a valid date: {$value}");
                }
                break;
            case 'membership_type_id':
                $id = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_MembershipType", $value, 'id', 'name');
                $values[$key] = $id;
                break;
            case 'status_id':
                $id = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_MembershipStatus", $value, 'id', 'name');
                $values[$key] = $id;
                break;
            default:
                break;
        }
    }
    _civicrm_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;
}
Ejemplo n.º 21
0
 /**
  * @dataProvider integerDataProvider
  */
 function testInteger($inputData, $expectedResult)
 {
     $this->assertEquals($expectedResult, CRM_Utils_Rule::integer($inputData));
 }
Ejemplo n.º 22
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values, $doGeocodeAddress = false)
 {
     $config =& CRM_Core_Config::singleton();
     $this->_unparsedStreetAddressContacts = array();
     if (!$doGeocodeAddress) {
         // CRM-5854, reset the geocode method to null to prevent geocoding
         $config->geocodeMethod = null;
     }
     // first make sure this is a valid line
     //$this->_updateWithId = false;
     $response = $this->summary($values);
     $statusFieldName = $this->_statusFieldName;
     if ($response != CRM_Import_Parser::VALID) {
         $importRecordParams = array($statusFieldName => 'INVALID', "{$statusFieldName}Msg" => "Invalid (Error Code: {$response})");
         $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('contact_type' => $this->_contactType);
     static $contactFields = null;
     if ($contactFields == null) {
         require_once "CRM/Contact/DAO/Contact.php";
         $contactFields =& CRM_Contact_DAO_Contact::import();
     }
     //check if external identifier exists in database
     if (CRM_Utils_Array::value('external_identifier', $params) && (CRM_Utils_Array::value('id', $params) || in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_SKIP, CRM_Import_Parser::DUPLICATE_NOCHECK)))) {
         require_once "CRM/Contact/BAO/Contact.php";
         if ($internalCid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
             if ($internalCid != CRM_Utils_Array::value('id', $params)) {
                 $errorMessage = ts('External Identifier already exists in database.');
                 array_unshift($values, $errorMessage);
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) {
         if (CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType, false, 'label')) {
             $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($this->_contactType, false, null);
             $params['contact_sub_type'] = array_search($subType, $subTypes);
         } elseif (!CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType)) {
             $message = "Mismatched or Invalid Contact SubType.";
             array_unshift($values, $message);
             return CRM_Import_Parser::NO_MATCH;
         }
     }
     //get contact id to format common data in update/fill mode,
     //if external identifier is present, CRM-4423
     if ($this->_updateWithId && !CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
         if ($cid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
             $formatted['id'] = $cid;
         }
     }
     //format common data, CRM-4062
     $this->formatCommonData($params, $formatted, $contactFields);
     $relationship = false;
     $createNewContact = true;
     // Support Match and Update Via Contact ID
     if ($this->_updateWithId) {
         $createNewContact = false;
         if (!CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
             if ($cid) {
                 $params['id'] = $cid;
             } else {
                 //update contact if dedupe found contact id, CRM-4148
                 $dedupeParams = $formatted;
                 //special case to check dedupe if external id present.
                 //if we send external id dedupe will stop.
                 unset($dedupeParams['external_identifier']);
                 $checkDedupe = _civicrm_duplicate_formatted_contact($dedupeParams);
                 if (civicrm_duplicate($checkDedupe)) {
                     $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
                     if (count($matchingContactIds) == 1) {
                         $params['id'] = array_pop($matchingContactIds);
                     } else {
                         $message = "More than one matching contact found for given criteria.";
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 } else {
                     $createNewContact = true;
                 }
             }
         }
         $error = _civicrm_duplicate_formatted_contact($formatted);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 $updateflag = true;
                 foreach ($matchedIDs as $contactId) {
                     if ($params['id'] == $contactId) {
                         $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
                         if ($formatted['contact_type'] == $contactType) {
                             //validation of subtype for update mode
                             //CRM-5125
                             $contactSubType = null;
                             if (CRM_Utils_Array::value('contact_sub_type', $params)) {
                                 $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
                             }
                             if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
                                 $message = "Mismatched contact SubTypes :";
                                 array_unshift($values, $message);
                                 $updateflag = false;
                                 $this->_retCode = CRM_Import_Parser::NO_MATCH;
                             } else {
                                 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId, false);
                                 $updateflag = false;
                                 $this->_retCode = CRM_Import_Parser::VALID;
                             }
                         } else {
                             $message = "Mismatched contact Types :";
                             array_unshift($values, $message);
                             $updateflag = false;
                             $this->_retCode = CRM_Import_Parser::NO_MATCH;
                         }
                     }
                 }
                 if ($updateflag) {
                     $message = "Mismatched contact IDs OR Mismatched contact Types :";
                     array_unshift($values, $message);
                     $this->_retCode = CRM_Import_Parser::NO_MATCH;
                 }
             }
         } else {
             $contactType = null;
             if (CRM_Utils_Array::value('id', $params)) {
                 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
                 if ($contactType) {
                     if ($formatted['contact_type'] == $contactType) {
                         //validation of subtype for update mode
                         //CRM-5125
                         $contactSubType = null;
                         if (CRM_Utils_Array::value('contact_sub_type', $params)) {
                             $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
                         }
                         if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
                             $message = "Mismatched contact SubTypes :";
                             array_unshift($values, $message);
                             $this->_retCode = CRM_Import_Parser::NO_MATCH;
                         } else {
                             $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $params['id'], false);
                             $this->_retCode = CRM_Import_Parser::VALID;
                         }
                     } else {
                         $message = "Mismatched contact Types :";
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 } else {
                     // we should avoid multiple errors for single record
                     // since we have already retCode and we trying to force again.
                     if ($this->_retCode != CRM_Import_Parser::NO_MATCH) {
                         $message = "No contact found for this contact ID:" . $params['id'];
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 }
             } else {
                 //CRM-4148
                 //now we want to create new contact on update/fill also.
                 $createNewContact = true;
             }
         }
         if (is_a($newContact, 'CRM_Contact_BAO_Contact')) {
             $relationship = true;
         } else {
             if (is_a($error, 'CRM_Core_Error')) {
                 $newContact = $error;
                 $relationship = true;
             }
         }
     }
     //fixed CRM-4148
     //now we create new contact in update/fill mode also.
     if ($createNewContact) {
         //CRM-4430, don't carry if not submitted.
         foreach (array('prefix', 'suffix', 'gender') as $name) {
             if (array_key_exists($name, $formatted)) {
                 if (in_array($name, array('prefix', 'suffix'))) {
                     $formattedName = "individual_{$name}";
                     $formatted[$formattedName] = CRM_Core_OptionGroup::getValue($formattedName, (string) $formatted[$name]);
                 } else {
                     $formatted[$name] = CRM_Core_OptionGroup::getValue($name, (string) $formatted[$name]);
                 }
             }
         }
         $newContact = $this->createContact($formatted, $contactFields, $onDuplicate);
     }
     if (is_object($newContact) || $newContact instanceof CRM_Contact_BAO_Contact) {
         $relationship = true;
         $newContact = clone $newContact;
         $this->_newContacts[] = $newContact->id;
         //get return code if we create new contact in update mode, CRM-4148
         if ($this->_updateWithId) {
             $this->_retCode = CRM_Import_Parser::VALID;
         }
     } else {
         if (civicrm_duplicate($newContact)) {
             $relationship = true;
             $contactID = $newContact['error_message']['params'][0];
             if (!in_array($contactID, $this->_newContacts)) {
                 $this->_newContacts[] = $contactID;
             }
         }
     }
     if ($relationship) {
         $primaryContactId = null;
         if (civicrm_duplicate($newContact)) {
             if (CRM_Utils_Rule::integer($newContact['error_message']['params'][0])) {
                 $primaryContactId = $newContact['error_message']['params'][0];
             }
         } else {
             $primaryContactId = $newContact->id;
         }
         if ((civicrm_duplicate($newContact) || is_a($newContact, 'CRM_Contact_BAO_Contact')) && $primaryContactId) {
             //relationship contact insert
             foreach ($params as $key => $field) {
                 list($id, $first, $second) = CRM_Utils_System::explode('_', $key, 3);
                 if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) {
                     continue;
                 }
                 $relationType = new CRM_Contact_DAO_RelationshipType();
                 $relationType->id = $id;
                 $relationType->find(true);
                 $direction = "contact_sub_type_{$second}";
                 $formatting = array('contact_type' => $params[$key]['contact_type']);
                 //set subtype for related contact CRM-5125
                 if (isset($relationType->{$direction})) {
                     //validation of related contact subtype for update mode
                     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $params[$key]) && $relCsType != $relationType->{$direction}) {
                         $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact");
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         $formatting['contact_sub_type'] = $relationType->{$direction};
                     }
                 }
                 $relationType->free();
                 $contactFields = null;
                 $contactFields = CRM_Contact_DAO_Contact::import();
                 //Relation on the basis of External Identifier.
                 if (!CRM_Utils_Array::value('id', $params[$key]) && isset($params[$key]['external_identifier'])) {
                     $params[$key]['id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['external_identifier'], 'id', 'external_identifier');
                 }
                 // check for valid related contact id in update/fill mode, CRM-4424
                 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL)) && CRM_Utils_Array::value('id', $params[$key])) {
                     $relatedContactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_type');
                     if (!$relatedContactType) {
                         $errorMessage = ts("No contact found for this related contact ID: %1", array(1 => $params[$key]['id']));
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         //validation of related contact subtype for update mode
                         //CRM-5125
                         $relatedCsType = null;
                         if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
                             $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_sub_type');
                         }
                         if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params[$key]['id'], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
                             $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact ID: %1", array(1 => $params[$key]['id']));
                             array_unshift($values, $errorMessage);
                             return CRM_Import_Parser::NO_MATCH;
                         } else {
                             // get related contact id to format data in update/fill mode,
                             //if external identifier is present, CRM-4423
                             $formatting['id'] = $params[$key]['id'];
                         }
                     }
                 }
                 //format common data, CRM-4062
                 $this->formatCommonData($field, $formatting, $contactFields);
                 //fixed for CRM-4148
                 if ($params[$key]['id']) {
                     $contact = array('contact_id' => $params[$key]['id']);
                     $defaults = array();
                     $relatedNewContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
                 } else {
                     $relatedNewContact = $this->createContact($formatting, $contactFields, $onDuplicate, null, false);
                 }
                 if (is_object($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) {
                     $relatedNewContact = clone $relatedNewContact;
                 }
                 $matchedIDs = array();
                 // To update/fill contact, get the matching contact Ids if duplicate contact found
                 // otherwise get contact Id from object of related contact
                 if (is_array($relatedNewContact) && civicrm_error($relatedNewContact)) {
                     if (civicrm_duplicate($relatedNewContact)) {
                         $matchedIDs = explode(',', $relatedNewContact['error_message']['params'][0]);
                     } else {
                         $errorMessage = $relatedNewContact['error_message'];
                         array_unshift($values, $errorMessage);
                         $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                         $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                         return CRM_Import_Parser::ERROR;
                     }
                 } else {
                     $matchedIDs[] = $relatedNewContact->id;
                 }
                 // update/fill related contact after getting matching Contact Ids, CRM-4424
                 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) {
                     //validation of related contact subtype for update mode
                     //CRM-5125
                     $relatedCsType = null;
                     if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
                         $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $matchedIDs[0], 'contact_sub_type');
                     }
                     if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($matchedIDs[0], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
                         $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.");
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         $updatedContact = $this->createContact($formatting, $contactFields, $onDuplicate, $matchedIDs[0]);
                     }
                 }
                 static $relativeContact = array();
                 if (civicrm_duplicate($relatedNewContact)) {
                     if (count($matchedIDs) >= 1) {
                         $relContactId = $matchedIDs[0];
                         //add relative contact to count during update & fill mode.
                         //logic to make count distinct by contact id.
                         if ($this->_newRelatedContacts || !empty($relativeContact)) {
                             $reContact = array_keys($relativeContact, $relContactId);
                             if (empty($reContact)) {
                                 $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                             }
                         } else {
                             $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                         }
                     }
                 } else {
                     $relContactId = $relatedNewContact->id;
                     $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                 }
                 if (civicrm_duplicate($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) {
                     //fix for CRM-1993.Checks for duplicate related contacts
                     if (count($matchedIDs) >= 1) {
                         //if more than one duplicate contact
                         //found, create relationship with first contact
                         // now create the relationship record
                         $relationParams = array();
                         $relationParams = array('relationship_type_id' => $key, 'contact_check' => array($relContactId => 1), 'is_active' => 1, 'skipRecentView' => true);
                         // we only handle related contact success, we ignore failures for now
                         // at some point wold be nice to have related counts as separate
                         $relationIds = array('contact' => $primaryContactId);
                         list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
                         CRM_Contact_BAO_Relationship::relatedMemberships($primaryContactId, $relationParams, $relationIds);
                         //handle current employer, CRM-3532
                         if ($valid) {
                             require_once 'CRM/Core/PseudoConstant.php';
                             $allRelationships = CRM_Core_PseudoConstant::relationshipType('name');
                             $relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $key);
                             $relationshipType = str_replace($relationshipTypeId . '_', '', $key);
                             $orgId = $individualId = null;
                             if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employee of') {
                                 $orgId = $relContactId;
                                 $individualId = $primaryContactId;
                             } else {
                                 if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') {
                                     $orgId = $primaryContactId;
                                     $individualId = $relContactId;
                                 }
                             }
                             if ($orgId && $individualId) {
                                 $currentEmpParams[$individualId] = $orgId;
                                 require_once 'CRM/Contact/BAO/Contact/Utils.php';
                                 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($this->_updateWithId) {
         //return warning if street address is unparsed, CRM-5886
         return $this->processMessage($values, $statusFieldName, $this->_retCode);
     }
     //dupe checking
     if (is_array($newContact) && civicrm_error($newContact)) {
         $code = null;
         if (($code = CRM_Utils_Array::value('code', $newContact['error_message'])) && $code == CRM_Core_Error::DUPLICATE_CONTACT) {
             $urls = array();
             // need to fix at some stage and decide if the error will return an
             // array or string, crude hack for now
             if (is_array($newContact['error_message']['params'][0])) {
                 $cids = $newContact['error_message']['params'][0];
             } else {
                 $cids = explode(',', $newContact['error_message']['params'][0]);
             }
             foreach ($cids as $cid) {
                 $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, true);
             }
             $url_string = implode("\n", $urls);
             // If we duplicate more than one record, skip no matter what
             if (count($cids) > 1) {
                 $errorMessage = ts('Record duplicates multiple contacts');
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 //combine error msg to avoid mismatch between error file columns.
                 $errorMessage .= "\n" . $url_string;
                 array_unshift($values, $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
             // Params only had one id, so shift it out
             $contactId = array_shift($cids);
             $cid = null;
             $vals = array('contact_id' => $contactId);
             if ($onDuplicate == CRM_Import_Parser::DUPLICATE_REPLACE) {
                 $result = civicrm_replace_contact_formatted($contactId, $formatted, $contactFields);
                 $cid = $result['result'];
             } else {
                 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
                     $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
                 } else {
                     if ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
                         $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
                     }
                 }
             }
             // else skip does nothing and just returns an error code.
             if ($cid) {
                 $contact = array('contact_id' => $cid);
                 $defaults = array();
                 $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
             }
             if (civicrm_error($newContact)) {
                 $contactID = $newContact['error_message']['params'][0];
                 if (!in_array($contactID, $this->_newContacts)) {
                     $this->_newContacts[] = $contactID;
                 }
             }
             //CRM-262 No Duplicate Checking
             if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
                 array_unshift($values, $url_string);
                 $importRecordParams = array($statusFieldName => 'DUPLICATE', "{$statusFieldName}Msg" => "Skipping duplicate record");
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::DUPLICATE;
             }
             $importRecordParams = array($statusFieldName => 'IMPORTED');
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             //return warning if street address is not parsed, CRM-5886
             return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
         } else {
             // Not a dupe, so we had an error
             $errorMessage = $newContact['error_message'];
             array_unshift($values, $errorMessage);
             $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             return CRM_Import_Parser::ERROR;
         }
     }
     // sleep(3);
     return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
 }
Ejemplo n.º 23
0
 /**
  * global validation rules for the form
  *
  * @param array  $fields   (referance) posted values of the form
  *
  * @return array    if errors then list of errors to be posted back to the form,
  *                  true otherwise
  * @static
  * @access public
  */
 static function formRule($fields, $files, $self)
 {
     $default = CRM_Utils_Array::value('default_value', $fields);
     $errors = array();
     //validate field label as well as name.
     $title = $fields['label'];
     $name = CRM_Utils_String::munge($title, '_', 64);
     $gId = $self->_gid;
     // CRM-7564
     $query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
     $fldCnt = CRM_Core_DAO::singleValueQuery($query, array(1 => array($name, 'String'), 2 => array($title, 'String'), 3 => array((int) $self->_id, 'Integer'), 4 => array($gId, 'Integer')));
     if ($fldCnt) {
         $errors['label'] = ts('Custom field \'%1\' already exists in Database.', array(1 => $title));
     }
     //checks the given custom field name doesnot start with digit
     if (!empty($title)) {
         // gives the ascii value
         $asciiValue = ord($title[0]);
         if ($asciiValue >= 48 && $asciiValue <= 57) {
             $errors['label'] = ts("Field's Name should not start with digit");
         }
     }
     // ensure that the label is not 'id'
     if (strtolower($title) == 'id') {
         $errors['label'] = ts("You cannot use 'id' as a field label.");
     }
     if (!isset($fields['data_type'][0]) || !isset($fields['data_type'][1])) {
         $errors['_qf_default'] = ts('Please enter valid - Data and Input Field Type.');
     }
     $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
     if ($default || $dataType == 'ContactReference') {
         switch ($dataType) {
             case 'Int':
                 if (!CRM_Utils_Rule::integer($default)) {
                     $errors['default_value'] = ts('Please enter a valid integer as default value.');
                 }
                 break;
             case 'Float':
                 if (!CRM_Utils_Rule::numeric($default)) {
                     $errors['default_value'] = ts('Please enter a valid number as default value.');
                 }
                 break;
             case 'Money':
                 if (!CRM_Utils_Rule::money($default)) {
                     $errors['default_value'] = ts('Please enter a valid number value.');
                 }
                 break;
             case 'Link':
                 if (!CRM_Utils_Rule::url($default)) {
                     $errors['default_value'] = ts('Please enter a valid link.');
                 }
                 break;
             case 'Date':
                 if (!CRM_Utils_Rule::date($default)) {
                     $errors['default_value'] = ts('Please enter a valid date as default value using YYYY-MM-DD format. Example: 2004-12-31.');
                 }
                 break;
             case 'Boolean':
                 if ($default != '1' && $default != '0') {
                     $errors['default_value'] = ts('Please enter 1 (for Yes) or 0 (for No) if you want to set a default value.');
                 }
                 break;
             case 'Country':
                 if (!empty($default)) {
                     $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
                     $params = array(1 => array($fields['default_value'], 'String'));
                     if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
                         $errors['default_value'] = ts('Invalid default value for country.');
                     }
                 }
                 break;
             case 'StateProvince':
                 if (!empty($default)) {
                     $query = "\nSELECT count(*)\n  FROM civicrm_state_province\n WHERE name = %1\n    OR abbreviation = %1";
                     $params = array(1 => array($fields['default_value'], 'String'));
                     if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
                         $errors['default_value'] = ts('The invalid default value for State/Province data type');
                     }
                 }
                 break;
             case 'ContactReference':
                 if ($fields['filter_selected'] == 'Advance' && CRM_Utils_Array::value('filter', $fields)) {
                     if (strpos($fields['filter'], 'entity=') !== FALSE) {
                         $errors['filter'] = ts("Please do not include entity parameter (entity is always 'contact')");
                     } elseif (strpos($fields['filter'], 'action=') === FALSE) {
                         $errors['filter'] = ts("Please specify 'action' parameter, it should be 'lookup' or 'get'");
                     } elseif (strpos($fields['filter'], 'action=get') === FALSE && strpos($fields['filter'], 'action=lookup') === FALSE) {
                         $errors['filter'] = ts("Only 'get' and 'lookup' actions are supported.");
                     }
                 }
                 $self->setDefaults(array('filter_selected', $fields['filter_selected']));
                 break;
         }
     }
     if (self::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
         if (!$fields['date_format']) {
             $errors['date_format'] = ts('Please select a date format.');
         }
     }
     /** Check the option values entered
      *  Appropriate values are required for the selected datatype
      *  Incomplete row checking is also required.
      */
     $_flagOption = $_rowError = 0;
     $_showHide = new CRM_Core_ShowHideBlocks('', '');
     $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
     if (isset($fields['data_type'][1])) {
         $dataField = $fields['data_type'][1];
     }
     $optionFields = array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select');
     if (isset($fields['option_type']) && $fields['option_type'] == 1) {
         //capture duplicate Custom option values
         if (!empty($fields['option_value'])) {
             $countValue = count($fields['option_value']);
             $uniqueCount = count(array_unique($fields['option_value']));
             if ($countValue > $uniqueCount) {
                 $start = 1;
                 while ($start < self::NUM_OPTION) {
                     $nextIndex = $start + 1;
                     while ($nextIndex <= self::NUM_OPTION) {
                         if ($fields['option_value'][$start] == $fields['option_value'][$nextIndex] && !empty($fields['option_value'][$nextIndex])) {
                             $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
                             $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
                             $_flagOption = 1;
                         }
                         $nextIndex++;
                     }
                     $start++;
                 }
             }
         }
         //capture duplicate Custom Option label
         if (!empty($fields['option_label'])) {
             $countValue = count($fields['option_label']);
             $uniqueCount = count(array_unique($fields['option_label']));
             if ($countValue > $uniqueCount) {
                 $start = 1;
                 while ($start < self::NUM_OPTION) {
                     $nextIndex = $start + 1;
                     while ($nextIndex <= self::NUM_OPTION) {
                         if ($fields['option_label'][$start] == $fields['option_label'][$nextIndex] && !empty($fields['option_label'][$nextIndex])) {
                             $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
                             $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
                             $_flagOption = 1;
                         }
                         $nextIndex++;
                     }
                     $start++;
                 }
             }
         }
         for ($i = 1; $i <= self::NUM_OPTION; $i++) {
             if (!$fields['option_label'][$i]) {
                 if ($fields['option_value'][$i]) {
                     $errors['option_label[' . $i . ']'] = ts('Option label cannot be empty');
                     $_flagOption = 1;
                 } else {
                     $_emptyRow = 1;
                 }
             } else {
                 if (!strlen(trim($fields['option_value'][$i]))) {
                     if (!$fields['option_value'][$i]) {
                         $errors['option_value[' . $i . ']'] = ts('Option value cannot be empty');
                         $_flagOption = 1;
                     }
                 }
             }
             if ($fields['option_value'][$i] && $dataType != 'String') {
                 if ($dataType == 'Int') {
                     if (!CRM_Utils_Rule::integer($fields['option_value'][$i])) {
                         $_flagOption = 1;
                         $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
                     }
                 } elseif ($dataType == 'Money') {
                     if (!CRM_Utils_Rule::money($fields['option_value'][$i])) {
                         $_flagOption = 1;
                         $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
                     }
                 } else {
                     if (!CRM_Utils_Rule::numeric($fields['option_value'][$i])) {
                         $_flagOption = 1;
                         $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
                     }
                 }
             }
             $showBlocks = 'optionField_' . $i;
             if ($_flagOption) {
                 $_showHide->addShow($showBlocks);
                 $_rowError = 1;
             }
             if (!empty($_emptyRow)) {
                 $_showHide->addHide($showBlocks);
             } else {
                 $_showHide->addShow($showBlocks);
             }
             if ($i == self::NUM_OPTION) {
                 $hideBlock = 'additionalOption';
                 $_showHide->addHide($hideBlock);
             }
             $_flagOption = $_emptyRow = 0;
         }
     } elseif (isset($dataField) && in_array($dataField, $optionFields) && !in_array($dataType, array('Boolean', 'Country', 'StateProvince'))) {
         if (!$fields['option_group_id']) {
             $errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
         } else {
             $query = "\nSELECT count(*)\nFROM   civicrm_custom_field\nWHERE  data_type != %1\nAND    option_group_id = %2";
             $params = array(1 => array(self::$_dataTypeKeys[$fields['data_type'][0]], 'String'), 2 => array($fields['option_group_id'], 'Integer'));
             $count = CRM_Core_DAO::singleValueQuery($query, $params);
             if ($count > 0) {
                 $errors['option_group_id'] = ts('The data type of the multiple choice option set you\'ve selected does not match the data type assigned to this field.');
             }
         }
     }
     $assignError = new CRM_Core_Page();
     if ($_rowError) {
         $_showHide->addToTemplate();
         $assignError->assign('optionRowError', $_rowError);
     } else {
         if (isset($fields['data_type'][1])) {
             switch (self::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
                 case 'Radio':
                     $_fieldError = 1;
                     $assignError->assign('fieldError', $_fieldError);
                     break;
                 case 'Checkbox':
                     $_fieldError = 1;
                     $assignError->assign('fieldError', $_fieldError);
                     break;
                 case 'Select':
                     $_fieldError = 1;
                     $assignError->assign('fieldError', $_fieldError);
                     break;
                 default:
                     $_fieldError = 0;
                     $assignError->assign('fieldError', $_fieldError);
             }
         }
         for ($idx = 1; $idx <= self::NUM_OPTION; $idx++) {
             $showBlocks = 'optionField_' . $idx;
             if (!empty($fields['option_label'][$idx])) {
                 $_showHide->addShow($showBlocks);
             } else {
                 $_showHide->addHide($showBlocks);
             }
         }
         $_showHide->addToTemplate();
     }
     // we can not set require and view at the same time.
     if (CRM_Utils_Array::value('is_required', $fields) && CRM_Utils_Array::value('is_view', $fields)) {
         $errors['is_view'] = ts('Can not set this field Required and View Only at the same time.');
     }
     return empty($errors) ? TRUE : $errors;
 }
Ejemplo n.º 24
0
 /**
  * @return bool
  */
 public function validate()
 {
     if (CRM_Utils_System::isNull($this->_value)) {
         return TRUE;
     }
     switch ($this->_name) {
         case 'contact_id':
             // note: we validate extistence of the contact in API, upon
             // insert (it would be too costlty to do a db call here)
             return CRM_Utils_Rule::integer($this->_value);
         case 'register_date':
             return CRM_Utils_Rule::date($this->_value);
             /* @codingStandardsIgnoreStart
                  case 'event_id':
                      static $events = null;
                      if (!$events) {
                          $events = CRM_Event_PseudoConstant::event();
                      }
                      if (in_array($this->_value, $events)) {
                          return true;
                      }
                      else {
                          return false;
                      }
                      break;
                @codingStandardsIgnoreEnd */
         /* @codingStandardsIgnoreStart
              case 'event_id':
                  static $events = null;
                  if (!$events) {
                      $events = CRM_Event_PseudoConstant::event();
                  }
                  if (in_array($this->_value, $events)) {
                      return true;
                  }
                  else {
                      return false;
                  }
                  break;
            @codingStandardsIgnoreEnd */
         default:
             break;
     }
     // check whether that's a valid custom field id
     // and if so, check the contents' validity
     if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) {
         static $customFields = NULL;
         if (!$customFields) {
             $customFields = CRM_Core_BAO_CustomField::getFields('Participant');
         }
         if (!array_key_exists($customFieldID, $customFields)) {
             return FALSE;
         }
         return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value);
     }
     return TRUE;
 }
Ejemplo n.º 25
0
 function validate()
 {
     if (CRM_Utils_System::isNull($this->_value)) {
         return true;
     }
     switch ($this->_name) {
         case 'contact_id':
             // note: we validate extistence of the contact in API, upon
             // insert (it would be too costlty to do a db call here)
             return CRM_Utils_Rule::integer($this->_value);
             break;
         case 'receive_date':
         case 'cancel_date':
         case 'receipt_date':
         case 'thankyou_date':
             return CRM_Utils_Rule::date($this->_value);
             break;
         case 'non_deductible_amount':
         case 'total_amount':
         case 'fee_amount':
         case 'net_amount':
             return CRM_Utils_Rule::money($this->_value);
             break;
         case 'trxn_id':
             static $seenTrxnIds = array();
             if (in_array($this->_value, $seenTrxnIds)) {
                 return false;
             } elseif ($this->_value) {
                 $seenTrxnIds[] = $this->_value;
                 return true;
             } else {
                 $this->_value = null;
                 return true;
             }
             break;
         case 'currency':
             return CRM_Utils_Rule::currencyCode($this->_value);
             break;
         case 'contribution_type':
             static $contributionTypes = null;
             if (!$contributionTypes) {
                 $contributionTypes =& CRM_Contribute_PseudoConstant::contributionType();
             }
             if (in_array($this->_value, $contributionTypes)) {
                 return true;
             } else {
                 return false;
             }
             break;
         case 'payment_instrument':
             static $paymentInstruments = null;
             if (!$paymentInstruments) {
                 $paymentInstruments =& CRM_Contribute_PseudoConstant::paymentInstrument();
             }
             if (in_array($this->_value, $paymentInstruments)) {
                 return true;
             } else {
                 return false;
             }
             break;
         default:
             break;
     }
     // check whether that's a valid custom field id
     // and if so, check the contents' validity
     if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) {
         static $customFields = null;
         if (!$customFields) {
             $customFields =& CRM_Core_BAO_CustomField::getFields('Contribution');
         }
         if (!array_key_exists($customFieldID, $customFields)) {
             return false;
         }
         return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value);
     }
     return true;
 }
Ejemplo n.º 26
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
 *                            '
 *
 * @return array|CRM_Error
 * @access public
 */
function _civicrm_pledge_format_params(&$params, &$values, $create = FALSE)
{
    // based on contribution apis - copy all the pledge fields - this function filters out non -valid fields but unfortunately
    // means we have to put them back where there are 2 names for the field (name in table & unique name)
    // since there is no clear std to use one or the other. Generally either works ? but not for create date
    // perhaps we should just copy $params across rather than run it through the 'filter'?
    // but at least the filter forces anomalies into the open. In several cases it turned out the unique names wouldn't work
    // even though they are 'generally' what is returned in the GET - implying they should
    $fields = CRM_Pledge_DAO_Pledge::fields();
    _civicrm_store_values($fields, $params, $values);
    //add back the fields we know of that got dropped by the previous function
    if ($params['pledge_create_date']) {
        //pledge_create_date will not be formatted by the format params function so change back to create_date
        $values['create_date'] = $params['pledge_create_date'];
    }
    if ($params['create_date']) {
        //create_date may have been dropped by the $fields function so retrieve it
        $values['create_date'] = $params['create_date'];
    }
    if (array_key_exists('installment_amount', $params)) {
        //field has been renamed - don't lose it! Note that this must be called
        // installment amount not pledge_installment_amount, pledge_original_installment_amount
        // or original_installment_amount to avoid error
        // Division by zero in CRM\Pledge\BAO\PledgePayment.php:162
        // but we should accept the variant because they are all 'logical assumptions' based on the
        // 'standards'
        $values['installment_amount'] = $params['installment_amount'];
    }
    if (array_key_exists('original_installment_amount', $params)) {
        $values['installment_amount'] = $params['original_installment_amount'];
    }
    if (array_key_exists('pledge_original_installment_amount', $params)) {
        $values['installment_amount'] = $params['pledge_original_installment_amount'];
    }
    if (array_key_exists('status_id', $params)) {
        $values['pledge_status_id'] = $params['status_id'];
    }
    if ($params['contact_id']) {
        //this is validity checked further down to make sure the contact exists
        $values['pledge_contact_id'] = $params['contact_id'];
    }
    if (array_key_exists('id', $params)) {
        //retrieve the id key dropped from params. Note we can't use pledge_id because it
        //causes an error in CRM_Pledge_BAO_PledgePayment - approx line 302
        $values['id'] = $params['id'];
    }
    if (array_key_exists('pledge_id', $params)) {
        //retrieve the id key dropped from params. Note we can't use pledge_id because it
        //causes an error in CRM_Pledge_BAO_PledgePayment - approx line 302
        $values['id'] = $params['pledge_id'];
        unset($values['pledge_id']);
    }
    if (array_key_exists('status_id', $params)) {
        $values['pledge_status_id'] = $params['status_id'];
    }
    if (empty($values['id'])) {
        //at this point both should be the same so unset both if not set - passing in empty
        //value causes crash rather creating new - do it before next section as null values ignored in 'switch'
        unset($values['id']);
    }
    if (!empty($params['scheduled_date'])) {
        //scheduled date is required to set next payment date - defaults to start date
        $values['scheduled_date'] = $params['scheduled_date'];
    } elseif (array_key_exists('start_date', $params)) {
        $values['scheduled_date'] = $params['start_date'];
    }
    if (CRM_Utils_Array::value('contribution_type_id', $params)) {
        $values['contribution_type_id'] = $params['contribution_type_id'];
    }
    foreach ($values as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        switch ($key) {
            case 'pledge_contact_id':
                if (!CRM_Utils_Rule::integer($value)) {
                    return civicrm_create_error("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) {
                    return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                }
                $values['contact_id'] = $values['pledge_contact_id'];
                unset($values['pledge_contact_id']);
                break;
            case 'pledge_id':
                if (!CRM_Utils_Rule::integer($value)) {
                    return civicrm_create_error("contact_id not valid: {$value}");
                }
                $dao = new CRM_Core_DAO();
                $qParams = array();
                $svq = $dao->singleValueQuery("SELECT id FROM civicrm_pledge WHERE id = {$value}", $qParams);
                if (!$svq) {
                    return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                }
                break;
            case 'create_date':
            case 'scheduled_date':
            case 'start_date':
                if (!CRM_Utils_Rule::datetime($value)) {
                    return civicrm_create_error("{$key} not a valid date: {$value}");
                }
                break;
            case 'installment_amount':
            case 'amount':
                if (!CRM_Utils_Rule::money($value)) {
                    return civicrm_create_error("{$key} not a valid amount: {$value}");
                }
                break;
            case 'currency':
                if (!CRM_Utils_Rule::currencyCode($value)) {
                    return civicrm_create_error("currency not a valid code: {$value}");
                }
                break;
            case 'contribution_type_id':
                require_once 'CRM/Contribute/PseudoConstant.php';
                $typeId = CRM_Contribute_PseudoConstant::contributionType($value);
                if (!CRM_Utils_Rule::integer($value) || !$typeId) {
                    return civicrm_create_error("contribution type id is not valid: {$value}");
                }
            default:
                break;
        }
    }
    //format the parameters
    _civicrm_custom_format_params($params, $values, 'Pledge');
    return array();
}
Ejemplo n.º 27
0
 /**
  * @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;
 }
Ejemplo n.º 28
0
/**
 * Delete a relationship type delete
 *
 * @param  id of relationship type  $id
 *
 * @return boolean  true if success, else false
 * @static void
 * @access public
 */
function civicrm_relationship_type_delete(&$params)
{
    if (!CRM_Utils_Array::value('id', $params)) {
        return civicrm_create_error('Missing required parameter');
    }
    require_once 'CRM/Utils/Rule.php';
    if ($params['id'] != null && !CRM_Utils_Rule::integer($params['id'])) {
        return civicrm_create_error('Invalid value for relationship type ID');
    }
    $relationTypeBAO = new CRM_Contact_BAO_RelationshipType();
    return $relationTypeBAO->del($params['id']) ? civicrm_create_success(ts('Deleted relationship type successfully')) : civicrm_create_error(ts('Could not delete relationship type'));
}
Ejemplo n.º 29
0
 function validate()
 {
     if (CRM_Utils_System::isNull($this->_value)) {
         return TRUE;
     }
     switch ($this->_name) {
         case 'contact_id':
             // note: we validate extistence of the contact in API, upon
             // insert (it would be too costlty to do a db call here)
             return CRM_Utils_Rule::integer($this->_value);
         default:
             break;
     }
 }
Ejemplo n.º 30
0
 /**
  * Verify that a variable is of a given type.
  *
  * @param mixed $data
  *   The value to validate.
  * @param string $type
  *   The type to validate against.
  * @param bool $abort
  *   If TRUE, the operation will CRM_Core_Error::fatal() on invalid data.
  * @name string $name
  *   The name of the attribute
  *
  * @return mixed
  *   The data, escaped if necessary
  */
 public static function validate($data, $type, $abort = TRUE, $name = 'One of parameters ')
 {
     switch ($type) {
         case 'Integer':
         case 'Int':
             if (CRM_Utils_Rule::integer($data)) {
                 return (int) $data;
             }
             break;
         case 'Positive':
             if (CRM_Utils_Rule::positiveInteger($data)) {
                 return $data;
             }
             break;
         case 'Boolean':
             if (CRM_Utils_Rule::boolean($data)) {
                 return $data;
             }
             break;
         case 'Float':
         case 'Money':
             if (CRM_Utils_Rule::numeric($data)) {
                 return $data;
             }
             break;
         case 'Text':
         case 'String':
         case 'Link':
         case 'Memo':
             return $data;
         case 'Date':
             // a null date is valid
             if (strlen(trim($data)) == 0) {
                 return trim($data);
             }
             if (preg_match('/^\\d{8}$/', $data) && CRM_Utils_Rule::mysqlDate($data)) {
                 return $data;
             }
             break;
         case 'Timestamp':
             // a null timestamp is valid
             if (strlen(trim($data)) == 0) {
                 return trim($data);
             }
             if ((preg_match('/^\\d{14}$/', $data) || preg_match('/^\\d{8}$/', $data)) && CRM_Utils_Rule::mysqlDate($data)) {
                 return $data;
             }
             break;
         case 'ContactReference':
             // null is valid
             if (strlen(trim($data)) == 0) {
                 return trim($data);
             }
             if (CRM_Utils_Rule::validContact($data)) {
                 return $data;
             }
             break;
         default:
             CRM_Core_Error::fatal("Cannot recognize {$type} for {$data}");
             break;
     }
     if ($abort) {
         $data = htmlentities($data);
         CRM_Core_Error::fatal("{$name} (value: {$data}) is not of the type {$type}");
     }
     return NULL;
 }