/**
  * build the form elements for a phone object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param int           $addressBlockCount block number to build
  * @param boolean       $blockEdit         is it block edit
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form, $addressBlockCount = NULL, $blockEdit = FALSE)
 {
     // passing this via the session is AWFUL. we need to fix this
     if (!$addressBlockCount) {
         $blockId = $form->get('Phone_Block_Count') ? $form->get('Phone_Block_Count') : 1;
     } else {
         $blockId = $addressBlockCount;
     }
     $form->applyFilter('__ALL__', 'trim');
     //phone type select
     $form->addElement('select', "phone[{$blockId}][phone_type_id]", ts('Phone'), CRM_Core_PseudoConstant::phoneType());
     //main phone number with crm_phone class
     $form->addElement('text', "phone[{$blockId}][phone]", ts('Phone'), array_merge(CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone'), array('class' => 'crm_phone twelve')));
     // phone extension
     $form->addElement('text', "phone[{$blockId}][phone_ext]", ts('Extension'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone_ext'));
     if (isset($form->_contactType) || $blockEdit) {
         //Block type select
         $form->addElement('select', "phone[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
         //is_Primary radio
         $js = array('id' => 'Phone_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
         $form->addElement('radio', "phone[{$blockId}][is_primary]", '', '', '1', $js);
     }
     // TODO: set this up as a group, we need a valid phone_type_id if we have a  phone number
     // $form->addRule( "location[$locationId][phone][$locationId][phone]", ts('Phone number is not valid.'), 'phone' );
 }
Example #2
0
 /**
  * build the form elements for an email object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param array         $location   the location object to store all the form elements in
  * @param int           $locationId the locationId we are dealing with
  * @param int           $count      the number of blocks to create
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form, $addressBlockCount = null)
 {
     // passing this via the session is AWFUL. we need to fix this
     if (!$addressBlockCount) {
         $blockId = $form->get('Email_Block_Count') ? $form->get('Email_Block_Count') : 1;
     } else {
         $blockId = $addressBlockCount;
     }
     $form->applyFilter('__ALL__', 'trim');
     //Email box
     $form->addElement('text', "email[{$blockId}][email]", ts('Email'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', 'email'));
     $form->addRule("email[{$blockId}][email]", ts('Email is not valid.'), 'email');
     if (isset($form->_contactType)) {
         //Block type
         $form->addElement('select', "email[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
         //On-hold checkbox
         $form->addElement('advcheckbox', "email[{$blockId}][on_hold]", null);
         //Bulkmail checkbox
         $js = array('id' => "Email_" . $blockId . "_IsBulkmail", 'onClick' => 'singleSelect( this.id );');
         $form->addElement('advcheckbox', "email[{$blockId}][is_bulkmail]", null, '', $js);
         //is_Primary radio
         $js = array('id' => "Email_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
         $form->addElement('radio', "email[{$blockId}][is_primary]", '', '', '1', $js);
         if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Contact') {
             $form->add('textarea', "email[{$blockId}][signature_text]", ts('Signature (Text)'), array('rows' => 2, 'cols' => 40));
             $form->addWysiwyg("email[{$blockId}][signature_html]", ts('Signature (HTML)'), array('rows' => 2, 'cols' => 40));
         }
     }
 }
Example #3
0
 /**
  * build form for address input fields 
  *
  * @param object $form - CRM_Core_Form (or subclass)
  * @param array reference $location - location array
  * @param int $locationId - location id whose block needs to be built.
  * @return none
  *
  * @access public
  * @static
  */
 static function buildQuickForm(&$form)
 {
     $blockId = $form->get('Address_Block_Count') ? $form->get('Address_Block_Count') : 1;
     $config =& CRM_Core_Config::singleton();
     $countryDefault = $config->defaultContactCountry;
     $form->applyFilter('__ALL__', 'trim');
     $js = array('onChange' => 'checkLocation( this.id );');
     $form->addElement('select', "address[{$blockId}][location_type_id]", ts('Location Type'), array('' => ts('- select -')) + CRM_Core_PseudoConstant::locationType(), $js);
     $js = array('id' => "Address_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
     $form->addElement('checkbox', "address[{$blockId}][is_primary]", ts('Primary location for this contact'), ts('Primary location for this contact'), $js);
     $js = array('id' => "Address_" . $blockId . "_IsBilling", 'onClick' => 'singleSelect( this.id );');
     $form->addElement('checkbox', "address[{$blockId}][is_billing]", ts('Billing location for this contact'), ts('Billing location for this contact'), $js);
     require_once 'CRM/Core/BAO/Preferences.php';
     $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true);
     $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Address');
     $elements = array('address_name' => array(ts('Address Name'), $attributes['address_name'], null), 'street_address' => array(ts('Street Address'), $attributes['street_address'], null), 'supplemental_address_1' => array(ts('Addt\'l Address 1'), $attributes['supplemental_address_1'], null), 'supplemental_address_2' => array(ts('Addt\'l Address 2'), $attributes['supplemental_address_2'], null), 'city' => array(ts('City'), $attributes['city'], null), 'postal_code' => array(ts('Zip / Postal Code'), $attributes['postal_code'], null), 'postal_code_suffix' => array(ts('Postal Code Suffix'), array('size' => 4, 'maxlength' => 12), null), 'county_id' => array(ts('County'), $attributes['county_id'], 'county'), 'state_province_id' => array(ts('State / Province'), $attributes['state_province_id'], null), 'country_id' => array(ts('Country'), $attributes['country_id'], null), 'geo_code_1' => array(ts('Latitude'), array('size' => 9, 'maxlength' => 10), null), 'geo_code_2' => array(ts('Longitude'), array('size' => 9, 'maxlength' => 10), null));
     $stateCountryMap = array();
     foreach ($elements as $name => $v) {
         list($title, $attributes, $select) = $v;
         $nameWithoutID = strpos($name, '_id') !== false ? substr($name, 0, -3) : $name;
         if (!CRM_Utils_Array::value($nameWithoutID, $addressOptions)) {
             continue;
         }
         if (!$attributes) {
             $attributes = $attributes[$name];
         }
         //build normal select if country is not present in address block
         if ($name == 'state_province_id' && !$addressOptions['country']) {
             $select = 'stateProvince';
         }
         if (!$select) {
             if ($name == 'country_id' || $name == 'state_province_id') {
                 if ($name == 'country_id') {
                     $stateCountryMap[$blockId]['country'] = "address_{$blockId}_{$name}";
                     $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country();
                 } else {
                     $stateCountryMap[$blockId]['state_province'] = "address_{$blockId}_{$name}";
                     if ($countryDefault) {
                         $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvinceForCountry($countryDefault);
                     } else {
                         $selectOptions = array('' => ts('- select a country -'));
                     }
                 }
                 $form->addElement('select', "address[{$blockId}][{$name}]", $title, $selectOptions);
             } else {
                 if ($name == 'address_name') {
                     $name = "name";
                 }
                 $form->addElement('text', "address[{$blockId}][{$name}]", $title, $attributes);
             }
         } else {
             $form->addElement('select', "address[{$blockId}][{$name}]", $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::$select());
         }
     }
     require_once 'CRM/Core/BAO/Address.php';
     CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap);
 }
