/**
  * Set defaults for the form.
  *
  * @return array
  */
 public function setDefaultValues()
 {
     $defaults = parent::setDefaultValues();
     if (!empty($defaults['preferred_language'])) {
         $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
         $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages);
     }
     // CRM-7119: set preferred_language to default if unset
     if (empty($defaults['preferred_language'])) {
         $config = CRM_Core_Config::singleton();
         $defaults['preferred_language'] = $config->lcMessages;
     }
     // CRM-19135: where CRM_Core_BAO_Contact::getValues() set label as a default value instead of reserved 'value',
     // the code is to ensure we always set default to value instead of label
     if (!empty($defaults['preferred_mail_format'])) {
         $defaults['preferred_mail_format'] = array_search($defaults['preferred_mail_format'], CRM_Core_SelectValues::pmf());
     }
     if (empty($defaults['communication_style_id'])) {
         $defaults['communication_style_id'] = array_pop(CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1'));
     }
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         $name = "{$greeting}_display";
         $this->assign($name, CRM_Utils_Array::value($name, $defaults));
     }
     return $defaults;
 }
Exemplo n.º 2
0
 /**
  * set defaults for the form
  *
  * @return array
  * @access public
  */
 public function setDefaultValues()
 {
     $defaults = parent::setDefaultValues();
     if (!empty($defaults['preferred_language'])) {
         $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
         $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages);
     }
     // CRM-7119: set preferred_language to default if unset
     if (empty($defaults['preferred_language'])) {
         $config = CRM_Core_Config::singleton();
         $defaults['preferred_language'] = $config->lcMessages;
     }
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         $name = "{$greeting}_display";
         $this->assign($name, CRM_Utils_Array::value($name, $defaults));
     }
     return $defaults;
 }