Example #4
0
 /**
  * build the form elements for an IM object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param array         $location   the location object to store all the form elements in
  * @param int           $locationId the locationId we are dealing with
  * @param int           $count      the number of blocks to create
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form)
 {
     $blockId = $form->get('IM_Block_Count') ? $form->get('IM_Block_Count') : 1;
     $form->applyFilter('__ALL__', 'trim');
     //IM provider select
     $form->addElement('select', "im[{$blockId}][provider_id]", '', CRM_Core_PseudoConstant::IMProvider());
     //Block type select
     $form->addElement('select', "im[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
     //IM box
     $form->addElement('text', "im[{$blockId}][name]", ts('Instant Messenger'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_IM', 'name'));
     //is_Primary radio
     $js = array('id' => "IM_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
     $form->addElement('radio', "im[{$blockId}][is_primary]", '', '', '1', $js);
 }
Example #5
0
 /**
  * function to build location block
  *
  * @param object $form the object of the form (QF Object)
  * @param int $maxLocationBlocks no of location blocks
  *
  * @static 
  * @access public
  */
 function &buildLocationBlock(&$form, $maxLocationBlocks)
 {
     $location = array();
     for ($locationId = 1; $locationId <= $maxLocationBlocks; $locationId++) {
         $location[$locationId]['location_type_id'] = $form->addElement('select', "location[{$locationId}][location_type_id]", null, CRM_Core_PseudoConstant::locationType());
         $location[$locationId]['is_primary'] = $form->addElement('checkbox', "location[{$locationId}][is_primary]", ts('Primary location for this contact'), ts('Primary location for this contact'), array('onchange' => "location_is_primary_onclick('" . $form->getName() . "', {$locationId}, {$maxLocationBlocks});"));
         $location[$locationId]['name'] = $form->addElement('text', "location[{$locationId}][name]", ts('Location Name'), CRM_Core_PseudoConstant::locationType());
         CRM_Contact_Form_Address::buildAddressBlock($form, $location, $locationId);
         CRM_Contact_Form_Phone::buildPhoneBlock($form, $location, $locationId, CRM_CONTACT_FORM_LOCATION_BLOCKS);
         CRM_Contact_Form_Email::buildEmailBlock($form, $location, $locationId, CRM_CONTACT_FORM_LOCATION_BLOCKS);
         CRM_Contact_Form_IM::buildIMBlock($form, $location, $locationId, CRM_CONTACT_FORM_LOCATION_BLOCKS);
         CRM_Core_ShowHideBlocks::linksForArray($form, $locationId, $maxLocationBlocks, "location", '', '');
     }
     return $location;
 }
 /**
  * build the form elements for an email object
  *
  * @param CRM_Core_Form $form              reference to the form object
  * @param int           $addressBlockCount block number to build
  * @param boolean       $blockEdit         is it block edit
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form, $addressBlockCount = NULL, $blockEdit = FALSE)
 {
     // passing this via the session is AWFUL. we need to fix this
     if (!$addressBlockCount) {
         $blockId = $form->get('Email_Block_Count') ? $form->get('Email_Block_Count') : 1;
     } else {
         $blockId = $addressBlockCount;
     }
     $form->applyFilter('__ALL__', 'trim');
     //Email box
     $form->addElement('text', "email[{$blockId}][email]", ts('Email'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', 'email'));
     $form->addRule("email[{$blockId}][email]", ts('Email is not valid.'), 'email');
     if (isset($form->_contactType) || $blockEdit) {
         //Block type
         $form->addElement('select', "email[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
         $multipleBulk = CRM_Core_BAO_Email::isMultipleBulkMail();
         //On-hold select
         if ($multipleBulk) {
             $holdOptions = array(0 => ts('- select -'), 1 => ts('On Hold Bounce'), 2 => ts('On Hold Opt Out'));
             $form->addElement('select', "email[{$blockId}][on_hold]", '', $holdOptions);
         } else {
             $form->addElement('advcheckbox', "email[{$blockId}][on_hold]", NULL);
         }
         //Bulkmail checkbox
         $form->assign('multipleBulk', $multipleBulk);
         if ($multipleBulk) {
             $js = array('id' => "Email_" . $blockId . "_IsBulkmail");
             $form->addElement('advcheckbox', "email[{$blockId}][is_bulkmail]", NULL, '', $js);
         } else {
             $js = array('id' => "Email_" . $blockId . "_IsBulkmail");
             if (!$blockEdit) {
                 $js['onClick'] = 'singleSelect( this.id );';
             }
             $form->addElement('radio', "email[{$blockId}][is_bulkmail]", '', '', '1', $js);
         }
         //is_Primary radio
         $js = array('id' => "Email_" . $blockId . "_IsPrimary");
         if (!$blockEdit) {
             $js['onClick'] = 'singleSelect( this.id );';
         }
         $form->addElement('radio', "email[{$blockId}][is_primary]", '', '', '1', $js);
         if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Contact') {
             $form->add('textarea', "email[{$blockId}][signature_text]", ts('Signature (Text)'), array('rows' => 2, 'cols' => 40));
             $form->addWysiwyg("email[{$blockId}][signature_html]", ts('Signature (HTML)'), array('rows' => 2, 'cols' => 40));
         }
     }
 }
Example #7
0
 /**
  * build the form elements for an open id object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param array         $location   the location object to store all the form elements in
  * @param int           $locationId the locationId we are dealing with
  * @param int           $count      the number of blocks to create
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form)
 {
     $blockId = $form->get('OpenID_Block_Count') ? $form->get('OpenID_Block_Count') : 1;
     $form->applyFilter('__ALL__', 'trim');
     $form->addElement('text', "openid[{$blockId}][openid]", ts('OpenID'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OpenID', 'openid'));
     $form->addRule("openid[{$blockId}][openid]", ts('OpenID is not a valid URL.'), 'url');
     //Block type
     $form->addElement('select', "openid[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
     $config = CRM_Core_Config::singleton();
     if ($config->userFramework == 'Standalone') {
         $js = array('id' => "OpenID_" . $blockId . "_IsLogin", 'onClick' => 'singleSelect( this.id );');
         $form->addElement('advcheckbox', "openid[{$blockId}][allowed_to_login]", null, '', $js);
     }
     //is_Primary radio
     $js = array('id' => "OpenID_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
     $form->addElement('radio', "openid[{$blockId}][is_primary]", '', '', '1', $js);
 }
 public function preProcess()
 {
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     $this->_mode = 'live';
     $this->loadCart();
     $this->checkWaitingList();
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $this->_bltID = array_search('Billing', $locationTypes);
     $this->assign('bltID', $this->_bltID);
     $event_titles = array();
     foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
         $event_titles[] = $event_in_cart->event->title;
     }
     $this->description = ts("Online Registration for %1", array(1 => implode(", ", $event_titles)));
     if (!isset($this->discounts)) {
         $this->discounts = array();
     }
 }
Example #9
0
 /**
  * build the form elements for a phone object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param array         $location   the location object to store all the form elements in
  * @param int           $locationId the locationId we are dealing with
  * @param int           $count      the number of blocks to create
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form)
 {
     $blockId = $form->get('Phone_Block_Count') ? $form->get('Phone_Block_Count') : 1;
     $form->applyFilter('__ALL__', 'trim');
     //phone type select
     $form->addElement('select', "phone[{$blockId}][phone_type_id]", ts('Phone'), CRM_Core_PseudoConstant::phoneType());
     //phone box
     $form->addElement('text', "phone[{$blockId}][phone]", ts('Phone'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone'));
     if (isset($form->_contactType)) {
         //Block type select
         $form->addElement('select', "phone[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
         //is_Primary radio
         $js = array('id' => "Phone_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
         $form->addElement('radio', "phone[{$blockId}][is_primary]", '', '', '1', $js);
     }
     // TODO: set this up as a group, we need a valid phone_type_id if we have a  phone number
     // $form->addRule( "location[$locationId][phone][$locationId][phone]", ts('Phone number is not valid.'), 'phone' );
 }
Example #10
0
 /**
  * build the form elements for an email object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param array         $location   the location object to store all the form elements in
  * @param int           $locationId the locationId we are dealing with
  * @param int           $count      the number of blocks to create
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form)
 {
     $blockId = $form->get('Email_Block_Count') ? $form->get('Email_Block_Count') : 1;
     $form->applyFilter('__ALL__', 'trim');
     //Email box
     $form->addElement('text', "email[{$blockId}][email]", ts('Email'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', 'email'));
     $form->addRule("email[{$blockId}][email]", ts('Email is not valid.'), 'email');
     if (isset($form->_contactType)) {
         //Block type
         $form->addElement('select', "email[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
         //On-hold checkbox
         $form->addElement('advcheckbox', "email[{$blockId}][on_hold]", null);
         //Bulkmail checkbox
         $js = array('id' => "Email_" . $blockId . "_IsBulkmail", 'onClick' => 'singleSelect( this.id );');
         $form->addElement('advcheckbox', "email[{$blockId}][is_bulkmail]", null, '', $js);
         //is_Primary radio
         $js = array('id' => "Email_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
         $form->addElement('radio', "email[{$blockId}][is_primary]", '', '', '1', $js);
     }
 }
Example #11
0
 /**
  * Given a contact id and a field set, return the values from the db
  * for this contact
  *
  * @param int     $id             the contact id
  * @param array   $fields         the profile fields of interest
  * @param array   $values         the values for the above fields
  * @param boolean $searchable     searchable or not
  * @param array   $componentWhere component condition
  *
  * @return void
  * @access public
  * @static
  */
 public static function getValues($cid, &$fields, &$values, $searchable = true, $componentWhere = null)
 {
     if (empty($cid)) {
         return null;
     }
     $options = array();
     $studentFields = array();
     if (CRM_Core_Permission::access('Quest', false)) {
         //student fields ( check box )
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
     }
     // get the contact details (hier)
     $returnProperties =& CRM_Contact_BAO_Contact::makeHierReturnProperties($fields);
     $params = array(array('contact_id', '=', $cid, 0, 0));
     // add conditions specified by components. eg partcipant_id etc
     if (!empty($componentWhere)) {
         $params = array_merge($params, $componentWhere);
     }
     $query =& new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
     $options =& $query->_options;
     $details = $query->searchQuery();
     if (!$details->fetch()) {
         return;
     }
     $config =& CRM_Core_Config::singleton();
     require_once 'CRM/Core/PseudoConstant.php';
     $locationTypes = $imProviders = array();
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     //start of code to set the default values
     foreach ($fields as $name => $field) {
         // fix for CRM-3962
         if ($name == 'id') {
             $name = 'contact_id';
         }
         $index = $field['title'];
         $params[$index] = $values[$index] = '';
         $customFieldName = null;
         $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee');
         if (isset($details->{$name}) || $name == 'group' || $name == 'tag') {
             //hack for CRM-665
             // to handle gender / suffix / prefix
             if (in_array($name, array('gender', 'individual_prefix', 'individual_suffix'))) {
                 $values[$index] = $details->{$name};
                 $name = $name . '_id';
                 $params[$index] = $details->{$name};
             } else {
                 if (in_array($name, array('email_greeting', 'postal_greeting', 'addressee'))) {
                     $dname = $name . '_display';
                     $values[$index] = $details->{$dname};
                     $name = $name . '_id';
                     $params[$index] = $details->{$name};
                 } else {
                     if (in_array($name, array('state_province', 'country', 'county'))) {
                         $values[$index] = $details->{$name};
                         $idx = $name . '_id';
                         $params[$index] = $details->{$idx};
                     } else {
                         if ($name === 'preferred_communication_method') {
                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                             $pref = array();
                             $compref = array();
                             $pref = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $details->{$name});
                             foreach ($pref as $k) {
                                 if ($k) {
                                     $compref[] = $communicationFields[$k];
                                 }
                             }
                             $params[$index] = $details->{$name};
                             $values[$index] = implode(",", $compref);
                         } else {
                             if ($name == 'group') {
                                 $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', null, false, true);
                                 $title = array();
                                 $ids = array();
                                 foreach ($groups as $g) {
                                     if ($g['visibility'] != 'User and User Admin Only') {
                                         $title[] = $g['title'];
                                         if ($g['visibility'] == 'Public Pages') {
                                             $ids[] = $g['group_id'];
                                         }
                                     }
                                 }
                                 $values[$index] = implode(', ', $title);
                                 $params[$index] = implode(',', $ids);
                             } else {
                                 if ($name == 'tag') {
                                     require_once 'CRM/Core/BAO/EntityTag.php';
                                     $entityTags =& CRM_Core_BAO_EntityTag::getTag($cid);
                                     $allTags =& CRM_Core_PseudoConstant::tag();
                                     $title = array();
                                     foreach ($entityTags as $tagId) {
                                         $title[] = $allTags[$tagId];
                                     }
                                     $values[$index] = implode(', ', $title);
                                     $params[$index] = implode(',', $entityTags);
                                 } else {
                                     if (array_key_exists($name, $studentFields)) {
                                         require_once 'CRM/Core/OptionGroup.php';
                                         $paramsNew = array($name => $details->{$name});
                                         if ($name == 'test_tutoring') {
                                             $names = array($name => array('newName' => $index, 'groupName' => 'test'));
                                         } else {
                                             if (substr($name, 0, 4) == 'cmr_') {
                                                 //for  readers group
                                                 $names = array($name => array('newName' => $index, 'groupName' => substr($name, 0, -3)));
                                             } else {
                                                 $names = array($name => array('newName' => $index, 'groupName' => $name));
                                             }
                                         }
                                         CRM_Core_OptionGroup::lookupValues($paramsNew, $names, false);
                                         $values[$index] = $paramsNew[$index];
                                         $params[$index] = $paramsNew[$name];
                                     } else {
                                         $processed = false;
                                         if (CRM_Core_Permission::access('Quest', false)) {
                                             require_once 'CRM/Quest/BAO/Student.php';
                                             $processed = CRM_Quest_BAO_Student::buildStudentForm($this, $field);
                                         }
                                         if (!$processed) {
                                             if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                                                 if ($details->{$name}) {
                                                     $values[$index] = '[ x ]';
                                                 }
                                             } else {
                                                 require_once 'CRM/Core/BAO/CustomField.php';
                                                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                                     $htmlType = $field['html_type'];
                                                     $dataType = $field['data_type'];
                                                     if ($htmlType == 'File') {
                                                         $fileURL = CRM_Core_BAO_CustomField::getFileURL($cid, $cfID);
                                                         $params[$index] = $values[$index] = $fileURL['file_url'];
                                                     } else {
                                                         $customVal = null;
                                                         if (isset($dao) && ($dao->data_type == 'Int' || $dao->data_type == 'Boolean')) {
                                                             $customVal = (int) $details->{$name};
                                                         } else {
                                                             if (isset($dao) && $dao->data_type == 'Float') {
                                                                 $customVal = (double) $details->{$name};
                                                             } else {
                                                                 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}))) {
                                                                     $customVal = $details->{$name};
                                                                 }
                                                             }
                                                         }
                                                         //CRM-4582
                                                         if (CRM_Utils_System::isNull($customVal)) {
                                                             continue;
                                                         }
                                                         $params[$index] = $customVal;
                                                         $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                                                         if ($htmlType == 'Autocomplete-Select') {
                                                             $params[$index] = $values[$index];
                                                         }
                                                         if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                                             $customFieldName = "{$name}_from";
                                                         }
                                                     }
                                                 } else {
                                                     if ($name == 'home_URL' && !empty($details->{$name})) {
                                                         $url = CRM_Utils_System::fixURL($details->{$name});
                                                         $values[$index] = "<a href=\"{$url}\">{$details->{$name}}</a>";
                                                     } else {
                                                         if (in_array($name, array('birth_date', 'deceased_date', 'membership_start_date', 'membership_end_date', 'join_date'))) {
                                                             require_once 'CRM/Utils/Date.php';
                                                             $values[$index] = CRM_Utils_Date::customFormat($details->{$name});
                                                             $params[$index] = CRM_Utils_Date::isoToMysql($details->{$name});
                                                         } else {
                                                             $values[$index] = $details->{$name};
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         } else {
             if (strpos($name, '-') !== false) {
                 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
                 if ($id == 'Primary') {
                     // fix for CRM-1543
                     // not sure why we'd every use Primary location type id
                     // we need to fix the source if we are using it
                     // $locationTypeName = CRM_Contact_BAO_Contact::getPrimaryLocationType( $cid );
                     $locationTypeName = 1;
                 } else {
                     $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                 }
                 if (!$locationTypeName) {
                     continue;
                 }
                 $detailName = "{$locationTypeName}-{$fieldName}";
                 $detailName = str_replace(' ', '_', $detailName);
                 if (in_array($fieldName, array('phone', 'im', 'email', 'openid'))) {
                     if ($type) {
                         $detailName .= "-{$type}";
                     }
                 }
                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                     $values[$index] = $details->{$detailName};
                     $idx = $detailName . '_id';
                     $params[$index] = $details->{$idx};
                 } else {
                     if ($fieldName == 'im') {
                         $providerId = $detailName . '-provider_id';
                         $providerName = $imProviders[$details->{$providerId}];
                         if ($providerName) {
                             $values[$index] = $details->{$detailName} . " (" . $providerName . ")";
                         } else {
                             $values[$index] = $details->{$detailName};
                         }
                         $params[$index] = $details->{$detailName};
                     } else {
                         $values[$index] = $params[$index] = $details->{$detailName};
                     }
                 }
             }
         }
         if ($field['visibility'] == "Public Pages and Listings" && CRM_Core_Permission::check('profile listings and forms')) {
             if (CRM_Utils_System::isNull($params[$index])) {
                 $params[$index] = $values[$index];
             }
             if (!isset($params[$index])) {
                 continue;
             }
             $customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name']);
             if (!$customFieldName) {
                 $fieldName = $field['name'];
             } else {
                 $fieldName = $customFieldName;
             }
             $url = null;
             if (CRM_Core_BAO_CustomField::getKeyID($field['name'])) {
                 $htmlType = $field['html_type'];
                 if ($htmlType == 'Link') {
                     $url = $params[$index];
                 } else {
                     if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country'))) {
                         $valSeperator = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                         $selectedOptions = explode($valSeperator, $params[$index]);
                         foreach ($selectedOptions as $key => $multiOption) {
                             if ($multiOption) {
                                 $eachOption = $valSeperator . $multiOption . $valSeperator;
                                 $url[] = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($eachOption));
                             }
                         }
                     } else {
                         $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
                     }
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
             }
             if ($url && !empty($values[$index]) && $searchable) {
                 if (is_array($url) && !empty($url)) {
                     $links = array();
                     $eachMultiValue = explode(', ', $values[$index]);
                     foreach ($eachMultiValue as $key => $valueLabel) {
                         $links[] = '<a href="' . $url[$key] . '">' . $valueLabel . '</a>';
                     }
                     $values[$index] = implode(', ', $links);
                 } else {
                     $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>';
                 }
             }
         }
     }
 }
 public function preProcess()
 {
     //custom data related code
     $this->_cdType = CRM_Utils_Array::value('type', $_GET);
     $this->assign('cdType', FALSE);
     if ($this->_cdType) {
         $this->assign('cdType', TRUE);
         return CRM_Custom_Form_CustomData::preProcess($this);
     }
     // get price set id.
     $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
     $this->set('priceSetId', $this->_priceSetId);
     $this->assign('priceSetId', $this->_priceSetId);
     // action
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     $this->_processors = array();
     // check for edit permission
     if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
     }
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('context', $this->_context);
     if ($this->_id) {
         $this->_memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $this->_id, "membership_type_id");
         $this->_membershipIDs[] = $this->_id;
     }
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     $this->assign('membershipMode', $this->_mode);
     if ($this->_mode) {
         $this->_paymentProcessor = array('billing_mode' => 1);
         $validProcessors = array();
         $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )");
         foreach ($processors as $ppID => $label) {
             $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
             if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
                 continue;
             } elseif ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
                 continue;
             } else {
                 $paymentObject = CRM_Core_Payment::singleton($this->_mode, $paymentProcessor, $this);
                 $error = $paymentObject->checkConfig();
                 if (empty($error)) {
                     $validProcessors[$ppID] = $label;
                 }
                 $paymentObject = NULL;
             }
         }
         if (empty($validProcessors)) {
             CRM_Core_Error::fatal(ts('Could not find valid payment processor for this page'));
         } else {
             $this->_processors = $validProcessors;
         }
         // also check for billing information
         // get the billing location type
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         // CRM-8108 remove ts around Billing location type
         //$this->_bltID = array_search( ts('Billing'),  $locationTypes );
         $this->_bltID = array_search('Billing', $locationTypes);
         if (!$this->_bltID) {
             CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
         }
         $this->set('bltID', $this->_bltID);
         $this->assign('bltID', $this->_bltID);
         $this->_fields = array();
         CRM_Core_Payment_Form::setCreditCardFields($this);
         // this required to show billing block
         $this->assign_by_ref('paymentProcessor', $paymentProcessor);
         $this->assign('hidePayPalExpress', TRUE);
     }
     if ($this->_action & CRM_Core_Action::ADD) {
         //check whether any active membership statuses are available - redirects back to contact summary if not
         CRM_Member_BAO_Membership::statusAvilability($this->_contactID);
         if ($this->_contactID) {
             //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
             $hasMembership = CRM_Member_BAO_Membership::getContactMembership($this->_contactID, NULL, 0);
             if (!empty($hasMembership)) {
                 $hasMembership['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $hasMembership['membership_type_id'], 'name', 'id');
                 $hasMembership['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $hasMembership['status_id'], 'label', 'id');
                 $membershipTab = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$this->_contactID}&selectedChild=member");
                 if ($this->_mode) {
                     $renewUrl = CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$hasMembership['id']}&context=membership&selectedChild=member&mode=live");
                 } else {
                     $renewUrl = CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$hasMembership['id']}&context=membership&selectedChild=member");
                 }
                 if (CRM_Utils_Array::value('membership_end_date', $hasMembership)) {
                     CRM_Core_Session::setStatus(ts('This contact has an existing %1 membership record with %2 status and end date of %3. <a href="%4">Click here if you want to renew this membership</a> (rather than creating a new membership record). <a href="%5">Click here to view all existing and / or expired memberships for this contact.</a>', array(1 => $hasMembership['membership_type'], 2 => $hasMembership['membership_status'], 3 => CRM_Utils_Date::customformat($hasMembership['membership_end_date']), 4 => $renewUrl, 5 => $membershipTab)));
                 } else {
                     CRM_Core_Session::setStatus(ts('This contact has an existing %1 membership record with %2 status. <a href="%3">Click here if you want to renew this membership</a> (rather than creating a new membership record). <a href="%4">Click here to view all existing and / or expired memberships for this contact.</a>', array(1 => $hasMembership['membership_type'], 2 => $hasMembership['membership_status'], 3 => $renewUrl, 4 => $membershipTab)));
                 }
             }
         }
     }
     // when custom data is included in this page
     if (CRM_Utils_Array::value("hidden_custom", $_POST)) {
         CRM_Custom_Form_CustomData::preProcess($this);
         CRM_Custom_Form_CustomData::buildQuickForm($this);
         CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     // CRM-4395, get the online pending contribution id.
     $this->_onlinePendingContributionId = NULL;
     if (!$this->_mode && $this->_id && $this->_action & CRM_Core_Action::UPDATE) {
         $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id, 'Membership');
     }
     $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId);
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
     parent::preProcess();
 }
Example #13
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 public function buildQuickForm()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete Profile Field'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if (isset($this->_id)) {
         $params = array('id' => $this->_id);
         CRM_Core_BAO_UFField::retrieve($params, $defaults);
         // set it to null if so (avoids crappy E_NOTICE errors below
         $defaults['location_type_id'] = CRM_Utils_Array::value('location_type_id', $defaults);
         $specialFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'county', 'phone', 'email', 'im', 'address_name');
         if (!$defaults['location_type_id'] && in_array($defaults['field_name'], $specialFields)) {
             $defaults['location_type_id'] = 0;
         }
         $defaults['field_name'] = array($defaults['field_type'], $defaults['field_name'], $defaults['location_type_id'], CRM_Utils_Array::value('phone_type_id', $defaults));
         $this->_gid = $defaults['uf_group_id'];
     } else {
         $defaults['is_active'] = 1;
     }
     if ($this->_action & CRM_Core_Action::ADD) {
         $fieldValues = array('uf_group_id' => $this->_gid);
         $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_UFField', $fieldValues);
     }
     // lets trim all the whitespace
     $this->applyFilter('__ALL__', 'trim');
     //hidden field to catch the group id in profile
     $this->add('hidden', 'group_id', $this->_gid);
     //hidden field to catch the field id in profile
     $this->add('hidden', 'field_id', $this->_id);
     $fields = array();
     $fields['Individual'] =& CRM_Contact_BAO_Contact::importableFields('Individual', false, false, true);
     $fields['Household'] =& CRM_Contact_BAO_Contact::importableFields('Household', false, false, true);
     $fields['Organization'] =& CRM_Contact_BAO_Contact::importableFields('Organization', false, false, true);
     // add current employer for individuals
     $fields['Individual']['current_employer'] = array('name' => 'organization_name', 'title' => ts('Current Employer'));
     // unset unwanted fields
     $unsetFieldArray = array('note', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'id');
     foreach ($unsetFieldArray as $value) {
         unset($fields['Individual'][$value]);
         unset($fields['Household'][$value]);
         unset($fields['Organization'][$value]);
     }
     require_once 'CRM/Core/BAO/Preferences.php';
     $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true);
     if (!$addressOptions['county']) {
         unset($fields['Individual']['county']);
         unset($fields['Household']['county']);
         unset($fields['Organization']['county']);
     }
     //build the common contact fields array CRM-3037.
     foreach ($fields['Individual'] as $key => $value) {
         if (CRM_Utils_Array::value($key, $fields['Household']) && CRM_Utils_Array::value($key, $fields['Organization'])) {
             $fields['Contact'][$key] = $value;
             //as we move common fields to contacts. There fore these fields
             //are unset from resoective array's.
             unset($fields['Individual'][$key]);
             unset($fields['Household'][$key]);
             unset($fields['Organization'][$key]);
         }
     }
     // add current employer for individuals
     $fields['Contact']['id'] = array('name' => 'id', 'title' => ts('Internal Contact ID'));
     unset($fields['Contact']['contact_type']);
     // since we need a hierarchical list to display contact types & subtypes,
     // this is what we going to display in first selector
     $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(false, false);
     unset($contactTypes['']);
     // include Subtypes For Profile
     $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
     foreach ($subTypes as $name => $val) {
         //custom fields for sub type
         $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($name);
         if (array_key_exists($val['parent'], $fields)) {
             $fields[$name] = $fields[$val['parent']] + $subTypeFields;
         } else {
             $fields[$name] = $subTypeFields;
         }
     }
     unset($subTypes);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $fields['Student'] =& CRM_Quest_BAO_Student::exportableFields();
     }
     if (CRM_Core_Permission::access('CiviContribute')) {
         $contribFields =& CRM_Contribute_BAO_Contribution::getContributionFields();
         if (!empty($contribFields)) {
             unset($contribFields['is_test']);
             unset($contribFields['is_pay_later']);
             unset($contribFields['contribution_id']);
             $fields['Contribution'] =& $contribFields;
         }
     }
     if (CRM_Core_Permission::access('CiviEvent')) {
         require_once 'CRM/Event/BAO/Query.php';
         $participantFields =& CRM_Event_BAO_Query::getParticipantFields(true);
         if (!empty($participantFields)) {
             unset($participantFields['external_identifier']);
             unset($participantFields['event_id']);
             unset($participantFields['participant_contact_id']);
             unset($participantFields['participant_is_test']);
             unset($participantFields['participant_fee_level']);
             unset($participantFields['participant_id']);
             unset($participantFields['participant_is_pay_later']);
             $fields['Participant'] =& $participantFields;
         }
     }
     if (CRM_Core_Permission::access('CiviMember')) {
         require_once 'CRM/Member/BAO/Membership.php';
         $membershipFields =& CRM_Member_BAO_Membership::getMembershipFields();
         unset($membershipFields['membership_id']);
         unset($membershipFields['join_date']);
         unset($membershipFields['membership_start_date']);
         unset($membershipFields['membership_type_id']);
         unset($membershipFields['membership_end_date']);
         unset($membershipFields['member_is_test']);
         unset($membershipFields['is_override']);
         unset($membershipFields['status_id']);
         unset($membershipFields['member_is_pay_later']);
         $fields['Membership'] =& $membershipFields;
     }
     $noSearchable = array();
     foreach ($fields as $key => $value) {
         foreach ($value as $key1 => $value1) {
             //CRM-2676, replacing the conflict for same custom field name from different custom group.
             require_once 'CRM/Core/BAO/CustomField.php';
             if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key1)) {
                 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
                 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
                 $this->_mapperFields[$key][$key1] = $value1['title'] . ' :: ' . $customGroupName;
             } else {
                 $this->_mapperFields[$key][$key1] = $value1['title'];
             }
             $hasLocationTypes[$key][$key1] = CRM_Utils_Array::value('hasLocationType', $value1);
             // hide the 'is searchable' field for 'File' custom data
             if (isset($value1['data_type']) && isset($value1['html_type']) && ($value1['data_type'] == 'File' && $value1['html_type'] == 'File' || $value1['data_type'] == 'Link' && $value1['html_type'] == 'Link')) {
                 if (!in_array($value1['title'], $noSearchable)) {
                     $noSearchable[] = $value1['title'];
                 }
             }
         }
     }
     $this->assign('noSearchable', $noSearchable);
     require_once 'CRM/Core/BAO/LocationType.php';
     $this->_location_types =& CRM_Core_PseudoConstant::locationType();
     $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault();
     /* FIXME: dirty hack to make the default option show up first.  This
      * avoids a mozilla browser bug with defaults on dynamically constructed
      * selector widgets. */
     if ($defaultLocationType) {
         $defaultLocation = $this->_location_types[$defaultLocationType->id];
         unset($this->_location_types[$defaultLocationType->id]);
         $this->_location_types = array($defaultLocationType->id => $defaultLocation) + $this->_location_types;
     }
     $this->_location_types = array('Primary') + $this->_location_types;
     $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array();
     $sel1 = array('' => '- select -') + $contactTypes;
     if (CRM_Core_Permission::access('Quest')) {
         $sel1['Student'] = 'Students';
     }
     if (CRM_Core_Permission::access('CiviEvent')) {
         $sel1['Participant'] = 'Participants';
     }
     if (!empty($contribFields)) {
         $sel1['Contribution'] = 'Contributions';
     }
     if (!empty($membershipFields)) {
         $sel1['Membership'] = 'Membership';
     }
     foreach ($sel1 as $key => $sel) {
         if ($key) {
             $sel2[$key] = $this->_mapperFields[$key];
         }
     }
     $sel3[''] = null;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     ksort($phoneTypes);
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_location_types as $key => $value) {
                 $sel4[$k]['phone'][$key] =& $phoneTypes;
             }
         }
     }
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             if (is_array($this->_mapperFields[$k])) {
                 foreach ($this->_mapperFields[$k] as $key => $value) {
                     if ($hasLocationTypes[$k][$key]) {
                         $sel3[$k][$key] = $this->_location_types;
                     } else {
                         $sel3[$key] = null;
                     }
                 }
             }
         }
     }
     $this->_defaults = array();
     $js = "<script type='text/javascript'>\n";
     $formName = "document.{$this->_name}";
     $alreadyMixProfile = false;
     if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
         $alreadyMixProfile = true;
     }
     $this->assign('alreadyMixProfile', $alreadyMixProfile);
     $attributes = array('onclick' => "showLabel();mixProfile();", 'onblur' => 'showLabel();mixProfile();');
     $sel =& $this->addElement('hierselect', "field_name", ts('Field Name'), $attributes);
     $formValues = array();
     $formValues = $this->exportValues();
     if (empty($formValues)) {
         for ($k = 1; $k < 4; $k++) {
             if (!$defaults['field_name'][$k]) {
                 $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
             }
         }
     } else {
         if (!empty($formValues['field_name'])) {
             foreach ($formValues['field_name'] as $value) {
                 for ($k = 1; $k < 4; $k++) {
                     if (!isset($formValues['field_name'][$k]) || !$formValues['field_name'][$k]) {
                         $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
                     } else {
                         $js .= "{$formName}['field_name[{$k}]'].style.display = '';\n";
                     }
                 }
             }
         } else {
             for ($k = 1; $k < 4; $k++) {
                 if (!isset($defaults['field_name'][$k])) {
                     $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
                 }
             }
         }
     }
     foreach ($sel2 as $k => $v) {
         if (is_array($sel2[$k])) {
             asort($sel2[$k]);
         }
     }
     $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::ufVisibility(), true, array("onChange" => "showHideSeletorSearch(this.value);"));
     //CRM-4363
     $js = array('onclick' => "mixProfile();");
     // should the field appear in selectors (as a column)?
     $this->add('checkbox', 'in_selector', ts('Results Column?'), null, null, $js);
     $this->add('checkbox', 'is_searchable', ts('Searchable?'), null, null, $js);
     // weight
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'weight'), true);
     $this->addRule('weight', ts('is a numeric field'), 'numeric');
     $this->add('textarea', 'help_post', ts('Field Help'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'help_post'));
     // listings title
     $this->add('text', 'listings_title', ts('Listings Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'listings_title'));
     $this->addRule('listings_title', ts('Please enter a valid title for this field when displayed in user listings.'), 'title');
     $this->add('checkbox', 'is_required', ts('Required?'));
     $this->add('checkbox', 'is_active', ts('Active?'));
     $this->add('checkbox', 'is_view', ts('View Only?'));
     // $this->add( 'checkbox', 'is_registration', ts( 'Display in Registration Form?' ) );
     //$this->add( 'checkbox', 'is_match'       , ts( 'Key to Match Contacts?'        ) );
     $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'label'));
     $js = null;
     if ($this->_hasSearchableORInSelector) {
         $js = array('onclick' => "return verify( );");
     }
     // add buttons
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => true, 'js' => $js), array('type' => 'next', 'name' => ts('Save and New'), 'subName' => 'new', 'js' => $js), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_UF_Form_Field', 'formRule'), $this);
     // if view mode pls freeze it with the done button.
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->freeze();
         $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/uf/group/field?reset=1&action=browse&gid=" . $this->_gid . "'"));
     }
     $this->setDefaults($defaults);
 }
 function getBillingID(&$ids)
 {
     // get the billing location type
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     // CRM-8108 remove the ts around the Billing locationtype
     //$ids['billing'] =  array_search( ts('Billing'),  $locationTypes );
     $ids['billing'] = array_search('Billing', $locationTypes);
     if (!$ids['billing']) {
         CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
         echo "Failure: Could not find billing location type<p>";
         return FALSE;
     }
     return TRUE;
 }
 /**
  * where / qill clause for location type
  *
  * @return void
  * @access public
  */
 function locationType(&$values, $status = NULL)
 {
     list($name, $op, $value, $grouping, $wildcard) = $values;
     if (is_array($value)) {
         $this->_where[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
         $this->_tables['civicrm_address'] = 1;
         $this->_whereTables['civicrm_address'] = 1;
         $locationType = CRM_Core_PseudoConstant::locationType();
         $names = array();
         foreach (array_keys($value) as $id) {
             $names[] = $locationType[$id];
         }
         $this->_primaryLocation = FALSE;
         if (!$status) {
             $this->_qill[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
         } else {
             return implode(' ' . ts('or') . ' ', $names);
         }
     }
 }
Example #16
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     $this->_showFeeBlock = CRM_Utils_Array::value('eventId', $_GET);
     $this->assign('showFeeBlock', false);
     $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     $this->_participantId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('context', $this->_context);
     // get the option value for custom data type
     $this->_roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
     $this->_eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
     $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
     $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
     if ($this->_mode) {
         $this->assign('participantMode', $this->_mode);
         $this->_paymentProcessor = array('billing_mode' => 1);
         $validProcessors = array();
         $processors = CRM_Core_PseudoConstant::paymentProcessor(false, false, "billing_mode IN ( 1, 3 )");
         foreach ($processors as $ppID => $label) {
             require_once 'CRM/Core/BAO/PaymentProcessor.php';
             require_once 'CRM/Core/Payment.php';
             $paymentProcessor =& CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
             if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
                 continue;
             } else {
                 if ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
                     continue;
                 } else {
                     $paymentObject =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $paymentProcessor, $this);
                     $error = $paymentObject->checkConfig();
                     if (empty($error)) {
                         $validProcessors[$ppID] = $label;
                     }
                     $paymentObject = null;
                 }
             }
         }
         if (empty($validProcessors)) {
             CRM_Core_Error::fatal(ts('Could not find valid payment processor for this page'));
         } else {
             $this->_processors = $validProcessors;
         }
         // also check for billing information
         // get the billing location type
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $this->_bltID = array_search('Billing', $locationTypes);
         if (!$this->_bltID) {
             CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
         }
         $this->set('bltID', $this->_bltID);
         $this->assign('bltID', $this->_bltID);
         $this->_fields = array();
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::setCreditCardFields($this);
         // this required to show billing block
         $this->assign_by_ref('paymentProcessor', $paymentProcessor);
         $this->assign('hidePayPalExpress', true);
     }
     if ($this->_showFeeBlock) {
         $this->assign('showFeeBlock', true);
         $this->assign('paid', true);
         return CRM_Event_Form_EventFees::preProcess($this);
     }
     //custom data related code
     $this->_cdType = CRM_Utils_Array::value('type', $_GET);
     $this->assign('cdType', false);
     if ($this->_cdType) {
         $this->assign('cdType', true);
         return CRM_Custom_Form_CustomData::preProcess($this);
     }
     //check the mode when this form is called either single or as
     //search task action
     if ($this->_participantId || $this->_contactID || $this->_context == 'standalone') {
         $this->_single = true;
         $this->assign('urlPath', 'civicrm/contact/view/participant');
         if (!$this->_participantId && !$this->_contactID) {
             $breadCrumbs = array(array('title' => ts('CiviEvent Dashboard'), 'url' => CRM_Utils_System::url('civicrm/event', 'reset=1')));
             CRM_Utils_System::appendBreadCrumb($breadCrumbs);
         }
     } else {
         //set the appropriate action
         $advanced = null;
         $builder = null;
         $session =& CRM_Core_Session::singleton();
         $advanced = $session->get('isAdvanced');
         $builder = $session->get('isSearchBuilder');
         $searchType = "basic";
         if ($advanced == 1) {
             $this->_action = CRM_Core_Action::ADVANCED;
             $searchType = "advanced";
         } else {
             if ($advanced == 2 && ($builder = 1)) {
                 $this->_action = CRM_Core_Action::PROFILE;
                 $searchType = "builder";
             } else {
                 if ($advanced == 3) {
                     $searchType = "custom";
                 }
             }
         }
         parent::preProcess();
         $this->_single = false;
         $this->_contactID = null;
         //set ajax path, this used for custom data building
         $this->assign('urlPath', "civicrm/contact/search/{$searchType}");
         $this->assign('urlPathVar', "_qf_Participant_display=true&qfKey={$this->controller->_key}");
     }
     $this->assign('single', $this->_single);
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, false, 'add');
     $this->assign('action', $this->_action);
     // check for edit permission
     if (!CRM_Core_Permission::checkActionPermission('CiviEvent', $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
     }
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     if ($this->_participantId) {
         // assign participant id to the template
         $this->assign('participantId', $this->_participantId);
         $this->_roleId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $this->_participantId, 'role_id');
     }
     // when fee amount is included in form
     if (CRM_Utils_Array::value('hidden_feeblock', $_POST) || CRM_Utils_Array::value('send_receipt', $_POST)) {
         CRM_Event_Form_EventFees::preProcess($this);
         CRM_Event_Form_EventFees::buildQuickForm($this);
         CRM_Event_Form_EventFees::setDefaultValues($this);
     }
     // when custom data is included in this page
     if (CRM_Utils_Array::value("hidden_custom", $_POST)) {
         //custom data of type participant role
         CRM_Custom_Form_Customdata::preProcess($this, $this->_roleCustomDataTypeID, $_POST['role_id'], 1, 'Participant', $this->_participantId);
         CRM_Custom_Form_Customdata::buildQuickForm($this);
         CRM_Custom_Form_Customdata::setDefaultValues($this);
         //custom data of type participant event
         CRM_Custom_Form_Customdata::preProcess($this, $this->_eventNameCustomDataTypeID, $_POST['event_id'], 1, 'Participant', $this->_participantId);
         CRM_Custom_Form_Customdata::buildQuickForm($this);
         CRM_Custom_Form_Customdata::setDefaultValues($this);
         //custom data of type participant, ( we 'null' to reset subType and subName)
         CRM_Custom_Form_Customdata::preProcess($this, 'null', 'null', 1, 'Participant', $this->_participantId);
         CRM_Custom_Form_Customdata::buildQuickForm($this);
         CRM_Custom_Form_Customdata::setDefaultValues($this);
     }
     // CRM-4395, get the online pending contribution id.
     $this->_onlinePendingContributionId = null;
     if (!$this->_mode && $this->_participantId && $this->_action & CRM_Core_Action::UPDATE) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_participantId, 'Event');
     }
     $this->set('onlinePendingContributionId', $this->_onlinePendingContributionId);
 }