Exemplo n.º 3
0
 function __construct()
 {
     self::$nscd_fid = _iats_civicrm_nscd_fid();
     self::$version = _iats_civicrm_domain_info('version');
     self::$financial_types = self::$version[0] <= 4 && self::$version[1] <= 2 ? array() : CRM_Contribute_PseudoConstant::financialType();
     if (self::$version[0] <= 4 && self::$version[1] < 4) {
         self::$prefixes = CRM_Core_PseudoConstant::individualPrefix();
         self::$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     } else {
         self::$prefixes = CRM_Contact_BAO_Contact::buildOptions('individual_prefix_id');
         self::$contributionStatus = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
     }
     $params = array('version' => 3, 'sequential' => 1, 'is_test' => 0, 'return.name' => 1);
     $result = civicrm_api('PaymentProcessor', 'get', $params);
     foreach ($result['values'] as $pp) {
         self::$processors[$pp['id']] = $pp['name'];
     }
     $this->_columns = array('civicrm_contact' => array('dao' => 'CRM_Contact_DAO_Contact', 'order_bys' => array('sort_name' => array('title' => ts("Last name, First name"))), 'fields' => array('first_name' => array('title' => ts('First Name')), 'last_name' => array('title' => ts('Last Name')), 'prefix_id' => array('title' => ts('Prefix')), 'sort_name' => array('title' => ts('Contact Name'), 'no_repeat' => TRUE, 'default' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE))), 'civicrm_email' => array('dao' => 'CRM_Core_DAO_Email', 'order_bys' => array('email' => array('title' => ts('Email'))), 'fields' => array('email' => array('title' => ts('Email'), 'no_repeat' => TRUE)), 'grouping' => 'contact-fields'), 'civicrm_phone' => array('dao' => 'CRM_Core_DAO_Phone', 'fields' => array('phone' => array('title' => ts('Phone'), 'no_repeat' => TRUE)), 'grouping' => 'contact-fields'), 'civicrm_contribution' => array('dao' => 'CRM_Contribute_DAO_Contribution', 'fields' => array('id' => array('title' => ts('Contribution ID(s)'), 'required' => TRUE, 'dbAlias' => "GROUP_CONCAT(contribution_civireport.id SEPARATOR ', ')"), 'total_amount' => array('title' => ts('Amount Contributed to date'), 'required' => TRUE, 'statistics' => array('sum' => ts("Total Amount contributed")))), 'filters' => array('total_amount' => array('title' => ts('Total Amount'), 'operatorType' => CRM_Report_Form::OP_FLOAT, 'type' => CRM_Utils_Type::T_FLOAT))), 'civicrm_iats_customer_codes' => array('dao' => 'CRM_Contribute_DAO_Contribution', 'order_bys' => array('expiry' => array('title' => ts("Expiry Date"))), 'fields' => array('customer_code' => array('title' => 'customer code', 'default' => TRUE), 'expiry' => array('title' => 'Expiry Date', 'default' => TRUE))), 'civicrm_contribution_recur' => array('dao' => 'CRM_Contribute_DAO_ContributionRecur', 'order_bys' => array('id' => array('title' => ts("Series ID")), 'amount' => array('title' => ts("Current Amount")), 'start_date' => array('title' => ts('Start Date')), 'modified_date' => array('title' => ts('Modified Date')), self::$nscd_fid => array('title' => ts('Next Scheduled Contribution Date')), 'cycle_day' => array('title' => ts('Cycle Day')), 'payment_processor_id' => array('title' => ts('Payment Processor'))), 'fields' => array('id' => array('required' => TRUE, 'title' => ts("Series ID")), 'recur_id' => array('name' => 'id', 'title' => ts('Series ID')), 'invoice_id' => array('title' => ts('Invoice ID'), 'default' => FALSE), 'currency' => array('title' => ts("Currency")), 'amount' => array('title' => ts('Amount'), 'default' => TRUE), 'contribution_status_id' => array('title' => ts('Donation Status')), 'frequency_interval' => array('title' => ts('Frequency interval'), 'default' => TRUE), 'frequency_unit' => array('title' => ts('Frequency unit'), 'default' => TRUE), 'installments' => array('title' => ts('Installments'), 'default' => TRUE), 'start_date' => array('title' => ts('Start Date'), 'default' => TRUE), 'create_date' => array('title' => ts('Create Date')), 'modified_date' => array('title' => ts('Modified Date')), 'cancel_date' => array('title' => ts('Cancel Date')), self::$nscd_fid => array('title' => ts('Next Scheduled Contribution Date'), 'default' => TRUE), 'next_scheduled_day' => array('name' => self::$nscd_fid, 'dbAlias' => 'DAYOFMONTH(contribution_recur_civireport.next_sched_contribution)', 'title' => ts('Next Scheduled Day of the Month')), 'cycle_day' => array('title' => ts('Cycle Day')), 'failure_count' => array('title' => ts('Failure Count')), 'failure_retry_date' => array('title' => ts('Failure Retry Date')), 'payment_processor_id' => array('title' => ts('Payment Processor'), 'default' => TRUE)), 'filters' => array('contribution_status_id' => array('title' => ts('Donation Status'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => self::$contributionStatus, 'default' => array(5), 'type' => CRM_Utils_Type::T_INT), 'payment_processor_id' => array('title' => ts('Payment Processor'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => self::$processors, 'type' => CRM_Utils_Type::T_INT), 'currency' => array('title' => 'Currency', 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_OptionGroup::values('currencies_enabled'), 'default' => NULL, 'type' => CRM_Utils_Type::T_STRING), 'financial_type_id' => array('title' => ts('Financial Type'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => self::$financial_types, 'type' => CRM_Utils_Type::T_INT), 'frequency_unit' => array('title' => ts('Frequency Unit'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_OptionGroup::values('recur_frequency_units')), self::$nscd_fid => array('title' => ts('Next Scheduled Contribution Date'), 'operatorType' => CRM_Report_Form::OP_DATE, 'type' => CRM_Utils_Type::T_DATE), 'next_scheduled_day' => array('title' => ts('Next Scheduled Day'), 'operatorType' => CRM_Report_Form::OP_INT, 'type' => CRM_Utils_Type::T_INT), 'cycle_day' => array('title' => ts('Cycle Day'), 'operatorType' => CRM_Report_Form::OP_INT, 'type' => CRM_Utils_Type::T_INT), 'start_date' => array('title' => ts('Start Date'), 'operatorType' => CRM_Report_Form::OP_DATE, 'type' => CRM_Utils_Type::T_DATE), 'modified_date' => array('title' => ts('Modified Date'), 'operatorType' => CRM_Report_Form::OP_DATE, 'type' => CRM_Utils_Type::T_DATE), 'cancel_date' => array('title' => ts('Cancel Date'), 'operatorType' => CRM_Report_Form::OP_DATE, 'type' => CRM_Utils_Type::T_DATE))), 'civicrm_address' => array('dao' => 'CRM_Core_DAO_Address', 'fields' => array('street_address' => array('title' => ts('Address'), 'default' => FALSE), 'supplemental_address_1' => array('title' => ts('Supplementary Address Field 1'), 'default' => FALSE), 'supplemental_address_2' => array('title' => ts('Supplementary Address Field 2'), 'default' => FALSE), 'city' => array('title' => 'City', 'default' => FALSE), 'state_province_id' => array('title' => 'Province', 'default' => FALSE, 'alter_display' => 'alterStateProvinceID'), 'postal_code' => array('title' => 'Postal Code', 'default' => FALSE), 'country_id' => array('title' => 'Country', 'default' => FALSE, 'alter_display' => 'alterCountryID')), 'grouping' => 'contact-fields'));
     if (empty(self::$financial_types)) {
         unset($this->_columns['civicrm_contribution_recur']['filters']['financial_type_id']);
     }
     parent::__construct();
 }
Exemplo n.º 4
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     //load form for child blocks
     if ($this->_addBlockName) {
         $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName;
         return $className::buildQuickForm($this);
     }
     if ($this->_action == CRM_Core_Action::UPDATE) {
         $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
         $deleteURL = array(CRM_Core_Action::DELETE => array('name' => ts('Delete Contact Image'), 'url' => 'civicrm/contact/image', 'qs' => 'reset=1&cid=%%id%%&action=delete', 'extra' => 'onclick = "' . htmlspecialchars("if (confirm({$deleteExtra})) this.href+='&confirmed=1'; else return false;") . '"'));
         $deleteURL = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, array('id' => $this->_contactId), ts('more'), FALSE, 'contact.image.delete', 'Contact', $this->_contactId);
         $this->assign('deleteURL', $deleteURL);
     }
     //build contact type specific fields
     $className = 'CRM_Contact_Form_Edit_' . $this->_contactType;
     $className::buildQuickForm($this);
     // build Custom data if Custom data present in edit option
     $buildCustomData = 'noCustomDataPresent';
     if (array_key_exists('CustomData', $this->_editOptions)) {
         $buildCustomData = "customDataPresent";
     }
     // subtype is a common field. lets keep it here
     $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType));
     if (!empty($subtypes)) {
         $this->addField('contact_sub_type', array('label' => ts('Contact Type'), 'options' => $subtypes, 'class' => $buildCustomData, 'multiple' => 'multiple', 'options-url' => FALSE));
     }
     // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
     foreach ($this->_editOptions as $name => $label) {
         if ($name == 'Address') {
             $this->_blocks['Address'] = $this->_editOptions['Address'];
             continue;
         }
         if ($name == 'TagsAndGroups') {
             continue;
         }
         $className = 'CRM_Contact_Form_Edit_' . $name;
         $className::buildQuickForm($this);
     }
     // build tags and groups
     CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups::ALL, FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
     // build location blocks.
     CRM_Contact_Form_Edit_Lock::buildQuickForm($this);
     CRM_Contact_Form_Location::buildQuickForm($this);
     // add attachment
     $this->addField('image_URL', array('maxlength' => '60', 'label' => ts('Browse/Upload Image')));
     // add the dedupe button
     $this->addElement('submit', $this->_dedupeButtonName, ts('Check for Matching Contact(s)'));
     $this->addElement('submit', $this->_duplicateButtonName, ts('Save Matching Contact'));
     $this->addElement('submit', $this->getButtonName('next', 'sharedHouseholdDuplicate'), ts('Save With Duplicate Household'));
     $buttons = array(array('type' => 'upload', 'name' => ts('Save'), 'subName' => 'view', 'isDefault' => TRUE));
     if (CRM_Core_Permission::check('add contacts')) {
         $buttons[] = array('type' => 'upload', 'name' => ts('Save and New'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'subName' => 'new');
     }
     $buttons[] = array('type' => 'cancel', 'name' => ts('Cancel'));
     if (!empty($this->_values['contact_sub_type'])) {
         $this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($this->_values['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR));
     }
     $this->assign('oldSubtypes', json_encode($this->_oldSubtypes));
     $this->addButtons($buttons);
 }
 /**
  * Set default values for the form.
  *
  * @param CRM_Core_Form $form
  * @param array $defaults
  */
 public static function setDefaultValues(&$form, &$defaults)
 {
     if (!empty($defaults['preferred_language'])) {
         $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
         $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages);
     }
     // CRM-7119: set preferred_language to default if unset
     if (empty($defaults['preferred_language'])) {
         $config = CRM_Core_Config::singleton();
         $defaults['preferred_language'] = $config->lcMessages;
     }
     if (empty($defaults['communication_style_id'])) {
         $defaults['communication_style_id'] = array_pop(CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1'));
     }
     // CRM-17778 -- set preferred_mail_format to default if unset
     if (empty($defaults['preferred_mail_format'])) {
         $defaults['preferred_mail_format'] = 'Both';
     } else {
         $defaults['preferred_mail_format'] = array_search($defaults['preferred_mail_format'], CRM_Core_SelectValues::pmf());
     }
     //set default from greeting types CRM-4575, CRM-9739
     if ($form->_action & CRM_Core_Action::ADD) {
         foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
             if (empty($defaults[$greeting . '_id'])) {
                 if ($defaultGreetingTypeId = CRM_Contact_BAO_Contact_Utils::defaultGreeting($form->_contactType, $greeting)) {
                     $defaults[$greeting . '_id'] = $defaultGreetingTypeId;
                 }
             }
         }
     } else {
         foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
             $name = "{$greeting}_display";
             $form->assign($name, CRM_Utils_Array::value($name, $defaults));
         }
     }
 }
Exemplo n.º 6
0
 /**
  * Ensure hook_civicrm_fieldOptions is working
  */
 public function testHookFieldOptions()
 {
     CRM_Core_PseudoConstant::flush();
     // Test replacing all options with a hook
     $this->targetField = 'case_type_id';
     $this->replaceOptions = array('foo' => 'Foo', 'bar' => 'Bar');
     $result = $this->callAPISuccess('case', 'getoptions', array('field' => 'case_type_id'));
     $this->assertEquals($result['values'], $this->replaceOptions);
     // TargetField doesn't match - should get unmodified option list
     $originalGender = CRM_Contact_BAO_Contact::buildOptions('gender_id');
     $this->assertNotEquals($originalGender, $this->replaceOptions);
     // This time we should get foo bar appended to the list
     $this->targetField = 'gender_id';
     $this->appendOptions = array('foo' => 'Foo', 'bar' => 'Bar');
     $this->replaceOptions = NULL;
     CRM_Core_PseudoConstant::flush();
     $result = CRM_Contact_BAO_Contact::buildOptions('gender_id');
     $this->assertEquals($result, $originalGender + $this->appendOptions);
 }
Exemplo n.º 7
0
 /**
  * Add profile field to a form.
  *
  * @param CRM_Core_Form $form
  * @param array $field
  *   Properties.
  * @param int $mode
  *   Profile mode.
  * @param int $contactId
  * @param bool $online
  * @param string $usedFor
  *   For building up prefixed fieldname for special cases (e.g. onBehalf, Honor).
  * @param int $rowNumber
  * @param string $prefix
  *
  * @return null
  */
 public static function buildProfile(&$form, &$field, $mode, $contactId = NULL, $online = FALSE, $usedFor = NULL, $rowNumber = NULL, $prefix = '')
 {
     $defaultValues = array();
     $fieldName = $field['name'];
     $title = $field['title'];
     $attributes = $field['attributes'];
     $rule = $field['rule'];
     $view = $field['is_view'];
     $required = $mode == CRM_Profile_Form::MODE_SEARCH ? FALSE : $field['is_required'];
     $search = $mode == CRM_Profile_Form::MODE_SEARCH ? TRUE : FALSE;
     $isShared = CRM_Utils_Array::value('is_shared', $field, 0);
     // do not display view fields in drupal registration form
     // CRM-4632
     if ($view && $mode == CRM_Profile_Form::MODE_REGISTER) {
         return NULL;
     }
     if ($usedFor == 'onbehalf') {
         $name = "onbehalf[{$fieldName}]";
     } elseif ($usedFor == 'honor') {
         $name = "honor[{$fieldName}]";
     } elseif ($contactId && !$online) {
         $name = "field[{$contactId}][{$fieldName}]";
     } elseif ($rowNumber) {
         $name = "field[{$rowNumber}][{$fieldName}]";
     } elseif (!empty($prefix)) {
         $name = $prefix . "[{$fieldName}]";
     } else {
         $name = $fieldName;
     }
     $selectAttributes = array('class' => 'crm-select2', 'placeholder' => TRUE);
     if ($fieldName == 'image_URL' && $mode == CRM_Profile_Form::MODE_EDIT) {
         $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
         $deleteURL = array(CRM_Core_Action::DELETE => array('name' => ts('Delete Contact Image'), 'url' => 'civicrm/contact/image', 'qs' => 'reset=1&id=%%id%%&gid=%%gid%%&action=delete', 'extra' => 'onclick = "' . htmlspecialchars("if (confirm({$deleteExtra})) this.href+='&confirmed=1'; else return false;") . '"'));
         $deleteURL = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, array('id' => $form->get('id'), 'gid' => $form->get('gid')), ts('more'), FALSE, 'contact.profileimage.delete', 'Contact', $form->get('id'));
         $form->assign('deleteURL', $deleteURL);
     }
     $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options', TRUE, NULL, TRUE);
     if (substr($fieldName, 0, 14) === 'state_province') {
         $form->addChainSelect($name, array('label' => $title, 'required' => $required));
         $config = CRM_Core_Config::singleton();
         if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactStateProvince) {
             $defaultValues[$name] = $config->defaultContactStateProvince;
             $form->setDefaults($defaultValues);
         }
     } elseif (substr($fieldName, 0, 7) === 'country') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), $required, $selectAttributes);
         $config = CRM_Core_Config::singleton();
         if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactCountry) {
             $defaultValues[$name] = $config->defaultContactCountry;
             $form->setDefaults($defaultValues);
         }
     } elseif (substr($fieldName, 0, 6) === 'county') {
         if ($addressOptions['county']) {
             $form->addChainSelect($name, array('label' => $title, 'required' => $required));
         }
     } elseif (substr($fieldName, 0, 9) === 'image_URL') {
         $form->add('file', $name, $title, $attributes, $required);
         $form->addUploadElement($name);
     } elseif (substr($fieldName, 0, 2) === 'im') {
         $form->add('text', $name, $title, $attributes, $required);
         if (!$contactId) {
             if ($usedFor) {
                 if (substr($name, -1) == ']') {
                     $providerName = substr($name, 0, -1) . '-provider_id]';
                 }
                 $form->add('select', $providerName, NULL, array('' => ts('- select -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required);
             } else {
                 $form->add('select', $name . '-provider_id', $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required);
             }
             if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) {
                 $form->freeze($name . '-provider_id');
             }
         }
     } elseif ($fieldName === 'birth_date' || $fieldName === 'deceased_date') {
         $form->addDate($name, $title, $required, array('formatType' => 'birth'));
     } elseif (in_array($fieldName, array('membership_start_date', 'membership_end_date', 'join_date'))) {
         $form->addDate($name, $title, $required, array('formatType' => 'activityDate'));
     } elseif (CRM_Utils_Array::value('name', $field) == 'membership_type') {
         list($orgInfo, $types) = CRM_Member_BAO_MembershipType::getMembershipTypeInfo();
         $sel =& $form->addElement('hierselect', $name, $title);
         $select = array('' => ts('- select -'));
         if (count($orgInfo) == 1 && $field['is_required']) {
             // we only have one org - so we should default to it. Not sure about defaulting to first type
             // as it could be missed - so adding a select
             // however, possibly that is more similar to the membership form
             if (count($types[1]) > 1) {
                 $types[1] = $select + $types[1];
             }
         } else {
             $orgInfo = $select + $orgInfo;
         }
         $sel->setOptions(array($orgInfo, $types));
     } elseif (CRM_Utils_Array::value('name', $field) == 'membership_status') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'), $required);
     } elseif (in_array($fieldName, array('gender_id', 'communication_style_id'))) {
         $options = array();
         $pseudoValues = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', $fieldName);
         foreach ($pseudoValues as $key => $var) {
             $options[$key] = $form->createElement('radio', NULL, ts($title), $var, $key);
         }
         $group = $form->addGroup($options, $name, $title);
         if ($required) {
             $form->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
         } else {
             $group->setAttribute('allowClear', TRUE);
         }
     } elseif ($fieldName === 'prefix_id' || $fieldName === 'suffix_id') {
         $form->addSelect($name, array('label' => $title, 'entity' => 'contact', 'field' => $fieldName, 'class' => 'six', 'placeholder' => ''), $required);
     } elseif ($fieldName === 'contact_sub_type') {
         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field);
         if ($usedFor == 'onbehalf') {
             $profileType = 'Organization';
         } elseif ($usedFor == 'honor') {
             $profileType = CRM_Core_BAO_UFField::getProfileType($form->_params['honoree_profile_id']);
         } else {
             $profileType = $gId ? CRM_Core_BAO_UFField::getProfileType($gId) : NULL;
             if ($profileType == 'Contact') {
                 $profileType = 'Individual';
             }
         }
         $setSubtype = FALSE;
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $setSubtype = $profileType;
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : array();
         if ($setSubtype) {
             $subtypeList = array();
             $subtypeList[$setSubtype] = $subtypes[$setSubtype];
         } else {
             $subtypeList = $subtypes;
         }
         $form->add('select', $name, $title, $subtypeList, $required, array('class' => 'crm-select2', 'multiple' => TRUE));
     } elseif (in_array($fieldName, CRM_Contact_BAO_Contact::$_greetingTypes)) {
         //add email greeting, postal greeting, addressee, CRM-4575
         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field);
         $profileType = CRM_Core_BAO_UFField::getProfileType($gId, TRUE, FALSE, TRUE);
         if (empty($profileType) || in_array($profileType, array('Contact', 'Contribution', 'Participant', 'Membership'))) {
             $profileType = 'Individual';
         }
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         $greeting = array('contact_type' => $profileType, 'greeting_type' => $fieldName);
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($greeting), $required);
         // add custom greeting element
         $form->add('text', $fieldName . '_custom', ts('Custom %1', array(1 => ucwords(str_replace('_', ' ', $fieldName)))), NULL, FALSE);
     } elseif ($fieldName === 'preferred_communication_method') {
         $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
         foreach ($communicationFields as $key => $var) {
             if ($key == '') {
                 continue;
             }
             $communicationOptions[] = $form->createElement('checkbox', $key, NULL, $var);
         }
         $form->addGroup($communicationOptions, $name, $title, '<br/>');
     } elseif ($fieldName === 'preferred_mail_format') {
         $form->add('select', $name, $title, CRM_Core_SelectValues::pmf());
     } elseif ($fieldName === 'preferred_language') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contact_BAO_Contact::buildOptions('preferred_language'));
     } elseif ($fieldName == 'external_identifier') {
         $form->add('text', $name, $title, $attributes, $required);
         $contID = $contactId;
         if (!$contID) {
             $contID = $form->get('id');
         }
         $form->addRule($name, ts('External ID already exists in Database.'), 'objectExists', array('CRM_Contact_DAO_Contact', $contID, 'external_identifier'));
     } elseif ($fieldName === 'group') {
         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, TRUE, $required, $title, NULL, $name);
     } elseif ($fieldName === 'tag') {
         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::TAG, FALSE, $required, NULL, $title, $name);
     } elseif (substr($fieldName, 0, 4) === 'url-') {
         $form->add('text', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Website', 'url'), $required);
         $form->addRule($name, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'url');
     } elseif (substr($fieldName, -4) == 'note') {
         $form->add('textarea', $name, $title, $attributes, $required);
     } elseif (substr($fieldName, 0, 6) === 'custom') {
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName);
         if ($customFieldID) {
             CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, FALSE, $required, $search, $title);
         }
     } elseif (substr($fieldName, 0, 14) === 'address_custom') {
         list($fName, $locTypeId) = CRM_Utils_System::explode('-', $fieldName, 2);
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID(substr($fName, 8));
         if ($customFieldID) {
             CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, FALSE, $required, $search, $title);
         }
     } elseif (in_array($fieldName, array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date'))) {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'send_receipt') {
         $form->addElement('checkbox', $name, $title);
     } elseif ($fieldName == 'soft_credit') {
         $form->addEntityRef("soft_credit_contact_id[{$rowNumber}]", ts('Soft Credit To'), array('create' => TRUE));
         $form->addMoney("soft_credit_amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE);
     } elseif ($fieldName == 'product_name') {
         list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
         $sel =& $form->addElement('hierselect', $name, $title);
         $products = array('0' => ts('- select -')) + $products;
         $sel->setOptions(array($products, $options));
     } elseif ($fieldName == 'payment_instrument') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), $required);
     } elseif ($fieldName == 'financial_type') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), $required);
     } elseif ($fieldName == 'contribution_status_id') {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus();
         $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         foreach (array('In Progress', 'Overdue', 'Refunded') as $suppress) {
             unset($contributionStatuses[CRM_Utils_Array::key($suppress, $statusName)]);
         }
         $form->add('select', $name, $title, array('' => ts('- select -')) + $contributionStatuses, $required);
     } elseif ($fieldName == 'soft_credit_type') {
         $name = "soft_credit_type[{$rowNumber}]";
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_OptionGroup::values("soft_credit_type"));
         //CRM-15350: choose SCT field default value as 'Gift' for membership use
         //else (for contribution), use configured SCT default value
         $SCTDefaultValue = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
         if ($field['field_type'] == 'Membership') {
             $SCTDefaultValue = CRM_Core_OptionGroup::getValue('soft_credit_type', 'Gift', 'name');
         }
         $form->addElement('hidden', 'sct_default_id', $SCTDefaultValue, array('id' => 'sct_default_id'));
     } elseif ($fieldName == 'currency') {
         $form->addCurrency($name, $title, $required);
     } elseif ($fieldName == 'contribution_page_id') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionPage(), $required, 'class="big"');
     } elseif ($fieldName == 'participant_register_date') {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'activity_status_id') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::activityStatus(), $required);
     } elseif ($fieldName == 'activity_engagement_level') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Campaign_PseudoConstant::engagementLevel(), $required);
     } elseif ($fieldName == 'activity_date_time') {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'participant_status') {
         $cond = NULL;
         if ($online == TRUE) {
             $cond = 'visibility_id = 1';
         }
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantStatus(NULL, $cond, 'label'), $required);
     } elseif ($fieldName == 'participant_role') {
         if (!empty($field['is_multiple'])) {
             $form->addCheckBox($name, $title, CRM_Event_PseudoConstant::participantRole(), NULL, NULL, NULL, NULL, '&nbsp', TRUE);
         } else {
             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantRole(), $required);
         }
     } elseif ($fieldName == 'world_region') {
         $form->add('select', $name, $title, CRM_Core_PseudoConstant::worldRegion(), $required, $selectAttributes);
     } elseif ($fieldName == 'signature_html') {
         $form->add('wysiwyg', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', $fieldName));
     } elseif ($fieldName == 'signature_text') {
         $form->add('textarea', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', $fieldName));
     } elseif (substr($fieldName, -11) == 'campaign_id') {
         if (CRM_Campaign_BAO_Campaign::isCampaignEnable()) {
             $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(CRM_Utils_Array::value($contactId, $form->_componentCampaigns));
             $form->add('select', $name, $title, array('' => ts('- select -')) + $campaigns, $required, 'class="crm-select2 big"');
         }
     } elseif ($fieldName == 'activity_details') {
         $form->add('wysiwyg', $fieldName, $title, array('rows' => 4, 'cols' => 60), $required);
     } elseif ($fieldName == 'activity_duration') {
         $form->add('text', $name, $title, $attributes, $required);
         $form->addRule($name, ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger');
     } else {
         if (substr($fieldName, 0, 3) === 'is_' or substr($fieldName, 0, 7) === 'do_not_') {
             $form->add('advcheckbox', $name, $title, $attributes, $required);
         } else {
             $form->add('text', $name, $title, $attributes, $required);
         }
     }
     static $hiddenSubtype = FALSE;
     if (!$hiddenSubtype && CRM_Contact_BAO_ContactType::isaSubType($field['field_type'])) {
         // In registration mode params are submitted via POST and we don't have any clue
         // about profile-id or the profile-type (which could be a subtype)
         // To generalize the  behavior and simplify the process,
         // lets always add the hidden
         //subtype value if there is any, and we won't have to
         // compute it while processing.
         if ($usedFor) {
             $form->addElement('hidden', $usedFor . '[contact_sub_type]', $field['field_type']);
         } else {
             $form->addElement('hidden', 'contact_sub_type_hidden', $field['field_type']);
         }
         $hiddenSubtype = TRUE;
     }
     if ($view && $mode != CRM_Profile_Form::MODE_SEARCH || $isShared) {
         $form->freeze($name);
     }
     //add the rules
     if (in_array($fieldName, array('non_deductible_amount', 'total_amount', 'fee_amount', 'net_amount'))) {
         $form->addRule($name, ts('Please enter a valid amount.'), 'money');
     }
     if ($rule) {
         if (!($rule == 'email' && $mode == CRM_Profile_Form::MODE_SEARCH)) {
             $form->addRule($name, ts('Please enter a valid %1', array(1 => $title)), $rule);
         }
     }
 }
Exemplo n.º 8
0
 /**
  * Return languages available in this instance of CiviCRM.
  *
  * @param bool $justEnabled
  *   whether to return all languages or just the enabled ones.
  *
  * @return array
  *   Array of code/language name mappings
  */
 public static function languages($justEnabled = FALSE)
 {
     static $all = NULL;
     static $enabled = NULL;
     if (!$all) {
         $all = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
         // check which ones are available; add them to $all if not there already
         $codes = array();
         if (is_dir(CRM_Core_I18n::getResourceDir()) && ($dir = opendir(CRM_Core_I18n::getResourceDir()))) {
             while ($filename = readdir($dir)) {
                 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
                     $codes[] = $filename;
                     if (!isset($all[$filename])) {
                         $all[$filename] = $filename;
                     }
                 }
             }
             closedir($dir);
         }
         // drop the unavailable languages (except en_US)
         foreach (array_keys($all) as $code) {
             if ($code == 'en_US') {
                 continue;
             }
             if (!in_array($code, $codes)) {
                 unset($all[$code]);
             }
         }
     }
     if ($enabled === NULL) {
         $config = CRM_Core_Config::singleton();
         $enabled = array();
         if (isset($config->languageLimit) and $config->languageLimit) {
             foreach ($all as $code => $name) {
                 if (in_array($code, array_keys($config->languageLimit))) {
                     $enabled[$code] = $name;
                 }
             }
         }
     }
     return $justEnabled ? $enabled : $all;
 }
Exemplo n.º 9
0
 /**
  * @param $table
  *
  * @return array
  */
 public function titlesAndValuesForTable($table)
 {
     // static caches for subsequent calls with the same $table
     static $titles = array();
     static $values = array();
     // FIXME: split off the table → DAO mapping to a GenCode-generated class
     static $daos = array('civicrm_address' => 'CRM_Core_DAO_Address', 'civicrm_contact' => 'CRM_Contact_DAO_Contact', 'civicrm_email' => 'CRM_Core_DAO_Email', 'civicrm_im' => 'CRM_Core_DAO_IM', 'civicrm_openid' => 'CRM_Core_DAO_OpenID', 'civicrm_phone' => 'CRM_Core_DAO_Phone', 'civicrm_website' => 'CRM_Core_DAO_Website', 'civicrm_contribution' => 'CRM_Contribute_DAO_Contribution', 'civicrm_note' => 'CRM_Core_DAO_Note', 'civicrm_relationship' => 'CRM_Contact_DAO_Relationship', 'civicrm_activity' => 'CRM_Activity_DAO_Activity', 'civicrm_case' => 'CRM_Case_DAO_Case');
     if (!isset($titles[$table]) or !isset($values[$table])) {
         if (in_array($table, array_keys($daos))) {
             // FIXME: these should be populated with pseudo constants as they
             // were at the time of logging rather than their current values
             // FIXME: Use *_BAO:buildOptions() method rather than pseudoconstants & fetch programmatically
             $values[$table] = array('contribution_page_id' => CRM_Contribute_PseudoConstant::contributionPage(), 'contribution_status_id' => CRM_Contribute_PseudoConstant::contributionStatus(), 'financial_type_id' => CRM_Contribute_PseudoConstant::financialType(), 'country_id' => CRM_Core_PseudoConstant::country(), 'gender_id' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), 'location_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), 'payment_instrument_id' => CRM_Contribute_PseudoConstant::paymentInstrument(), 'phone_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'), 'preferred_communication_method' => CRM_Contact_BAO_Contact::buildOptions('preferred_communication_method'), 'preferred_language' => CRM_Contact_BAO_Contact::buildOptions('preferred_language'), 'prefix_id' => CRM_Contact_BAO_Contact::buildOptions('prefix_id'), 'provider_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), 'state_province_id' => CRM_Core_PseudoConstant::stateProvince(), 'suffix_id' => CRM_Contact_BAO_Contact::buildOptions('suffix_id'), 'website_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'), 'activity_type_id' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE), 'case_type_id' => CRM_Case_PseudoConstant::caseType('title', FALSE), 'priority_id' => CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'));
             // for columns that appear in more than 1 table
             switch ($table) {
                 case 'civicrm_case':
                     $values[$table]['status_id'] = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
                     break;
                 case 'civicrm_activity':
                     $values[$table]['status_id'] = CRM_Core_PseudoConstant::activityStatus();
                     break;
             }
             $dao = new $daos[$table]();
             foreach ($dao->fields() as $field) {
                 $titles[$table][$field['name']] = CRM_Utils_Array::value('title', $field);
                 if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
                     $values[$table][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
                 }
             }
         } elseif (substr($table, 0, 14) == 'civicrm_value_') {
             list($titles[$table], $values[$table]) = $this->titlesAndValuesForCustomDataTable($table);
         } else {
             $titles[$table] = $values[$table] = array();
         }
     }
     return array($titles[$table], $values[$table]);
 }
Exemplo n.º 10
0
 /**
  * @param $value
  * @param $row
  * @param $selectedfield
  * @param $criteriaFieldName
  *
  * @return mixed
  */
 function alterGenderID($value, &$row, $selectedfield, $criteriaFieldName) {
   $values = CRM_Contact_BAO_Contact::buildOptions('gender_id');
   return $values[$value];
 }
Exemplo n.º 11
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.
  *
  * @param bool $doGeocodeAddress
  *
  * @return bool
  *   the result of this processing
  */
 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) {
         $contactFields = CRM_Contact_DAO_Contact::import();
     }
     //check if external identifier exists in database
     if (!empty($params['external_identifier']) && (!empty($params['id']) || in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_SKIP, CRM_Import_Parser::DUPLICATE_NOCHECK)))) {
         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 ID 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::DUPLICATE;
             }
         }
     }
     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 && empty($params['id']) && !empty($params['external_identifier'])) {
         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 (empty($params['id']) && !empty($params['external_identifier'])) {
             if ($cid) {
                 $params['id'] = $cid;
             }
         }
         $error = _civicrm_api3_deprecated_duplicate_formatted_contact($formatted);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $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 (!empty($params['contact_sub_type'])) {
                                 $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 {
                                 $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 (!empty($params['id'])) {
                 $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 (!empty($params['contact_sub_type'])) {
                             $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->_dedupeRuleGroupID);
                             $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 (isset($newContact) && is_a($newContact, 'CRM_Contact_BAO_Contact')) {
             $relationship = TRUE;
         } elseif (is_a($error, 'CRM_Core_Error')) {
             $newContact = $error;
             $relationship = TRUE;
         }
     }
     //fixed CRM-4148
     //now we create new contact in update/fill mode also.
     $contactID = NULL;
     if ($createNewContact || $this->_retCode != CRM_Import_Parser::NO_MATCH && $this->_updateWithId) {
         //CRM-4430, don't carry if not submitted.
         foreach (array('prefix_id', 'suffix_id', 'gender_id') as $name) {
             if (!empty($formatted[$name])) {
                 $options = CRM_Contact_BAO_Contact::buildOptions($name, 'get');
                 if (!isset($options[$formatted[$name]])) {
                     $formatted[$name] = CRM_Utils_Array::key((string) $formatted[$name], $options);
                 }
             }
         }
         if ($this->_updateWithId && !empty($params['id'])) {
             $contactID = $params['id'];
         }
         $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactID, TRUE, $this->_dedupeRuleGroupID);
     }
     if (isset($newContact) && is_object($newContact) && $newContact instanceof CRM_Contact_BAO_Contact) {
         $relationship = TRUE;
         $newContact = clone $newContact;
         $contactID = $newContact->id;
         $this->_newContacts[] = $contactID;
         //get return code if we create new contact in update mode, CRM-4148
         if ($this->_updateWithId) {
             $this->_retCode = CRM_Import_Parser::VALID;
         }
     } elseif (isset($newContact) && CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
         // if duplicate, no need of further processing
         if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
             $errorMessage = "Skipping duplicate record";
             array_unshift($values, $errorMessage);
             $importRecordParams = array($statusFieldName => 'DUPLICATE', "{$statusFieldName}Msg" => $errorMessage);
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             return CRM_Import_Parser::DUPLICATE;
         }
         $relationship = TRUE;
         # see CRM-10433 - might return comma separate list of all dupes
         $dupeContactIDs = explode(',', $newContact['error_message']['params'][0]);
         $dupeCount = count($dupeContactIDs);
         $contactID = array_pop($dupeContactIDs);
         // check to see if we had more than one duplicate contact id.
         // if we have more than one, the record will be rejected below
         if ($dupeCount == 1) {
             // there was only one dupe, we will continue normally...
             if (!in_array($contactID, $this->_newContacts)) {
                 $this->_newContacts[] = $contactID;
             }
         }
     }
     if ($contactID) {
         // call import hook
         $currentImportID = end($values);
         $hookParams = array('contactID' => $contactID, 'importID' => $currentImportID, 'importTempTable' => $this->_tableName, 'fieldHeaders' => $this->_mapperKeys, 'fields' => $this->_activeFields);
         CRM_Utils_Hook::import('Contact', 'process', $this, $hookParams);
     }
     if ($relationship) {
         $primaryContactId = NULL;
         if (CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             if (CRM_Utils_Rule::integer($newContact['error_message']['params'][0])) {
                 $primaryContactId = $newContact['error_message']['params'][0];
             }
         } else {
             $primaryContactId = $newContact->id;
         }
         if ((CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT) || 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 (empty($params[$key]['id']) && !empty($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)) && !empty($params[$key]['id'])) {
                     $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 (!empty($formatting['contact_sub_type'])) {
                             $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.") . ' ' . ts("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);
                 //do we have enough fields to create related contact.
                 $allowToCreate = $this->checkRelatedContactFields($key, $formatting);
                 if (!$allowToCreate) {
                     $errorMessage = ts('Related contact required fields are missing.');
                     array_unshift($values, $errorMessage);
                     return CRM_Import_Parser::NO_MATCH;
                 }
                 //fixed for CRM-4148
                 if (!empty($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 (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
                         $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 (!empty($formatting['contact_sub_type'])) {
                         $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 (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
                     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 (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT) || $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::legacyCreateMultiple($relationParams, $relationIds);
                         if ($valid || $duplicate) {
                             $relationIds['contactTarget'] = $relContactId;
                             $action = $duplicate ? CRM_Core_Action::UPDATE : CRM_Core_Action::ADD;
                             CRM_Contact_BAO_Relationship::relatedMemberships($primaryContactId, $relationParams, $relationIds, $action);
                         }
                         //handle current employer, CRM-3532
                         if ($valid) {
                             $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;
                             } elseif ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') {
                                 $orgId = $primaryContactId;
                                 $individualId = $relContactId;
                             }
                             if ($orgId && $individualId) {
                                 $currentEmpParams[$individualId] = $orgId;
                                 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) {
                 civicrm_api('contact', 'delete', $vals);
                 $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, NULL, NULL, $formatted['contact_type']);
             } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
                 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
             } elseif ($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)) {
                 if (empty($newContact['error_message']['params'])) {
                     // different kind of error other than DUPLICATE
                     $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;
                 }
                 $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);
 }
Exemplo n.º 12
0
 /**
  * This function sets the default values for the form. Note that in edit/view mode
  * the default values are retrieved from the database
  *
  * @access public
  *
  * @return None
  */
 static function setDefaultValues(&$form, &$defaults)
 {
     if (!empty($defaults['preferred_language'])) {
         $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
         $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages);
     }
     // CRM-7119: set preferred_language to default if unset
     if (empty($defaults['preferred_language'])) {
         $config = CRM_Core_Config::singleton();
         $defaults['preferred_language'] = $config->lcMessages;
     }
     //set default from greeting types CRM-4575, CRM-9739
     if ($form->_action & CRM_Core_Action::ADD) {
         foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
             if (empty($defaults[$greeting . '_id'])) {
                 if ($defaultGreetingTypeId = CRM_Contact_BAO_Contact_Utils::defaultGreeting($form->_contactType, $greeting)) {
                     $defaults[$greeting . '_id'] = $defaultGreetingTypeId;
                 }
             }
         }
     } else {
         foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
             $name = "{$greeting}_display";
             $form->assign($name, CRM_Utils_Array::value($name, $defaults));
         }
     }
 }
 /**
  * wrapper for getOptions / pseudoconstant to get contact type options
  */
 function getContactTypeOptions()
 {
     if (method_exists('CRM_Contribute_PseudoConstant', 'contactType')) {
         return CRM_Contribute_PseudoConstant::contactType();
     } else {
         return CRM_Contact_BAO_Contact::buildOptions('contact_type');
     }
 }