Example #17
0
 /**
  * Process the mapped fields and map it into the uploaded file
  * preview the file and extract some summary statistics
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues('MapField');
     //reload the mapfield if load mapping is pressed
     if (!empty($params['savedMapping'])) {
         $this->set('savedMapping', $params['savedMapping']);
         $this->controller->resetPage($this->_name);
         return;
     }
     $mapperKeys = array();
     $mapper = array();
     $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
     $mapperKeysMain = array();
     $mapperLocType = array();
     $mapperPhoneType = array();
     $mapperImProvider = array();
     $locations = array();
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     for ($i = 0; $i < $this->_columnCount; $i++) {
         $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
         $mapperKeysMain[$i] = $mapperKeys[$i][0];
         if (isset($mapperKeys[$i][1]) && is_numeric($mapperKeys[$i][1])) {
             $mapperLocType[$i] = $mapperKeys[$i][1];
         } else {
             $mapperLocType[$i] = null;
         }
         $locations[$i] = isset($mapperLocType[$i]) ? $this->_location_types[$mapperLocType[$i]] : null;
         // to store phone_type id and provider id seperately, CRM-3140
         if (CRM_Utils_Array::value($i, $mapperKeysMain) == 'phone') {
             $mapperPhoneType[$i] = $phoneTypes[$mapperKeys[$i][2]];
             $mapperImProvider[$i] = null;
         } else {
             if (CRM_Utils_Array::value($i, $mapperKeysMain) == 'im') {
                 $mapperImProvider[$i] = $imProviders[$mapperKeys[$i][2]];
                 $mapperPhoneType[$i] = null;
             } else {
                 $mapperPhoneType[$i] = null;
                 $mapperImProvider[$i] = null;
             }
         }
         //relationship info
         if (isset($mapperKeys[$i]) && isset($mapperKeys[$i][0])) {
             list($id, $first, $second) = CRM_Utils_System::explode('_', $mapperKeys[$i][0], 3);
         } else {
             list($id, $first, $second) = array(null, null, null);
         }
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $related[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
             $relatedContactLocType[$i] = isset($mapperKeys[$i][1]) ? $this->_location_types[$mapperKeys[$i][2]] : null;
             //$relatedContactPhoneType[$i] = !is_numeric($mapperKeys[$i][2]) ? $mapperKeys[$i][3] : null;
             // to store phoneType id and provider id seperately for ralated contact, CRM-3140
             if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                 $relatedContactPhoneType[$i] = isset($mapperKeys[$i][3]) ? $phoneTypes[$mapperKeys[$i][3]] : null;
                 $relatedContactImProvider[$i] = null;
             } else {
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                     $relatedContactImProvider[$i] = isset($mapperKeys[$i][3]) ? $imProviders[$mapperKeys[$i][3]] : null;
                     $relatedContactPhoneType[$i] = null;
                 }
             }
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             eval('$relatedContactType[$i] = $relationType->contact_type_' . $second . ';');
             $relatedContactDetails[$i] = $this->_formattedFieldNames[$relatedContactType[$i]][$mapperKeys[$i][1]];
         } else {
             $related[$i] = null;
             $relatedContactType[$i] = null;
             $relatedContactDetails[$i] = null;
             $relatedContactLocType[$i] = null;
             $relatedContactPhoneType[$i] = null;
             $relatedContactImProvider[$i] = null;
         }
     }
     $this->set('mapper', $mapper);
     $this->set('locations', $locations);
     $this->set('phones', $mapperPhoneType);
     $this->set('ims', $mapperImProvider);
     $this->set('columnNames', $this->_columnNames);
     //relationship info
     $this->set('related', $related);
     $this->set('relatedContactType', $relatedContactType);
     $this->set('relatedContactDetails', $relatedContactDetails);
     $this->set('relatedContactLocType', $relatedContactLocType);
     $this->set('relatedContactPhoneType', $relatedContactPhoneType);
     $this->set('relatedContactImProvider', $relatedContactImProvider);
     // store mapping Id to display it in the preview page
     $this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params));
     //Updating Mapping Records
     if (CRM_Utils_Array::value('updateMapping', $params)) {
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $mappingFields =& new CRM_Core_DAO_MappingField();
         $mappingFields->mapping_id = $params['mappingId'];
         $mappingFields->find();
         $mappingFieldsId = array();
         while ($mappingFields->fetch()) {
             if ($mappingFields->id) {
                 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
             }
         }
         for ($i = 0; $i < $this->_columnCount; $i++) {
             $updateMappingFields =& new CRM_Core_DAO_MappingField();
             $updateMappingFields->id = $mappingFieldsId[$i];
             $updateMappingFields->mapping_id = $params['mappingId'];
             $updateMappingFields->column_number = $i;
             list($id, $first, $second) = explode('_', $mapperKeys[$i][0]);
             if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
                 $updateMappingFields->relationship_type_id = $id;
                 $updateMappingFields->relationship_direction = "{$first}_{$second}";
                 $updateMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
                 $updateMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                 // get phoneType id and provider id separately
                 // before updating mappingFields of phone and IM for related contact, CRM-3140
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                     $updateMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                 } else {
                     if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                         $updateMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                     }
                 }
             } else {
                 $updateMappingFields->name = $mapper[$i];
                 $updateMappingFields->relationship_type_id = null;
                 $location = array_keys($locationTypes, $locations[$i]);
                 $updateMappingFields->location_type_id = isset($location) ? $location[0] : null;
                 // to store phoneType id and provider id seperately
                 // before updating mappingFields for phone and IM, CRM-3140
                 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
                     $updateMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                 } else {
                     if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
                         $updateMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                     }
                 }
             }
             $updateMappingFields->save();
         }
     }
     //Saving Mapping Details and Records
     if (CRM_Utils_Array::value('saveMapping', $params)) {
         $mappingParams = array('name' => $params['saveMappingName'], 'description' => $params['saveMappingDesc'], 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type', 'Import Contact', 'name'));
         $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $contactType = $this->get('contactType');
         switch ($contactType) {
             case CRM_Import_Parser::CONTACT_INDIVIDUAL:
                 $cType = 'Individual';
                 break;
             case CRM_Import_Parser::CONTACT_HOUSEHOLD:
                 $cType = 'Household';
                 break;
             case CRM_Import_Parser::CONTACT_ORGANIZATION:
                 $cType = 'Organization';
         }
         for ($i = 0; $i < $this->_columnCount; $i++) {
             $saveMappingFields =& new CRM_Core_DAO_MappingField();
             $saveMappingFields->mapping_id = $saveMapping->id;
             $saveMappingFields->contact_type = $cType;
             $saveMappingFields->column_number = $i;
             list($id, $first, $second) = explode('_', $mapperKeys[$i][0]);
             if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
                 $saveMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
                 $saveMappingFields->relationship_type_id = $id;
                 $saveMappingFields->relationship_direction = "{$first}_{$second}";
                 // to get phoneType id and provider id seperately
                 // before saving mappingFields of phone and IM for related contact, CRM-3140
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                     $saveMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                 } else {
                     if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                         $saveMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                     }
                 }
                 $saveMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
             } else {
                 $saveMappingFields->name = $mapper[$i];
                 $location_id = array_keys($locationTypes, $locations[$i]);
                 $saveMappingFields->location_type_id = isset($location_id[0]) ? $location_id[0] : null;
                 // to get phoneType id and provider id seperately
                 // before saving mappingFields of phone and IM, CRM-3140
                 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
                     $saveMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                 } else {
                     if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
                         $saveMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                     }
                 }
                 $saveMappingFields->relationship_type_id = null;
             }
             $saveMappingFields->save();
         }
         $this->set('savedMapping', $saveMappingFields->mapping_id);
     }
     $parser =& new CRM_Import_Parser_Contact($mapperKeysMain, $mapperLocType, $mapperPhoneType, $mapperImProvider, $related, $relatedContactType, $relatedContactDetails, $relatedContactLocType, $relatedContactPhoneType, $relatedContactImProvider);
     $primaryKeyName = $this->get('primaryKeyName');
     $statusFieldName = $this->get('statusFieldName');
     $parser->run($this->_importTableName, $mapper, CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType'), $primaryKeyName, $statusFieldName, $this->_onDuplicate, null, null, false, CRM_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'));
     // add all the necessary variables to the form
     $parser->set($this);
 }
Example #18
0
 /**
  * where / qill clause for location type and location Name
  *
  * @return void
  * @access public
  */
 function locationTypeAndName($status = null)
 {
     if (CRM_Utils_Array::value('location_type', $this->_params)) {
         if (is_array($this->_params['location_type'])) {
             $this->_where[] = 'civicrm_location.location_type_id IN (' . implode(',', array_keys($this->_params['location_type'])) . ')';
             $this->_tables['civicrm_location'] = 1;
             $this->_whereTables['civicrm_location'] = 1;
             $locationType =& CRM_Core_PseudoConstant::locationType();
             $names = array();
             foreach (array_keys($this->_params['location_type']) as $id) {
                 $names[] = $locationType[$id];
             }
             $this->_primaryLocation = false;
             if (!$status) {
                 $this->_qill[] = ts('Location type -') . ' ' . implode(' ' . ts('or') . ' ', $names);
             } else {
                 return implode(' ' . ts('or') . ' ', $names);
             }
         }
     }
     // do the same for location name
     if (CRM_Utils_Array::value('location_name', $this->_params)) {
         $this->_where[] = "civicrm_location.name LIKE '%" . strtolower(addslashes(trim($this->_params['location_name']))) . "%'";
         $this->_tables['civicrm_location'] = 1;
         $this->_whereTables['civicrm_location'] = 1;
         $this->_qill[] = ts('Location name like "%1"', array(1 => $this->_params['location_name']));
     }
 }
Example #19
0
 function getBillingID(&$ids)
 {
     // get the billing location type
     require_once "CRM/Core/PseudoConstant.php";
     $locationTypes =& CRM_Core_PseudoConstant::locationType();
     $ids['billing'] = array_search('Billing', $locationTypes);
     if (!$ids['billing']) {
         CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
         echo "Failure: Could not find billing location type<p>";
         return false;
     }
     return true;
 }
Example #20
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 function buildQuickForm()
 {
     if ($this->_action & CRM_CORE_ACTION_DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete Profile Field'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if (isset($this->_id)) {
         $params = array('id' => $this->_id);
         CRM_Core_BAO_UFField::retrieve($params, $defaults);
         $defaults['field_name'] = array($defaults['field_type'], $defaults['field_name'], $defaults['location_type_id'], $defaults['phone_type']);
         $this->_gid = $defaults['uf_group_id'];
     } else {
         $defaults['is_active'] = 1;
     }
     if ($this->_action & CRM_CORE_ACTION_ADD) {
         $uf =& new CRM_Core_DAO();
         $sql = "SELECT weight FROM civicrm_uf_field  WHERE uf_group_id = " . $this->_gid . " ORDER BY weight  DESC LIMIT 0, 1";
         $uf->query($sql);
         while ($uf->fetch()) {
             $defaults['weight'] = $uf->weight + 1;
         }
         if (empty($defaults['weight'])) {
             $defaults['weight'] = 1;
         }
     }
     // lets trim all the whitespace
     $this->applyFilter('__ALL__', 'trim');
     //hidden field to catch the group id in profile
     $this->add('hidden', 'group_id', $this->_gid);
     //hidden field to catch the field id in profile
     $this->add('hidden', 'field_id', $this->_id);
     $fields = array();
     $fields['Individual'] =& CRM_Contact_BAO_Contact::exportableFields('Individual');
     $fields['Household'] =& CRM_Contact_BAO_Contact::exportableFields('Household');
     $fields['Organization'] =& CRM_Contact_BAO_Contact::exportableFields('Organization');
     $contribFields =& CRM_Contribute_BAO_Contribution::getContributionFields();
     if (!empty($contribFields)) {
         $fields['Contribution'] =& $contribFields;
     }
     foreach ($fields as $key => $value) {
         foreach ($value as $key1 => $value1) {
             $this->_mapperFields[$key][$key1] = $value1['title'];
             $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
         }
     }
     require_once 'CRM/Core/BAO/LocationType.php';
     $this->_location_types =& CRM_Core_PseudoConstant::locationType();
     $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault();
     /* FIXME: dirty hack to make the default option show up first.  This
      * avoids a mozilla browser bug with defaults on dynamically constructed
      * selector widgets. */
     if ($defaultLocationType) {
         $defaultLocation = $this->_location_types[$defaultLocationType->id];
         unset($this->_location_types[$defaultLocationType->id]);
         $this->_location_types = array($defaultLocationType->id => $defaultLocation) + $this->_location_types;
     }
     $sel1 = array('' => '-select-') + CRM_Core_SelectValues::contactType();
     if (!empty($contribFields)) {
         $sel1['Contribution'] = 'Contributions';
     }
     foreach ($sel1 as $key => $sel) {
         if ($key) {
             $sel2[$key] = $this->_mapperFields[$key];
         }
     }
     $sel3[''] = null;
     $phoneTypes = CRM_Core_SelectValues::phoneType();
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_location_types as $key => $value) {
                 $sel4[$k]['phone'][$key] =& $phoneTypes;
             }
         }
     }
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_mapperFields[$k] as $key => $value) {
                 if ($hasLocationTypes[$k][$key]) {
                     $sel3[$k][$key] = $this->_location_types;
                 } else {
                     $sel3[$key] = null;
                 }
             }
         }
     }
     $this->_defaults = array();
     $js = "<script type='text/javascript'>\n";
     $formName = "document.{$this->_name}";
     $sel =& $this->addElement('hierselect', "field_name", ts('Field Name'), 'onclick="showLabel();"');
     $formValues = array();
     //$formValues = $this->controller->exportValues( $this->_name );
     $formValues = $_POST;
     // using $_POST since export values don't give values on first submit
     if (empty($formValues)) {
         for ($k = 1; $k < 4; $k++) {
             if (!$defaults['field_name'][$k]) {
                 $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
             }
         }
     } else {
         foreach ($formValues['field_name'] as $value) {
             for ($k = 1; $k < 4; $k++) {
                 if (!$formValues['field_name'][$k]) {
                     $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
                 }
             }
         }
     }
     $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::ufVisibility(), true);
     // should the field appear in selector?
     $this->add('checkbox', 'in_selector', ts('In Selector?'));
     // weight
     $this->add('text', 'weight', ts('Weight'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'weight'), true);
     $this->addRule('weight', ts(' is a numeric field'), 'numeric');
     $this->add('textarea', 'help_post', ts('Field Help'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'help_post'));
     // listings title
     $this->add('text', 'listings_title', ts('Listings Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'listings_title'));
     $this->addRule('listings_title', ts('Please enter a valid title for this field when displayed in user listings.'), 'title');
     $this->add('checkbox', 'is_required', ts('Required?'));
     $this->add('checkbox', 'is_active', ts('Active?'));
     $this->add('checkbox', 'is_searchable', ts('Searchable?'));
     $this->add('checkbox', 'is_view', ts('View Only?'));
     // $this->add( 'checkbox', 'is_registration', ts( 'Display in Registration Form?' ) );
     //$this->add( 'checkbox', 'is_match'       , ts( 'Key to Match Contacts?'        ) );
     $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'label'));
     // add buttons
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_UF_Form_Field', 'formRule'));
     // if view mode pls freeze it with the done button.
     if ($this->_action & CRM_CORE_ACTION_VIEW) {
         $this->freeze();
         $this->addElement('button', 'done', ts('Done'), array('onClick' => "location.href='civicrm/admin/uf/group/field?reset=1&action=browse&gid=" . $this->_gid . "'"));
     }
     $this->setDefaults($defaults);
 }
Example #21
0
 /**
  * Function to get the list the export fields
  *
  * @param int    $selectAll user preference while export
  * @param array  $ids  contact ids
  * @param array  $params associated array of fields
  * @param string $order order by clause
  * @param array  $associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null)
 {
     $headerRows = array();
     $primary = false;
     $returnProperties = array();
     $origFields = $fields;
     $queryMode = null;
     $paymentFields = false;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
         case CRM_Export_Form_Select::GRANT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = null;
             $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 1;
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($relIMProviderId) {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                         } else {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                         }
                     }
                     $relPhoneTypeId = $relIMProviderId = null;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 1;
                         } else {
                             if ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
                                 $returnProperties['grant_id'] = 1;
                             }
                         }
                     }
                 }
             }
         }
     } else {
         $primary = true;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', true, true);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = false;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = true;
                 $paymentTableId = "participant_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = true;
                 $paymentTableId = "membership_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset groups, tags, notes for components
             foreach (array('groups', 'tags', 'notes') as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] =& new CRM_Contact_BAO_Query(0, $relationReturnProperties, null, false, false, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             $relIDs = implode(',', $ids);
             $relSQL = "SELECT {$contactB} as relContact,{$contactA} as refContact  FROM civicrm_relationship \n                           WHERE  relationship_type_id = {$id} AND\n                                  {$contactA} IN ({$relIDs})\n                           GROUP BY {$contactA}";
             // Get the related contacts
             $relContactDAO = CRM_Core_DAO::executeQuery($relSQL);
             $relContactArray = array();
             while ($relContactDAO->fetch()) {
                 $relContactArray[$relContactDAO->refContact] = $relContactDAO->relContact;
             }
             $uniqueContacts = array_unique($relContactArray);
             if (!empty($uniqueContacts)) {
                 $relationWhere = " WHERE contact_a.id IN (" . implode(',', $uniqueContacts) . ") GROUP BY contact_id";
                 $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere}";
                 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
                 while ($allRelContactDAO->fetch()) {
                     foreach ($relContactArray as $k => $v) {
                         if ($allRelContactDAO->contact_id == $v) {
                             //$allRelContactArray[$rel][$k] = array();
                             // build the array of all related contacts
                             $allRelContactArray[$rel][$k] = clone $allRelContactDAO;
                         }
                     }
                 }
             }
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (CRM_Utils_Array::value('groups', $returnProperties)) {
         $oldClause = "contact_a.id = civicrm_group_contact.contact_id";
         $newClause = " ( {$oldClause} AND civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) ";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where}";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $queryString .= " GROUP BY contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray);
     $header = false;
     $addPaymentHeader = false;
     if ($paymentFields) {
         $addPaymentHeader = true;
         //special return properties for event and members
         $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
     }
     $componentDetails = $headerRows = array();
     $setHeader = true;
     while ($dao->fetch()) {
         $row = array();
         //first loop through returnproperties so that we return what is required, and in same order.
         $relationshipField = 0;
         foreach ($returnProperties as $field => $value) {
             //we should set header only once
             if ($setHeader) {
                 if (isset($query->_fields[$field]['title'])) {
                     $headerRows[] = $query->_fields[$field]['title'];
                 } else {
                     if ($field == 'phone_type_id') {
                         $headerRows[] = 'Phone Type';
                     } else {
                         if ($field == 'provider_id') {
                             $headerRows[] = 'Im Service Provider';
                         } else {
                             if (is_array($value) && $field == 'location') {
                                 // fix header for location type case
                                 foreach ($value as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                         if (CRM_Utils_Array::value(1, $type)) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } else {
                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                 }
                                             }
                                         }
                                         $headerRows[] = $hdr;
                                     }
                                 }
                             } else {
                                 if (substr($field, 0, 5) == 'case_') {
                                     if ($query->_fields['case'][$field]['title']) {
                                         $headerRows[] = $query->_fields['case'][$field]['title'];
                                     } else {
                                         if ($query->_fields['activity'][$field]['title']) {
                                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                                         }
                                     }
                                 } else {
                                     if (array_key_exists($field, $contactRelationshipTypes)) {
                                         $relName = CRM_Utils_Array::value($field, $contactRelationshipTypes);
                                         foreach ($value as $relationField => $relationValue) {
                                             // below block is same as primary block (duplicate)
                                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                                 $headerRows[] = $relName . '-' . $relationQuery[$field]->_fields[$relationField]['title'];
                                             } else {
                                                 if ($relationField == 'phone_type_id') {
                                                     $headerRows[] = $relName . '-' . 'Phone Type';
                                                 } else {
                                                     if ($relationField == 'provider_id') {
                                                         $headerRows[] = $relName . '-' . 'Im Service Provider';
                                                     } else {
                                                         if (is_array($relationValue) && $relationField == 'location') {
                                                             // fix header for location type case
                                                             foreach ($relationValue as $ltype => $val) {
                                                                 foreach (array_keys($val) as $fld) {
                                                                     $type = explode('-', $fld);
                                                                     $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                                                     if (CRM_Utils_Array::value(1, $type)) {
                                                                         if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                                             $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                                                         } else {
                                                                             if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                                             }
                                                                         }
                                                                     }
                                                                     $headerRows[] = $relName . '-' . $hdr;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         $headerRows[] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             //build row values (data)
             if (property_exists($dao, $field)) {
                 $fieldValue = $dao->{$field};
                 // to get phone type from phone type id
                 if ($field == 'phone_type_id') {
                     $fieldValue = $phoneTypes[$fieldValue];
                 } else {
                     if ($field == 'provider_id') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     }
                 }
             } else {
                 $fieldValue = '';
             }
             if ($field == 'id') {
                 $row[$field] = $dao->contact_id;
             } else {
                 if ($field == 'pledge_balance_amount') {
                     //special case for calculated field
                     $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                 } else {
                     if ($field == 'pledge_next_pay_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                     } else {
                         if (is_array($value) && $field == 'location') {
                             // fix header for location type case
                             foreach ($value as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (CRM_Utils_Array::value(1, $type)) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     $row[$fldValue] = $dao->{$fldValue};
                                 }
                             }
                         } else {
                             if (array_key_exists($field, $contactRelationshipTypes)) {
                                 $relDAO = $allRelContactArray[$field][$dao->contact_id];
                                 foreach ($value as $relationField => $relationValue) {
                                     if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                                         $fieldValue = $relDAO->{$relationField};
                                         if ($relationField == 'phone_type_id') {
                                             $fieldValue = $phoneTypes[$relationValue];
                                         } else {
                                             if ($relationField == 'provider_id') {
                                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                                             }
                                         }
                                     } else {
                                         $fieldValue = '';
                                     }
                                     if ($relationField == 'id') {
                                         $row[$field . $relationField] = $relDAO->contact_id;
                                     } else {
                                         if (is_array($relationValue) && $relationField == 'location') {
                                             foreach ($relationValue as $ltype => $val) {
                                                 foreach (array_keys($val) as $fld) {
                                                     $type = explode('-', $fld);
                                                     $fldValue = "{$ltype}-" . $type[0];
                                                     if (CRM_Utils_Array::value(1, $type)) {
                                                         $fldValue .= "-" . $type[1];
                                                     }
                                                     $row[$field . $fldValue] = $relDAO->{$fldValue};
                                                 }
                                             }
                                         } else {
                                             if (isset($fieldValue) && $fieldValue != '') {
                                                 //check for custom data
                                                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                                     $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                                                 } else {
                                                     if (in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                         //special case for greeting replacement
                                                         $fldValue = "{$relationField}_display";
                                                         $row[$field . $relationField] = $relDAO->{$fldValue};
                                                     } else {
                                                         //normal relationship fields
                                                         $row[$field . $relationField] = $fieldValue;
                                                     }
                                                 }
                                             } else {
                                                 // if relation field is empty or null
                                                 $row[$field . $relationField] = '';
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if (isset($fieldValue) && $fieldValue != '') {
                                     //check for custom data
                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                                     } else {
                                         if (array_key_exists($field, $multipleSelectFields)) {
                                             //option group fixes
                                             $paramsNew = array($field => $fieldValue);
                                             if ($field == 'test_tutoring') {
                                                 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                             } else {
                                                 if (substr($field, 0, 4) == 'cmr_') {
                                                     //for  readers group
                                                     $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                                                 } else {
                                                     $name = array($field => array('newName' => $field, 'groupName' => $field));
                                                 }
                                             }
                                             CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                                             $row[$field] = $paramsNew[$field];
                                         } else {
                                             if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                 //special case for greeting replacement
                                                 $fldValue = "{$field}_display";
                                                 $row[$field] = $dao->{$fldValue};
                                             } else {
                                                 //normal fields
                                                 $row[$field] = $fieldValue;
                                             }
                                         }
                                     }
                                 } else {
                                     // if field is empty or null
                                     $row[$field] = '';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //build header only once
         $setHeader = false;
         // add payment headers if required
         if ($addPaymentHeader && $paymentFields) {
             $headerRows = array_merge($headerRows, $paymentHeaders);
             $addPaymentHeader = false;
         }
         // add payment related information
         if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
             $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
         }
         //remove organization name for individuals if it is set for current employer
         if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') {
             $row['organization_name'] = '';
         }
         // CRM-3157: localise the output
         // FIXME: we should move this to multilingual stack some day
         require_once 'CRM/Core/I18n.php';
         $i18n =& CRM_Core_I18n::singleton();
         $translatable = array('preferred_communication_method', 'preferred_mail_format', 'gender', 'state_province', 'country', 'world_region');
         foreach ($translatable as $column) {
             if (isset($row[$column]) and $row[$column]) {
                 $row[$column] = $i18n->translate($row[$column]);
             }
         }
         // add component info
         $componentDetails[] = $row;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails);
     exit;
 }
Example #22
0
 /**
  * Process the mapped fields and map it into the uploaded file
  * preview the file and extract some summary statistics
  *
  * @return void
  * @access public
  */
 function postProcess()
 {
     $fileName = $this->controller->exportValue('UploadFile', 'uploadFile');
     $skipColumnHeader = $this->controller->exportValue('UploadFile', 'skipColumnHeader');
     $invalidRowCount = $this->get('invalidRowCount');
     $conflictRowCount = $this->get('conflictRowCount');
     $onDuplicate = $this->get('onDuplicate');
     $newGroup = $this->controller->exportValue($this->_name, 'newGroup');
     $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName');
     $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc');
     $groups = $this->controller->exportValue($this->_name, 'groups');
     $allGroups = $this->get('groups');
     $tagForContact = $this->controller->exportValue($this->_name, 'tag');
     $allTags = $this->get('tag');
     $seperator = ',';
     $mapper = $this->controller->exportValue('MapField', 'mapper');
     $mapperKeys = array();
     $mapperLocTypes = array();
     $mapperPhoneTypes = array();
     $mapperRelated = array();
     $mapperRelatedContactType = array();
     $mapperRelatedContactDetails = array();
     $mapperRelatedContactLocType = array();
     $mapperRelatedContactPhoneType = array();
     foreach ($mapper as $key => $value) {
         $mapperKeys[$key] = $mapper[$key][0];
         if (is_numeric($mapper[$key][1])) {
             $mapperLocTypes[$key] = $mapper[$key][1];
         } else {
             $mapperLocTypes[$key] = null;
         }
         if (!is_numeric($mapper[$key][2])) {
             $mapperPhoneTypes[$key] = $mapper[$key][2];
         } else {
             $mapperPhoneTypes[$key] = null;
         }
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             eval('$mapperRelatedContactType[$key] = $relationType->contact_type_' . $second . ';');
             $mapperRelated[$key] = $mapper[$key][0];
             $mapperRelatedContactDetails[$key] = $mapper[$key][1];
             $mapperRelatedContactLocType[$key] = $mapper[$key][2];
             $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
         } else {
             $mapperRelated[$key] = null;
             $mapperRelatedContactType[$key] = null;
             $mapperRelatedContactDetails[$key] = null;
             $mapperRelatedContactLocType[$key] = null;
             $mapperRelatedContactPhoneType[$key] = null;
         }
     }
     $parser =& new CRM_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType);
     $mapFields = $this->get('fields');
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $phoneTypes = CRM_Core_SelectValues::phoneType();
     foreach ($mapper as $key => $value) {
         $header = array();
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             $header[] = $relationType->name_a_b;
             $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
             if (isset($mapper[$key][2])) {
                 $header[] = $locationTypes[$mapper[$key][2]];
             }
             if (isset($mapper[$key][3])) {
                 $header[] = $phoneTypes[$mapper[$key][3]];
             }
         } else {
             if (isset($mapFields[$mapper[$key][0]])) {
                 $header[] = $mapFields[$mapper[$key][0]];
                 if (isset($mapper[$key][1])) {
                     $header[] = $locationTypes[$mapper[$key][1]];
                 }
                 if (isset($mapper[$key][2])) {
                     $header[] = $phoneTypes[$mapper[$key][2]];
                 }
             }
         }
         $mapperFields[] = implode(' - ', $header);
     }
     $parser->run($fileName, $seperator, $mapperFields, $skipColumnHeader, CRM_IMPORT_PARSER_MODE_IMPORT, $this->get('contactType'), $onDuplicate);
     // add the new contacts to selected groups
     $contactIds =& $parser->getImportedContacts();
     // add the new related contacts to selected groups
     $relatedContactIds =& $parser->getRelatedImportedContacts();
     $this->set('relatedCount', count($relatedContactIds));
     $newGroupId = null;
     //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
     if ($newGroupName) {
         /* Create a new group */
         $gParams = array('domain_id' => CRM_Core_Config::domainID(), 'name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => true);
         $group =& CRM_Contact_BAO_Group::create($gParams);
         $groups[] = $newGroupId = $group->id;
     }
     if (is_array($groups)) {
         $groupAdditions = array();
         foreach ($groups as $groupId) {
             $addCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             if (!empty($relatedContactIds)) {
                 $addRelCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId);
             }
             $totalCount = $addCount[1] + $addRelCount[1];
             if ($groupId == $newGroupId) {
                 $name = $newGroupName;
                 $new = true;
             } else {
                 $name = $allGroups[$groupId];
                 $new = false;
             }
             $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2], 'new' => $new);
         }
         $this->set('groupAdditions', $groupAdditions);
     }
     if (is_array($tagForContact)) {
         $tagAddition = array();
         require_once "CRM/Core/BAO/EntityTag.php";
         foreach ($tagForContact as $tagId => $selected) {
             $taggedContacts = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId);
             $tagName = $allTags[$tagId];
             $tagAdditions[] = array('name' => $tagName, 'added' => $taggedContacts[1], 'notAdded' => $taggedContacts[2]);
         }
         $this->set('tagAdditions', $tagAdditions);
     }
     // add all the necessary variables to the form
     $parser->set($this, CRM_IMPORT_PARSER_MODE_IMPORT);
     // check if there is any error occured
     $errorStack =& CRM_Core_Error::singleton();
     $errors = $errorStack->getErrors();
     $errorMessage = array();
     $config =& CRM_Core_Config::singleton();
     if (is_array($errors)) {
         foreach ($errors as $key => $value) {
             $errorMessage[] = $value['message'];
         }
         $errorFile = $fileName . '.error.log';
         if ($fd = fopen($errorFile, 'w')) {
             fwrite($fd, implode('\\n', $errorMessage));
         }
         fclose($fd);
         $this->set('errorFile', $errorFile);
         $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=1'));
         $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=2'));
         $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=4'));
     }
 }