Exemplo n.º 14
0
 static function basic(&$form)
 {
     $form->addElement('hidden', 'hidden_basic', 1);
     if ($form->_searchOptions['contactType']) {
         // add checkboxes for contact type
         $contact_type = array();
         $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements();
         if ($contactTypes) {
             $form->add('select', 'contact_type', ts('Contact Type(s)'), $contactTypes, FALSE, array('id' => 'contact_type', 'multiple' => 'multiple', 'title' => ts('- select -')));
         }
     }
     if ($form->_searchOptions['groups']) {
         // multiselect for groups
         if ($form->_group) {
             // Arrange groups into hierarchical listing (child groups follow their parents and have indentation spacing in title)
             $groupHierarchy = CRM_Contact_BAO_Group::getGroupsHierarchy($form->_group, NULL, '&nbsp;&nbsp;', TRUE);
             $form->add('select', 'group', ts('Groups'), $groupHierarchy, FALSE, array('id' => 'group', 'multiple' => 'multiple', 'title' => ts('- select -')));
             $groupOptions = CRM_Core_BAO_OptionValue::getOptionValuesAssocArrayFromName('group_type');
             $form->add('select', 'group_type', ts('Group Types'), $groupOptions, FALSE, array('id' => 'group_type', 'multiple' => 'multiple', 'title' => ts('- select -')));
             $form->add('hidden', 'group_search_selected', 'group');
         }
     }
     if ($form->_searchOptions['tags']) {
         // multiselect for categories
         $contactTags = CRM_Core_BAO_Tag::getTags();
         if ($contactTags) {
             $form->add('select', 'contact_tags', ts('Tags'), $contactTags, FALSE, array('id' => 'contact_tags', 'multiple' => 'multiple', 'title' => ts('- select -')));
         }
         $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_contact');
         CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_contact', NULL, TRUE, FALSE, TRUE);
         $used_for = CRM_Core_OptionGroup::values('tag_used_for');
         $tagsTypes = array();
         $showAllTagTypes = false;
         foreach ($used_for as $key => $value) {
             //check tags for every type and find if there are any defined
             $tags = CRM_Core_BAO_Tag::getTagsUsedFor($key, FALSE, TRUE, NULL);
             // check if there are tags other than contact type, if no - keep checkbox hidden on adv search
             // we will hide searching contact by attachments tags until it will be implemented in core
             if (count($tags) && $key != 'civicrm_file' && $key != 'civicrm_contact') {
                 //if tags exists then add type to display in adv search form help text
                 $tagsTypes[] = ts($value);
                 $showAllTagTypes = true;
             }
         }
         $tagTypesText = implode(" or ", $tagsTypes);
         if ($showAllTagTypes) {
             $form->add('checkbox', 'all_tag_types', ts('Include tags used for %1', array(1 => $tagTypesText)));
             $form->add('hidden', 'tag_types_text', $tagTypesText);
         }
     }
     // add text box for last name, first name, street name, city
     $form->addElement('text', 'sort_name', ts('Find...'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     // add text box for last name, first name, street name, city
     $form->add('text', 'email', ts('Contact Email'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     //added contact source
     $form->add('text', 'contact_source', ts('Contact Source'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'contact_source'));
     //added job title
     $form->addElement('text', 'job_title', ts('Job Title'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'job_title'));
     //added internal ID
     $form->addElement('text', 'contact_id', ts('Contact ID'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'id'));
     $form->addRule('contact_id', ts('Please enter valid Contact ID'), 'positiveInteger');
     //added external ID
     $form->addElement('text', 'external_identifier', ts('External ID'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'external_identifier'));
     if (CRM_Core_Permission::check('access deleted contacts') and CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_undelete', NULL)) {
         $form->add('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
     }
     // add checkbox for cms users only
     $form->addYesNo('uf_user', ts('CMS User?'));
     // tag all search
     $form->add('text', 'tag_search', ts('All Tags'));
     // add search profiles
     // FIXME: This is probably a part of profiles - need to be
     // FIXME: eradicated from here when profiles are reworked.
     $types = array('Participant', 'Contribution', 'Membership');
     // get component profiles
     $componentProfiles = array();
     $componentProfiles = CRM_Core_BAO_UFGroup::getProfiles($types);
     $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('Search Profile', 1);
     $accessibleUfGroups = CRM_Core_Permission::ufGroup(CRM_Core_Permission::VIEW);
     $searchProfiles = array();
     foreach ($ufGroups as $key => $var) {
         if (!array_key_exists($key, $componentProfiles) && in_array($key, $accessibleUfGroups)) {
             $searchProfiles[$key] = $var['title'];
         }
     }
     $form->addElement('select', 'uf_group_id', ts('Search Views'), array('0' => ts('- default view -')) + $searchProfiles);
     $componentModes = CRM_Contact_Form_Search::getModeSelect();
     // unset contributions or participants if user does not have
     // permission on them
     if (!CRM_Core_Permission::access('CiviContribute')) {
         unset($componentModes['2']);
     }
     if (!CRM_Core_Permission::access('CiviEvent')) {
         unset($componentModes['3']);
     }
     if (!CRM_Core_Permission::access('CiviMember')) {
         unset($componentModes['5']);
     }
     if (!CRM_Core_Permission::check('view all activities')) {
         unset($componentModes['4']);
     }
     if (count($componentModes) > 1) {
         $form->addElement('select', 'component_mode', ts('Display Results As'), $componentModes);
     }
     $form->addElement('select', 'operator', ts('Search Operator'), array('AND' => ts('AND'), 'OR' => ts('OR')));
     // add the option to display relationships
     $rTypes = CRM_Core_PseudoConstant::relationshipType();
     $rSelect = array('' => ts('- Select Relationship Type-'));
     foreach ($rTypes as $rid => $rValue) {
         if ($rValue['label_a_b'] == $rValue['label_b_a']) {
             $rSelect[$rid] = $rValue['label_a_b'];
         } else {
             $rSelect["{$rid}_a_b"] = $rValue['label_a_b'];
             $rSelect["{$rid}_b_a"] = $rValue['label_b_a'];
         }
     }
     $form->addElement('select', 'display_relationship_type', ts('Display Results as Relationship'), $rSelect);
     // checkboxes for DO NOT phone, email, mail
     // we take labels from SelectValues
     $t = CRM_Core_SelectValues::privacy();
     $form->add('select', 'privacy_options', ts('Privacy'), $t, FALSE, array('id' => 'privacy_options', 'multiple' => 'multiple', 'title' => ts('- select -')));
     $form->addElement('select', 'privacy_operator', ts('Operator'), array('OR' => ts('OR'), 'AND' => ts('AND')));
     $options = array(1 => ts('Exclude'), 2 => ts('Include by Privacy Option(s)'));
     $form->addRadio('privacy_toggle', ts('Privacy Options'), $options);
     // preferred communication method
     $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
     $commPreff = array();
     foreach ($comm as $k => $v) {
         $commPreff[] = $form->createElement('advcheckbox', $k, NULL, $v);
     }
     $onHold[] = $form->createElement('advcheckbox', 'on_hold', NULL, ts(''));
     $form->addGroup($onHold, 'email_on_hold', ts('Email On Hold'));
     $form->addGroup($commPreff, 'preferred_communication_method', ts('Preferred Communication Method'));
     //CRM-6138 Preferred Language
     $form->add('select', 'preferred_language', ts('Preferred Language'), array('' => ts('- any -')) + CRM_Contact_BAO_Contact::buildOptions('preferred_language'));
     // Phone search
     $form->addElement('text', 'phone_numeric', ts('Phone Number'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone'));
     $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $phoneType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $form->add('select', 'phone_location_type_id', ts('Phone Location'), array('' => ts('- any -')) + $locationType);
     $form->add('select', 'phone_phone_type_id', ts('Phone Type'), array('' => ts('- any -')) + $phoneType);
 }