Example #23
0
/**
 * function convert params to v3.0 format before add location.
 */
function _civicrm_format_params_v2_to_v3(&$params, $locationTypeId = null)
{
    // get the loc type id.
    if (!$locationTypeId) {
        // get location type.
        $locationTypeId = CRM_Utils_Array::value('location_type_id', $params);
        if (!$locationTypeId && array_key_exists('location_type', $params)) {
            require_once 'CRM/Core/PseudoConstant.php';
            $locTypes =& CRM_Core_PseudoConstant::locationType();
            $locType = $params['location_type'];
            if (is_array($params['location_type'])) {
                $locType = array_pop($params['location_type']);
            }
            $locationTypeId = CRM_Utils_Array::key($locType, $locTypes);
        }
    }
    // convert params into v3.0 format.
    $primary = $billing = array();
    $blocks = array('Email', 'Phone', 'IM', 'OpenID');
    // format params array.
    $firstBlockCount = null;
    foreach ($blocks as $block) {
        require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_DAO_" . $block) . ".php";
        eval('$fields =& CRM_Core_DAO_' . $block . '::fields( );');
        $name = strtolower($block);
        $blockCount = 0;
        if (CRM_Utils_Array::value($name, $params)) {
            if (is_array($params[$name])) {
                $values = $params[$name];
                $params[$name] = array();
                foreach ($values as $val) {
                    _civicrm_store_values($fields, $val, $params[$name][++$blockCount]);
                    // check for primary and billing.
                    if (CRM_Utils_Array::value('is_primary', $val)) {
                        $primary[$name][$blockCount] = true;
                    }
                    if (CRM_Utils_Array::value('is_billing', $val)) {
                        $primary[$name][$blockCount] = true;
                    }
                    if (!$firstBlockCount) {
                        $firstBlockCount = $blockCount;
                    }
                }
            } else {
                //need to get ids.
                if (in_array($name, array('im', 'phone'))) {
                    require_once 'CRM/Core/PseudoConstant.php';
                    if ($name == 'im') {
                        CRM_Utils_Array::lookupValue($params, 'provider', CRM_Core_PseudoConstant::IMProvider(), true);
                    } else {
                        CRM_Utils_Array::lookupValue($params, 'phone_type', CRM_Core_PseudoConstant::phoneType(), true);
                    }
                }
                $locValues[$name] = array();
                _civicrm_store_values($fields, $params, $locValues[$name][++$blockCount]);
                $params[$name] = $locValues[$name];
                $firstBlockCount = $blockCount;
                unset($locValues[$name]);
            }
            // make first block as default primary when is_primary
            // is not set in sub array and set in main params array.
            if (!CRM_Utils_Array::value($name, $primary) && CRM_Utils_Array::value('is_primary', $params)) {
                $primary[$name][$firstBlockCount] = true;
                $params[$name][$firstBlockCount]['is_primary'] = true;
            }
            if (!CRM_Utils_Array::value($name, $billing) && CRM_Utils_Array::value('is_billing', $params)) {
                $billing[$name][$firstBlockCount] = true;
                $params[$name][$firstBlockCount]['is_billing'] = true;
            }
        }
    }
    //get the address fields.
    $addressCount = 1;
    $ids = array('county', 'country_id', 'country', 'state_province_id', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name', 'city', 'street_address');
    $addressTaken = false;
    foreach ($ids as $id) {
        if (array_key_exists($id, $params)) {
            if (!$addressTaken) {
                require_once 'CRM/Core/DAO/Address.php';
                $fields =& CRM_Core_DAO_Address::fields();
                _civicrm_store_values($fields, $params, $params['address'][$addressCount]);
                $addressTaken = true;
            }
            $params['address'][$addressCount][$id] = $params[$id];
            unset($params[$id]);
        }
    }
    // format state and country.
    foreach (array('state_province', 'country') as $field) {
        $fName = $field == 'state_province' ? 'stateProvinceAbbreviation' : 'countryIsoCode';
        if (CRM_Utils_Array::value('address', $params) && CRM_Utils_Array::value($field, $params['address'][$addressCount]) && is_numeric($params['address'][$addressCount][$field])) {
            $fValue =& $params['address'][$addressCount][$field];
            eval('$fValue = CRM_Core_PseudoConstant::' . $fName . '( $fValue );');
            //kill the reference.
            unset($fValue);
        }
    }
    // check for primary address.
    if (CRM_Utils_Array::value('is_primary', $params)) {
        if ($addressTaken) {
            $primary['address'][$addressCount] = true;
            $params['address'][$addressCount]['is_primary'] = true;
        }
        unset($params['is_primary']);
    }
    if (CRM_Utils_Array::value('is_billing', $params)) {
        if ($addressTaken) {
            $billing['address'][$addressCount] = true;
            $params['address'][$addressCount]['is_billing'] = true;
        }
        unset($params['is_billing']);
    }
    // handle primary and billing reset.
    foreach (array('email', 'phone', 'im', 'address', 'openid') as $name) {
        if (!array_key_exists($name, $params) || CRM_Utils_System::isNull($params[$name])) {
            continue;
        }
        $errorMsg = null;
        $primaryBlockIndex = $billingBlockIndex = 0;
        if (array_key_exists($name, $primary)) {
            if (count($primary[$name]) > 1) {
                $errorMsg .= ts("<br />Multiple Primary %1.", array(1 => $block));
            } else {
                $primaryBlockIndex = key($primary[$name]);
            }
        }
        if (array_key_exists($name, $billing)) {
            if (count($billing[$name]) > 1) {
                $errorMsg .= ts("<br />Multiple Billing %1.", array(1 => $block));
            } else {
                $billingBlockIndex = key($billing[$name]);
            }
        }
        if ($errorMsg) {
            return civicrm_create_error($errorMsg);
        }
        foreach ($params[$name] as $count => &$values) {
            if ($primaryBlockIndex && $count != $primaryBlockIndex) {
                $values['is_primary'] = false;
            }
            if ($billingBlockIndex && $count != $billingBlockIndex) {
                $values['is_billing'] = false;
            }
            // get location type if not present in sub array.
            if (!CRM_Utils_Array::value('location_type_id', $values)) {
                $values['location_type_id'] = $locationTypeId;
            }
            //kill the reference.
            unset($values);
        }
    }
    // finally unset location_type and location type id.
    foreach (array('location_type', 'location_type_id') as $f) {
        if (isset($params[$f])) {
            unset($params[$f]);
        }
    }
    return $params;
}
Example #24
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 public function buildQuickForm()
 {
     require_once "CRM/Core/BAO/Mapping.php";
     require_once "CRM/Core/OptionGroup.php";
     //to save the current mappings
     if (!$this->get('savedMapping')) {
         $saveDetailsName = ts('Save this field mapping');
         $this->applyFilter('saveMappingName', 'trim');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     } else {
         $savedMapping = $this->get('savedMapping');
         list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
         $mappingName = $mappingName[1];
         $mappingContactType = $mappingContactType[1];
         $mappingLocation = CRM_Utils_Array::value('1', $mappingLocation[1]);
         $mappingPhoneType = CRM_Utils_Array::value('1', $mappingPhoneType[1]);
         $mappingRelation = CRM_Utils_Array::value('1', $mappingRelation[1]);
         //mapping is to be loaded from database
         $params = array('id' => $savedMapping);
         $temp = array();
         $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
         $this->assign('loadedMapping', $mappingDetails->name);
         $this->set('loadedMapping', $savedMapping);
         $getMappingName =& new CRM_Core_DAO_Mapping();
         $getMappingName->id = $savedMapping;
         $getMappingName->mapping_type = 'Import Contributions';
         $getMappingName->find();
         while ($getMappingName->fetch()) {
             $mapperName = $getMappingName->name;
         }
         $this->assign('savedName', $mapperName);
         $this->add('hidden', 'mappingId', $savedMapping);
         $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), null);
         $saveDetailsName = ts('Save as a new field mapping');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     }
     $this->addElement('checkbox', 'saveMapping', $saveDetailsName, null, array('onclick' => "showSaveDetails(this)"));
     $this->addFormRule(array('CRM_Contribute_Import_Form_MapField', 'formRule'), $this);
     //-------- end of saved mapping stuff ---------
     $defaults = array();
     $mapperKeys = array_keys($this->_mapperFields);
     $hasHeaders = !empty($this->_columnHeaders);
     $headerPatterns = $this->get('headerPatterns');
     $dataPatterns = $this->get('dataPatterns');
     $hasLocationTypes = $this->get('fieldTypes');
     /* Initialize all field usages to false */
     foreach ($mapperKeys as $key) {
         $this->_fieldUsed[$key] = false;
     }
     $this->_location_types =& CRM_Core_PseudoConstant::locationType();
     $sel1 = $this->_mapperFields;
     if (!$this->get('onDuplicate')) {
         unset($sel1['id']);
         unset($sel1['contribution_id']);
     }
     // start of soft credit section
     // get contact type for this import
     $contactTypeId = $this->get('contactType');
     $contactTypes = array(CRM_Contribute_Import_Parser::CONTACT_INDIVIDUAL => 'Individual', CRM_Contribute_Import_Parser::CONTACT_HOUSEHOLD => 'Household', CRM_Contribute_Import_Parser::CONTACT_ORGANIZATION => 'Organization');
     $contactType = $contactTypes[$contactTypeId];
     // get imporatable fields for contact type
     require_once 'CRM/Contact/BAO/Contact.php';
     $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, null);
     // get the Dedupe rule for this contact type and build soft credit array
     $ruleParams = array('contact_type' => $contactType, 'level' => 'Strict');
     require_once 'CRM/Dedupe/BAO/Rule.php';
     $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
     $softCreditFields = array();
     if (is_array($fieldsArray)) {
         foreach ($fieldsArray as $value) {
             //skip if there is no dupe rule
             if ($value == 'none') {
                 continue;
             }
             $softCreditFields[$value] = $contactFields[trim($value)]['title'];
         }
     }
     $softCreditFields['contact_id'] = ts('Contact ID');
     $softCreditFields['external_identifier'] = ts('External Identifier');
     $sel2['soft_credit'] = $softCreditFields;
     // end of soft credit section
     $js = "<script type='text/javascript'>\n";
     $formName = 'document.forms.' . $this->_name;
     //used to warn for mismatch column count or mismatch mapping
     $warning = 0;
     for ($i = 0; $i < $this->_columnCount; $i++) {
         $sel =& $this->addElement('hierselect', "mapper[{$i}]", ts('Mapper for Field %1', array(1 => $i)), null);
         $jsSet = false;
         if ($this->get('savedMapping')) {
             if (isset($mappingName[$i])) {
                 if ($mappingName[$i] != ts('- do not import -')) {
                     $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
                     // reusing contact_type field array for soft credit
                     $softField = isset($mappingContactType[$i]) ? $mappingContactType[$i] : 0;
                     if (!$softField) {
                         $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n";
                     }
                     $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n";
                     $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n";
                     $defaults["mapper[{$i}]"] = array($mappingHeader[0], $softField ? $softField : "", isset($locationId) ? $locationId : "", isset($phoneType) ? $phoneType : "");
                     $jsSet = true;
                 } else {
                     $defaults["mapper[{$i}]"] = array();
                 }
                 if (!$jsSet) {
                     for ($k = 1; $k < 4; $k++) {
                         $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n";
                     }
                 }
             } else {
                 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
                 $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_" . $i . "_');\n";
                 if ($hasHeaders) {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
                 } else {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i));
                 }
             }
             //end of load mapping
         } else {
             $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_" . $i . "_');\n";
             if ($hasHeaders) {
                 // Infer the default from the skipped headers if we have them
                 $defaults["mapper[{$i}]"] = array($this->defaultFromHeader(CRM_Utils_Array::value($i, $this->_columnHeaders), $headerPatterns), 0);
             } else {
                 // Otherwise guess the default from the form of the data
                 $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i), 0);
             }
         }
         $sel->setOptions(array($sel1, $sel2, isset($sel3) ? $sel3 : "", isset($sel4) ? $sel4 : ""));
     }
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     //set warning if mismatch in more than
     if (isset($mappingName)) {
         if ($this->_columnCount != count($mappingName)) {
             $warning++;
         }
     }
     if ($warning != 0 && $this->get('savedMapping')) {
         $session = CRM_Core_Session::singleton();
         $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
     } else {
         $session = CRM_Core_Session::singleton();
         $session->setStatus(null);
     }
     $this->setDefaults($defaults);
     $this->addButtons(array(array('type' => 'back', 'name' => ts('<< Previous')), array('type' => 'next', 'name' => ts('Continue >>'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
 }
Example #25
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 public function buildQuickForm()
 {
     require_once "CRM/Core/BAO/Mapping.php";
     require_once "CRM/Core/OptionGroup.php";
     //to save the current mappings
     if (!$this->get('savedMapping')) {
         $saveDetailsName = ts('Save this field mapping');
         $this->applyFilter('saveMappingName', 'trim');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     } else {
         $savedMapping = $this->get('savedMapping');
         list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
         $mappingName = $mappingName[1];
         $mappingContactType = $mappingContactType[1];
         $mappingLocation = CRM_Utils_Array::value('1', $mappingLocation);
         $mappingPhoneType = CRM_Utils_Array::value('1', $mappingPhoneType);
         $mappingRelation = CRM_Utils_Array::value('1', $mappingRelation);
         //mapping is to be loaded from database
         $params = array('id' => $savedMapping);
         $temp = array();
         $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
         $this->assign('loadedMapping', $mappingDetails->name);
         $this->set('loadedMapping', $savedMapping);
         $getMappingName =& new CRM_Core_DAO_Mapping();
         $getMappingName->id = $savedMapping;
         $getMappingName->mapping_type = 'Import Participants';
         $getMappingName->find();
         while ($getMappingName->fetch()) {
             $mapperName = $getMappingName->name;
         }
         $this->assign('savedName', $mapperName);
         $this->add('hidden', 'mappingId', $savedMapping);
         $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), null);
         $saveDetailsName = ts('Save as a new field mapping');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     }
     $this->addElement('checkbox', 'saveMapping', $saveDetailsName, null, array('onclick' => "showSaveDetails(this)"));
     $this->addFormRule(array('CRM_Event_Import_Form_MapField', 'formRule'), $this);
     $defaults = array();
     $mapperKeys = array_keys($this->_mapperFields);
     $hasHeaders = !empty($this->_columnHeaders);
     $headerPatterns = $this->get('headerPatterns');
     $dataPatterns = $this->get('dataPatterns');
     $hasLocationTypes = $this->get('fieldTypes');
     /* Initialize all field usages to false */
     foreach ($mapperKeys as $key) {
         $this->_fieldUsed[$key] = false;
     }
     $this->_location_types =& CRM_Core_PseudoConstant::locationType();
     $sel1 = $this->_mapperFields;
     $sel2[''] = null;
     $js = "<script type='text/javascript'>\n";
     $formName = 'document.forms.' . $this->_name;
     //used to warn for mismatch column count or mismatch mapping
     $warning = 0;
     for ($i = 0; $i < $this->_columnCount; $i++) {
         $sel =& $this->addElement('hierselect', "mapper[{$i}]", ts('Mapper for Field %1', array(1 => $i)), null);
         $jsSet = false;
         if ($this->get('savedMapping')) {
             if (isset($mappingName[$i])) {
                 if ($mappingName[$i] != ts('- do not import -')) {
                     $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
                     if (!isset($locationId) || !$locationId) {
                         $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n";
                     }
                     if (!isset($phoneType) || !$phoneType) {
                         $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n";
                     }
                     $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n";
                     $defaults["mapper[{$i}]"] = array($mappingHeader[0], isset($locationId) ? $locationId : "", isset($phoneType) ? $phoneType : "");
                     $jsSet = true;
                 } else {
                     $defaults["mapper[{$i}]"] = array();
                 }
                 if (!$jsSet) {
                     for ($k = 1; $k < 4; $k++) {
                         $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n";
                     }
                 }
             } else {
                 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
                 $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_" . $i . "_');\n";
                 if ($hasHeaders) {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
                 } else {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i));
                 }
             }
             //end of load mapping
         } else {
             $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_" . $i . "_');\n";
             if ($hasHeaders) {
                 // Infer the default from the skipped headers if we have them
                 $defaults["mapper[{$i}]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns), 0);
             } else {
                 // Otherwise guess the default from the form of the data
                 $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i), 0);
             }
         }
         $sel->setOptions(array($sel1, $sel2, isset($sel3) ? $sel3 : "", isset($sel4) ? $sel4 : ""));
     }
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     //set warning if mismatch in more than
     if (isset($mappingName)) {
         if ($this->_columnCount != count($mappingName)) {
             $warning++;
         }
     }
     if ($warning != 0 && $this->get('savedMapping')) {
         $session =& CRM_Core_Session::singleton();
         $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
     } else {
         $session =& CRM_Core_Session::singleton();
         $session->setStatus(null);
     }
     $this->setDefaults($defaults);
     $this->addButtons(array(array('type' => 'back', 'name' => ts('<< Previous')), array('type' => 'next', 'name' => ts('Continue >>'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
 }
Example #26
0
 /**
  * Wrapper for getOptions / pseudoconstant to get contact type options.
  *
  * @return array
  */
 function getLocationTypeOptions() {
   if (method_exists('CRM_Core_PseudoConstant', 'locationType')) {
     return CRM_Core_PseudoConstant::locationType();
   }
   else {
     return $this->_getOptions('address', 'location_type_id');
   }
 }
Example #27
0
 /**  
  * Function to build the array for display the profile fields
  *  
  * @param array $params key value. 
  * @param int $gid profile Id
  * @param array $groupTitle Profile Group Title.
  * @param array $values formatted array of key value
  *
  * @return None  
  * @access public  
  */
 function displayProfile(&$params, $gid, &$groupTitle, &$values)
 {
     if ($gid) {
         require_once 'CRM/Core/BAO/UFGroup.php';
         require_once 'CRM/Profile/Form.php';
         require_once 'CRM/Event/PseudoConstant.php';
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         if ($contactID) {
             if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
                 $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::VIEW);
             }
         } else {
             $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::ADD);
         }
         if (is_array($fields)) {
             // unset any email-* fields since we already collect it, CRM-2888
             foreach (array_keys($fields) as $fieldName) {
                 if (substr($fieldName, 0, 6) == 'email-') {
                     unset($fields[$fieldName]);
                 }
             }
         }
         foreach ($fields as $v) {
             if (CRM_Utils_Array::value('groupTitle', $v)) {
                 $groupTitle['groupTitle'] = $v["groupTitle"];
                 break;
             }
         }
         $config = CRM_Core_Config::singleton();
         require_once 'CRM/Core/PseudoConstant.php';
         $locationTypes = $imProviders = array();
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $imProviders = CRM_Core_PseudoConstant::IMProvider();
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             $index = $field['title'];
             $customFieldName = null;
             if ($name === 'organization_name') {
                 $values[$index] = $params[$name];
             }
             if ('state_province' == substr($name, 0, 14)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } else {
                 if ('country' == substr($name, 0, 7)) {
                     if ($params[$name]) {
                         $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
                     } else {
                         $values[$index] = '';
                     }
                 } else {
                     if ('county' == substr($name, 0, 6)) {
                         if ($params[$name]) {
                             $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
                         } else {
                             $values[$index] = '';
                         }
                     } else {
                         if ('gender' == substr($name, 0, 6)) {
                             $gender = CRM_Core_PseudoConstant::gender();
                             $values[$index] = $gender[$params[$name]];
                         } else {
                             if ('individual_prefix' == substr($name, 0, 17)) {
                                 $prefix = CRM_Core_PseudoConstant::individualPrefix();
                                 $values[$index] = $prefix[$params[$name]];
                             } else {
                                 if ('individual_suffix' == substr($name, 0, 17)) {
                                     $suffix = CRM_Core_PseudoConstant::individualSuffix();
                                     $values[$index] = $suffix[$params[$name]];
                                 } else {
                                     if (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                                         $filterCondition = array('greeting_type' => $name);
                                         $greeting =& CRM_Core_PseudoConstant::greeting($filterCondition);
                                         $values[$index] = $greeting[$params[$name]];
                                     } else {
                                         if ($name === 'preferred_communication_method') {
                                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                                             $pref = array();
                                             $compref = array();
                                             $pref = $params[$name];
                                             if (is_array($pref)) {
                                                 foreach ($pref as $k => $v) {
                                                     if ($v) {
                                                         $compref[] = $communicationFields[$k];
                                                     }
                                                 }
                                             }
                                             $values[$index] = implode(",", $compref);
                                         } else {
                                             if ($name == 'group') {
                                                 require_once 'CRM/Contact/BAO/GroupContact.php';
                                                 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
                                                 $title = array();
                                                 foreach ($params[$name] as $gId => $dontCare) {
                                                     if ($dontCare) {
                                                         $title[] = $groups[$gId];
                                                     }
                                                 }
                                                 $values[$index] = implode(', ', $title);
                                             } else {
                                                 if ($name == 'tag') {
                                                     require_once 'CRM/Core/BAO/EntityTag.php';
                                                     $entityTags = $params[$name];
                                                     $allTags =& CRM_Core_PseudoConstant::tag();
                                                     $title = array();
                                                     if (is_array($entityTags)) {
                                                         foreach ($entityTags as $tagId => $dontCare) {
                                                             $title[] = $allTags[$tagId];
                                                         }
                                                     }
                                                     $values[$index] = implode(', ', $title);
                                                 } else {
                                                     if ('participant_role_id' == $name) {
                                                         $roles = CRM_Event_PseudoConstant::participantRole();
                                                         $values[$index] = $roles[$params[$name]];
                                                     } else {
                                                         if ('participant_status_id' == $name) {
                                                             $status = CRM_Event_PseudoConstant::participantStatus();
                                                             $values[$index] = $status[$params[$name]];
                                                         } else {
                                                             if (strpos($name, '-') !== false) {
                                                                 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
                                                                 $detailName = str_replace(' ', '_', $name);
                                                                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                                                                     $values[$index] = $params[$detailName];
                                                                     $idx = $detailName . '_id';
                                                                     $values[$index] = $params[$idx];
                                                                 } else {
                                                                     if ($fieldName == 'im') {
                                                                         $providerName = null;
                                                                         if ($providerId = $detailName . '-provider_id') {
                                                                             $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
                                                                         }
                                                                         if ($providerName) {
                                                                             $values[$index] = $params[$detailName] . " (" . $providerName . ")";
                                                                         } else {
                                                                             $values[$index] = $params[$detailName];
                                                                         }
                                                                     } else {
                                                                         $values[$index] = $params[$detailName];
                                                                     }
                                                                 }
                                                             } else {
                                                                 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                                                                     if ($params[$name]) {
                                                                         $values[$index] = '[ x ]';
                                                                     }
                                                                 } else {
                                                                     require_once 'CRM/Core/BAO/CustomField.php';
                                                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                                                         $query = "\nSELECT html_type, data_type\nFROM   civicrm_custom_field\nWHERE  id = {$cfID}\n";
                                                                         $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
                                                                         $dao->fetch();
                                                                         $htmlType = $dao->html_type;
                                                                         $dataType = $dao->data_type;
                                                                         if ($htmlType == 'File') {
                                                                             //$fileURL = CRM_Core_BAO_CustomField::getFileURL( $contactID, $cfID );
                                                                             //$params[$index] = $values[$index] = $fileURL['file_url'];
                                                                             $values[$index] = $params[$index];
                                                                         } else {
                                                                             if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') {
                                                                                 $customVal = (int) $params[$name];
                                                                             } else {
                                                                                 if ($dao->data_type == 'Float') {
                                                                                     $customVal = (double) $params[$name];
                                                                                 } else {
                                                                                     if ($dao->data_type == 'Date') {
                                                                                         $date = CRM_Utils_Date::format($params[$name], null, 'invalidDate');
                                                                                         if ($date != 'invalidDate') {
                                                                                             $customVal = $date;
                                                                                         }
                                                                                     } else {
                                                                                         $customVal = $params[$name];
                                                                                     }
                                                                                 }
                                                                             }
                                                                             //take the custom field options
                                                                             $returnProperties = array($name => 1);
                                                                             require_once 'CRM/Contact/BAO/Query.php';
                                                                             $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
                                                                             $options =& $query->_options;
                                                                             $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                                                                             //Hack since we dont have function to check empty.
                                                                             //FIXME in 2.3 using crmIsEmptyArray()
                                                                             $customValue = true;
                                                                             if (is_array($customVal) && is_array($displayValue)) {
                                                                                 $customValue = array_diff($customVal, $displayValue);
                                                                             }
                                                                             //use difference of arrays
                                                                             if (empty($customValue) || !$customValue) {
                                                                                 $values[$index] = '';
                                                                             } else {
                                                                                 $values[$index] = $displayValue;
                                                                             }
                                                                             if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                                                                 $customFieldName = "{$name}_from";
                                                                             }
                                                                         }
                                                                     } else {
                                                                         if ($name == 'home_URL' && !empty($params[$name])) {
                                                                             $url = CRM_Utils_System::fixURL($params[$name]);
                                                                             $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>";
                                                                         } else {
                                                                             if (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) {
                                                                                 require_once 'CRM/Utils/Date.php';
                                                                                 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
                                                                             } else {
                                                                                 $values[$index] = $params[$name];
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #28
0
 /**
  * View summary details of a contact
  *
  * @return void
  * @access public
  */
 function view()
 {
     $session = CRM_Core_Session::singleton();
     $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $this->_contactId);
     $session->pushUserContext($url);
     $params = array();
     $defaults = array();
     $ids = array();
     $params['id'] = $params['contact_id'] = $this->_contactId;
     $params['noRelationships'] = $params['noNotes'] = $params['noGroups'] = true;
     $contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults, true);
     $communicationType = array('phone' => array('type' => 'phoneType', 'id' => 'phone_type'), 'im' => array('type' => 'IMProvider', 'id' => 'provider'), 'website' => array('type' => 'websiteType', 'id' => 'website_type'), 'address' => array('skip' => true, 'customData' => 1), 'email' => array('skip' => true), 'openid' => array('skip' => true));
     foreach ($communicationType as $key => $value) {
         if (CRM_Utils_Array::value($key, $defaults)) {
             foreach ($defaults[$key] as &$val) {
                 CRM_Utils_Array::lookupValue($val, 'location_type', CRM_Core_PseudoConstant::locationType(), false);
                 if (!CRM_Utils_Array::value('skip', $value)) {
                     eval('$pseudoConst = CRM_Core_PseudoConstant::' . $value['type'] . '( );');
                     CRM_Utils_Array::lookupValue($val, $value['id'], $pseudoConst, false);
                 }
             }
             if (isset($value['customData'])) {
                 foreach ($defaults[$key] as $blockId => $blockVal) {
                     $groupTree = CRM_Core_BAO_CustomGroup::getTree(ucfirst($key), $this, $blockVal['id']);
                     // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var.
                     $defaults[$key][$blockId]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, false, null, "dnc_");
                 }
                 // reset template variable since that won't be of any use, and could be misleading
                 $this->assign("dnc_viewCustomData", null);
             }
         }
     }
     if (CRM_Utils_Array::value('gender_id', $defaults)) {
         $gender = CRM_Core_PseudoConstant::gender();
         $defaults['gender_display'] = $gender[CRM_Utils_Array::value('gender_id', $defaults)];
     }
     // to make contact type label available in the template -
     $contactType = array_key_exists('contact_sub_type', $defaults) ? $defaults['contact_sub_type'] : $defaults['contact_type'];
     $defaults['contact_type_label'] = CRM_Contact_BAO_ContactType::contactTypePairs(true, $contactType);
     // get contact tags
     require_once 'CRM/Core/BAO/EntityTag.php';
     $contactTags = CRM_Core_BAO_EntityTag::getContactTags($this->_contactId);
     if (!empty($contactTags)) {
         $defaults['contactTag'] = implode(', ', $contactTags);
     }
     $defaults['privacy_values'] = CRM_Core_SelectValues::privacy();
     //Show blocks only if they are visible in edit form
     require_once 'CRM/Core/BAO/Preferences.php';
     $this->_editOptions = CRM_Core_BAO_Preferences::valueOptions('contact_edit_options');
     $configItems = array('CommBlock' => 'Communication Preferences', 'Demographics' => 'Demographics', 'TagsAndGroups' => 'Tags and Groups', 'Notes' => 'Notes');
     foreach ($configItems as $c => $t) {
         $varName = '_show' . $c;
         $this->{$varName} = CRM_Utils_Array::value($c, $this->_editOptions);
         $this->assign(substr($varName, 1), $this->{$varName});
     }
     // get contact name of shared contact names
     $sharedAddresses = array();
     $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']);
     foreach ($defaults['address'] as $key => $addressValue) {
         if (CRM_Utils_Array::value('master_id', $addressValue) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
             $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']);
         }
     }
     $this->assign('sharedAddresses', $sharedAddresses);
     //get the current employer name
     if (CRM_Utils_Array::value('contact_type', $defaults) == 'Individual') {
         if ($contact->employer_id && $contact->organization_name) {
             $defaults['current_employer'] = $contact->organization_name;
             $defaults['current_employer_id'] = $contact->employer_id;
         }
         //for birthdate format with respect to birth format set
         $this->assign('birthDateViewFormat', CRM_Utils_Array::value('qfMapping', CRM_Utils_Date::checkBirthDateFormat()));
     }
     $this->assign($defaults);
     // also assign the last modifed details
     require_once 'CRM/Core/BAO/Log.php';
     $lastModified =& CRM_Core_BAO_Log::lastModified($this->_contactId, 'civicrm_contact');
     $this->assign_by_ref('lastModified', $lastModified);
     $allTabs = array();
     $weight = 10;
     $this->_viewOptions = CRM_Core_BAO_Preferences::valueOptions('contact_view_options', true);
     $changeLog = $this->_viewOptions['log'];
     $this->assign_by_ref('changeLog', $changeLog);
     require_once 'CRM/Core/Component.php';
     $components = CRM_Core_Component::getEnabledComponents();
     foreach ($components as $name => $component) {
         if (CRM_Utils_Array::value($name, $this->_viewOptions) && CRM_Core_Permission::access($component->name)) {
             $elem = $component->registerTab();
             // FIXME: not very elegant, probably needs better approach
             // allow explicit id, if not defined, use keyword instead
             if (array_key_exists('id', $elem)) {
                 $i = $elem['id'];
             } else {
                 $i = $component->getKeyword();
             }
             $u = $elem['url'];
             //appending isTest to url for test soft credit CRM-3891.
             //FIXME: hack ajax url.
             $q = "reset=1&snippet=1&force=1&cid={$this->_contactId}";
             if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) {
                 $q = $q . "&isTest=1";
             }
             $allTabs[] = array('id' => $i, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$u}", $q), 'title' => $elem['title'], 'weight' => $elem['weight'], 'count' => CRM_Contact_BAO_Contact::getCountComponent($u, $this->_contactId));
             // make sure to get maximum weight, rest of tabs go after
             // FIXME: not very elegant again
             if ($weight < $elem['weight']) {
                 $weight = $elem['weight'];
             }
         }
     }
     $rest = array('activity' => ts('Activities'), 'case' => ts('Cases'), 'rel' => ts('Relationships'), 'group' => ts('Groups'), 'note' => ts('Notes'), 'tag' => ts('Tags'), 'log' => ts('Change Log'));
     $config = CRM_Core_Config::singleton();
     if (isset($config->sunlight) && $config->sunlight) {
         $title = ts('Elected Officials');
         $rest['sunlight'] = $title;
         $this->_viewOptions[$title] = true;
     }
     foreach ($rest as $k => $v) {
         if (CRM_Utils_Array::value($k, $this->_viewOptions)) {
             $allTabs[] = array('id' => $k, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$k}", "reset=1&snippet=1&cid={$this->_contactId}"), 'title' => $v, 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($k, $this->_contactId));
             $weight += 10;
         }
     }
     // now add all the custom tabs
     $entityType = $this->get('contactType');
     $activeGroups = CRM_Core_BAO_CustomGroup::getActiveGroups($entityType, 'civicrm/contact/view/cd', $this->_contactId);
     foreach ($activeGroups as $group) {
         $id = "custom_{$group['id']}";
         $allTabs[] = array('id' => $id, 'url' => CRM_Utils_System::url($group['path'], $group['query'] . "&snippet=1&selectedChild={$id}"), 'title' => $group['title'], 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($id, $this->_contactId, $group['table_name']));
         $weight += 10;
     }
     // see if any other modules want to add any tabs
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::tabs($allTabs, $this->_contactId);
     // now sort the tabs based on weight
     require_once 'CRM/Utils/Sort.php';
     usort($allTabs, array('CRM_Utils_Sort', 'cmpFunc'));
     $this->assign('allTabs', $allTabs);
     $selectedChild = CRM_Utils_Request::retrieve('selectedChild', 'String', $this, false, 'summary');
     $this->assign('selectedChild', $selectedChild);
     // hook for contact summary
     require_once 'CRM/Utils/Hook.php';
     $contentPlacement = CRM_Utils_Hook::SUMMARY_BELOW;
     // ignored but needed to prevent warnings
     CRM_Utils_Hook::summary($this->_contactId, $content, $contentPlacement);
     if ($content) {
         $this->assign_by_ref('hookContent', $content);
         $this->assign('hookContentPlacement', $contentPlacement);
     }
 }
Example #29
0
 function blockSetDefaults(&$defaults)
 {
     $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::locationType()), 'is_int');
     sort($locationTypeKeys);
     // get the default location type
     require_once 'CRM/Core/BAO/LocationType.php';
     $locationType = CRM_Core_BAO_LocationType::getDefault();
     // unset primary location type
     $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys);
     unset($locationTypeKeys[$primaryLocationTypeIdKey]);
     // reset the array sequence
     $locationTypeKeys = array_values($locationTypeKeys);
     // get default phone and im provider id.
     require_once 'CRM/Core/OptionGroup.php';
     $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', false, false, false, ' AND is_default = 1'));
     $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service', false, false, false, ' AND is_default = 1'));
     $allBlocks = $this->_blocks;
     if (array_key_exists('Address', $this->_editOptions)) {
         $allBlocks['Address'] = $this->_editOptions['Address'];
     }
     $config =& CRM_Core_Config::singleton();
     foreach ($allBlocks as $blockName => $label) {
         $name = strtolower($blockName);
         if (array_key_exists($name, $defaults) && !CRM_Utils_System::isNull($defaults[$name])) {
             continue;
         }
         for ($instance = 1; $instance <= $this->get($blockName . "_Block_Count"); $instance++) {
             //set location to primary for first one.
             if ($instance == 1) {
                 $defaults[$name][$instance]['is_primary'] = true;
                 $defaults[$name][$instance]['location_type_id'] = $locationType->id;
             } else {
                 $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id;
                 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
             }
             //set default country
             if ($name == 'address' && $config->defaultContactCountry) {
                 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry;
             }
             //set default phone type.
             if ($name == 'phone' && $defPhoneTypeId) {
                 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
             }
             //set default im provider.
             if ($name == 'im' && $defIMProviderId) {
                 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
             }
         }
     }
     // set defaults for country-state widget
     if (CRM_Utils_Array::value('address', $defaults) && is_array($defaults['address'])) {
         require_once 'CRM/Contact/Form/Edit/Address.php';
         foreach ($defaults['address'] as $blockId => $values) {
             CRM_Contact_Form_Edit_Address::fixStateSelect($this, "address[{$blockId}][country_id]", "address[{$blockId}][state_province_id]", CRM_Utils_Array::value('country_id', $values, $config->defaultContactCountry));
         }
     }
 }
Example #30
0
 /**
  * Given a contact id and a field set, return the values from the db
  * for this contact
  *
  * @param int     $id       the contact id
  * @param array   $fields   the profile fields of interest
  * @param array   $values   the values for the above fields
  * @return void
  * @access public
  * @static
  */
 function getValues($cid, &$fields, &$values)
 {
     $options = array();
     // get the contact details (hier)
     $returnProperties =& CRM_Contact_BAO_Contact::makeHierReturnProperties($fields);
     $params = array('id' => $cid);
     $query =& new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
     $options =& $query->_options;
     $details = $query->searchQuery();
     if (!$details->fetch()) {
         return;
     }
     require_once 'CRM/Core/PseudoConstant.php';
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     //start of code to set the default values
     foreach ($fields as $name => $field) {
         $index = $field['title'];
         $params[$index] = $values[$index] = '';
         if ($details->{$name} || $name == 'group' || $name == 'tag') {
             //hack for CRM-665
             //to handle custom data (checkbox) to be written
             // to handle gender / suffix / prefix
             if (in_array($name, array('gender', 'individual_prefix', 'individual_suffix'))) {
                 $values[$index] = $details->{$name};
                 $name = $name . '_id';
                 $params[$index] = $details->{$name};
             } else {
                 if (in_array($name, array('state_province', 'country'))) {
                     $values[$index] = $details->{$name};
                     $idx = $name . '_id';
                     $params[$index] = $details->{$idx};
                 } else {
                     if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                         if ($details->{$name}) {
                             $values[$index] = '[ x ]';
                         }
                     } else {
                         if ($name == 'group') {
                             $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', null, false, true);
                             $title = array();
                             $ids = array();
                             foreach ($groups as $g) {
                                 if ($g['visibility'] != 'User and User Admin Only') {
                                     $title[] = $g['title'];
                                     if ($g['visibility'] == 'Public User Pages and Listings') {
                                         $ids[] = $g['group_id'];
                                     }
                                 }
                             }
                             $values[$index] = implode(', ', $title);
                             $params[$index] = implode(',', $ids);
                         } else {
                             if ($name == 'tag') {
                                 require_once 'CRM/Core/BAO/EntityTag.php';
                                 $entityTags =& CRM_Core_BAO_EntityTag::getTag('civicrm_contact', $cid);
                                 $allTags =& CRM_Core_PseudoConstant::tag();
                                 $title = array();
                                 foreach ($entityTags as $tagId) {
                                     $title[] = $allTags[$tagId];
                                 }
                                 $values[$index] = implode(', ', $title);
                                 $params[$index] = implode(',', $entityTags);
                             } else {
                                 require_once 'CRM/Core/BAO/CustomField.php';
                                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                     $params[$index] = $details->{$name};
                                     $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($details->{$name}, $cfID, $options);
                                 } else {
                                     $values[$index] = $details->{$name};
                                 }
                             }
                         }
                     }
                 }
             }
         } else {
             if (strpos($name, '-') !== false) {
                 list($fieldName, $id, $type) = explode('-', $name);
                 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                 if (!$locationTypeName) {
                     continue;
                 }
                 $detailName = "{$locationTypeName}-{$fieldName}";
                 if (in_array($fieldName, array('phone', 'im', 'email'))) {
                     if ($type) {
                         $detailName .= "-{$type}";
                     } else {
                         $detailName .= '-1';
                     }
                 }
                 if (in_array($fieldName, array('state_province', 'country'))) {
                     $values[$index] = $details->{$detailName};
                     $idx = $detailName . '_id';
                     $params[$index] = $details->{$idx};
                 } else {
                     $values[$index] = $params[$index] = $details->{$detailName};
                 }
             }
         }
         if ($field['visibility'] == "Public User Pages and Listings" && CRM_Utils_System::checkPermission('profile listings and forms')) {
             if (CRM_Utils_System::isNull($params[$index])) {
                 $params[$index] = $values[$index];
             }
             if (empty($params[$index])) {
                 continue;
             }
             $fieldName = $field['name'];
             $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
             if (!empty($values[$index])) {
                 $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>';
             }
         }
     }
 }