Пример #1
0
 /**
  * This function sets the default values for the form.
  * default values are retrieved from the database
  * 
  * @access public
  * @return None
  */
 function setDefaultValues()
 {
     if (!$this->_defaults) {
         $this->_defaults = array();
         $formArray = array('Component', 'Localization');
         $formMode = false;
         if (in_array($this->_name, $formArray)) {
             $formMode = true;
         }
         require_once "CRM/Core/BAO/Setting.php";
         CRM_Core_BAO_Setting::retrieve($this->_defaults);
         require_once "CRM/Core/Config/Defaults.php";
         CRM_Core_Config_Defaults::setValues($this->_defaults, $formMode);
         require_once "CRM/Core/OptionGroup.php";
         $list = array_flip(CRM_Core_OptionGroup::values('contact_autocomplete_options', false, false, true, null, 'name'));
         require_once "CRM/Core/BAO/Preferences.php";
         $listEnabled = CRM_Core_BAO_Preferences::valueOptions('contact_autocomplete_options');
         $autoSearchFields = array();
         if (!empty($list) && !empty($listEnabled)) {
             $autoSearchFields = array_combine($list, $listEnabled);
         }
         //Set sort_name for default
         $this->_defaults['autocompleteContactSearch'] = array('1' => 1) + $autoSearchFields;
     }
     return $this->_defaults;
 }
Пример #2
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);
 }
Пример #3
0
 static function getContactList(&$config)
 {
     require_once 'CRM/Core/BAO/Preferences.php';
     $name = CRM_Utils_Type::escape($_GET['s'], 'String');
     $limit = '10';
     $list = array_keys(CRM_Core_BAO_Preferences::valueOptions('contact_autocomplete_options'), '1');
     $select = array('sort_name');
     $where = '';
     $from = array();
     foreach ($list as $value) {
         $suffix = substr($value, 0, 2) . substr($value, -1);
         switch ($value) {
             case 'street_address':
             case 'city':
                 $selectText = $value;
                 $value = "address";
                 $suffix = 'sts';
             case 'phone':
             case 'email':
                 $select[] = $value == 'address' ? $selectText : $value;
                 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
                 break;
             case 'country':
             case 'state_province':
                 $select[] = "{$suffix}.name";
                 if (!in_array('address', $from)) {
                     $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
                 }
                 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id  ) ";
                 break;
         }
     }
     $select = implode(', ', $select);
     $from = implode(' ', $from);
     if (CRM_Utils_Array::value('limit', $_GET)) {
         $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
     }
     // add acl clause here
     require_once 'CRM/Contact/BAO/Contact/Permission.php';
     list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
     if ($aclWhere) {
         $where .= " AND {$aclWhere} ";
     }
     $query = "\nSELECT DISTINCT(cc.id) as id, CONCAT_WS( ' :: ', {$select} ) as data\nFROM civicrm_contact cc {$from}\n{$aclFrom}\nWHERE sort_name LIKE '%{$name}%' {$where} \nORDER BY sort_name\nLIMIT 0, {$limit}\n";
     // send query to hook to be modified if needed
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::contactListQuery($query, $name, CRM_Utils_Array::value('context', $_GET), CRM_Utils_Array::value('id', $_GET));
     $dao = CRM_Core_DAO::executeQuery($query);
     $contactList = null;
     while ($dao->fetch()) {
         echo $contactList = "{$dao->data}|{$dao->id}\n";
     }
     exit;
 }
Пример #4
0
 static function mailingPreferences()
 {
     if (!self::$_mailingPref) {
         $mailingPref =& new CRM_Core_DAO_Preferences();
         $mailingPref->domain_id = CRM_Core_Config::domainID();
         $mailingPref->is_domain = true;
         $mailingPref->contact_id = null;
         $mailingPref->find(true);
         if ($mailingPref->mailing_backend) {
             self::$_mailingPref = unserialize($mailingPref->mailing_backend);
         }
     }
     return self::$_mailingPref;
 }
Пример #5
0
 static function checkAddress(&$values)
 {
     if (!isset($values['street_address']) || !isset($values['city']) && !isset($values['state_province']) && !isset($values['postal_code'])) {
         return false;
     }
     require_once 'CRM/Core/BAO/Preferences.php';
     $userID = CRM_Core_BAO_Preferences::value('address_standardization_userid');
     $url = CRM_Core_BAO_Preferences::value('address_standardization_url');
     if (empty($userID) || empty($url)) {
         return false;
     }
     $address2 = str_replace(',', '', $values['street_address']);
     $XMLQuery = '<AddressValidateRequest USERID="' . $userID . '"><Address ID="0"><Address1>' . $values['supplemental_address_1'] . '</Address1><Address2>' . $address2 . '</Address2><City>' . $values['city'] . '</City><State>' . $values['state_province'] . '</State><Zip5>' . $values['postal_code'] . '</Zip5><Zip4>' . $values['postal_code_suffix'] . '</Zip4></Address></AddressValidateRequest>';
     require_once 'HTTP/Request.php';
     $request =& new HTTP_Request();
     $request->setURL($url);
     $request->addQueryString('API', 'Verify');
     $request->addQueryString('XML', $XMLQuery);
     $response = $request->sendRequest();
     $session =& CRM_Core_Session::singleton();
     $code = $request->getResponseCode();
     if ($code != 200) {
         $session->setStatus(ts('USPS Address Lookup Failed with HTTP status code: $code'));
         return false;
     }
     $responseBody = $request->getResponseBody();
     $xml = simplexml_load_string($responseBody);
     if (is_null($xml) || is_null($xml->Address)) {
         $session->setStatus(ts('Your USPS API Lookup has Failed.'));
         return false;
     }
     if ($xml->Number == '80040b1a') {
         $session->setStatus(ts('Your USPS API Authorization has Failed.'));
         return false;
     }
     if (array_key_exists('Error', $xml->Address)) {
         $session->setStatus(ts('Address not found in USPS database.'));
         return false;
     }
     $values['street_address'] = (string) $xml->Address->Address2;
     $values['city'] = (string) $xml->Address->City;
     $values['state_province'] = (string) $xml->Address->State;
     $values['postal_code'] = (string) $xml->Address->Zip5;
     $values['postal_code_suffix'] = (string) $xml->Address->Zip4;
     if (array_key_exists('Address1', $xml->Address)) {
         $values['supplemental_address_1'] = (string) $xml->Address->Address1;
     }
     return true;
 }
Пример #6
0
 /**
  * build all the data structures needed to build the form
  *
  * @return void
  * @access public
  */
 function preProcess()
 {
     /*
      * initialize the task and row fields
      */
     parent::preProcess();
     //get the contact read only fields to display.
     require_once 'CRM/Core/BAO/Preferences.php';
     $readOnlyFields = array_merge(array('sort_name' => ts('Name')), CRM_Core_BAO_Preferences::valueOptions('contact_autocomplete_options', true, null, false, 'name', true));
     //get the read only field data.
     $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
     require_once 'CRM/Contact/BAO/Contact/Utils.php';
     $contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_contributionIds, 'CiviContribute', $returnProperties);
     $this->assign('contactDetails', $contactDetails);
     $this->assign('readOnlyFields', $readOnlyFields);
 }
Пример #7
0
 /**
  * Build the form
  *
  * @access public
  * @return void
  */
 function buildQuickForm()
 {
     // text for sort_name or email criteria
     $this->add('text', 'sort_name', ts('Name or Email'));
     require_once 'CRM/Core/BAO/Preferences.php';
     $searchOptions = CRM_Core_BAO_Preferences::valueOptions('advanced_search_options');
     if (CRM_Utils_Array::value('contactType', $searchOptions)) {
         require_once 'CRM/Contact/BAO/ContactType.php';
         $contactTypes = array('' => ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements();
         $this->add('select', 'contact_type', ts('is...'), $contactTypes);
     }
     if (CRM_Utils_Array::value('groups', $searchOptions)) {
         $config = CRM_Core_Config::singleton();
         if ($config->groupTree) {
             $this->add('hidden', 'group', null, array('id' => 'group'));
             $group = CRM_Utils_Array::value('group', $this->_formValues);
             $selectedGroups = explode(',', $group);
             if (is_array($selectedGroups)) {
                 $groupNames = null;
                 $groupIds = array();
                 foreach ($selectedGroups as $groupId) {
                     if ($groupNames) {
                         $groupNames .= '<br/>';
                     }
                     $groupNames .= $this->_group[$groupId];
                 }
                 $groupIds[] = $groupId;
             }
             $this->assign('groupIds', implode(',', $groupIds));
             $this->assign('groupNames', $groupNames);
         } else {
             // add select for groups
             $group = array('' => ts('- any group -')) + $this->_group;
             $this->_groupElement =& $this->addElement('select', 'group', ts('in'), $group);
         }
     }
     if (CRM_Utils_Array::value('tags', $searchOptions)) {
         // tag criteria
         if (!empty($this->_tag)) {
             $tag = array('' => ts('- any tag -')) + $this->_tag;
             $this->_tagElement =& $this->addElement('select', 'tag', ts('with'), $tag);
         }
     }
     parent::buildQuickForm();
 }
Пример #8
0
 /**
  * Browse all activities for a particular contact
  *
  * @return none
  *
  * @access public
  */
 function browse()
 {
     require_once 'CRM/Core/Selector/Controller.php';
     $output = CRM_Core_Selector_Controller::SESSION;
     require_once 'CRM/Activity/Selector/Activity.php';
     $selector =& new CRM_Activity_Selector_Activity($this->_contactId, $this->_permission);
     $sortID = null;
     if ($this->get(CRM_Utils_Sort::SORT_ID)) {
         $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID), $this->get(CRM_Utils_Sort::SORT_DIRECTION));
     }
     $controller =& new CRM_Core_Selector_Controller($selector, $this->get(CRM_Utils_Pager::PAGE_ID), $sortID, CRM_Core_Action::VIEW, $this, $output);
     $controller->setEmbedded(true);
     $controller->run();
     $controller->moveFromSessionToTemplate();
     // check if case is enabled
     require_once 'CRM/Core/BAO/Preferences.php';
     $viewOptions = CRM_Core_BAO_Preferences::valueOptions('contact_view_options', true, null, true);
     $enableCase = false;
     if (CRM_Utils_Array::value('CiviCase', $viewOptions)) {
         $enableCase = true;
     }
     $this->assign('enableCase', $enableCase);
     $this->assign('context', 'activity');
 }
Пример #9
0
 /**
  * @param $params
  */
 static function fixAndStoreDirAndURL(&$params)
 {
     $sql = "\nSELECT v.name as valueName, g.name as optionName\nFROM   civicrm_option_value v,\n       civicrm_option_group g\nWHERE  ( g.name = 'directory_preferences'\nOR       g.name = 'url_preferences' )\nAND    v.option_group_id = g.id\nAND    v.is_active = 1\n";
     $dirParams = array();
     $urlParams = array();
     $dao = CRM_Core_DAO::executeQuery($sql);
     while ($dao->fetch()) {
         if (!isset($params[$dao->valueName])) {
             continue;
         }
         if ($dao->optionName == 'directory_preferences') {
             $dirParams[$dao->valueName] = CRM_Utils_Array::value($dao->valueName, $params, '');
         } else {
             $urlParams[$dao->valueName] = CRM_Utils_Array::value($dao->valueName, $params, '');
         }
         unset($params[$dao->valueName]);
     }
     if (!empty($dirParams)) {
         CRM_Core_BAO_Preferences::storeDirectoryOrURLPreferences($dirParams, 'directory');
     }
     if (!empty($urlParams)) {
         CRM_Core_BAO_Preferences::storeDirectoryOrURLPreferences($urlParams, 'url');
     }
 }
Пример #10
0
 /**
  * Browse all activities for a particular contact
  *
  * @return none
  *
  * @access public
  */
 function browse($contactId, $admin)
 {
     $config =& CRM_Core_Config::singleton();
     if (!$config->civiHRD) {
         require_once 'CRM/Core/Selector/Controller.php';
         $output = CRM_Core_Selector_Controller::SESSION;
         require_once 'CRM/Activity/Selector/Activity.php';
         $selector =& new CRM_Activity_Selector_Activity($contactId, $this->_permission, $admin, 'home');
         $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID), $this->get(CRM_Utils_Sort::SORT_DIRECTION));
         $controller =& new CRM_Core_Selector_Controller($selector, $this->get(CRM_Utils_Pager::PAGE_ID), $sortID, CRM_Core_Action::VIEW, $this, $output);
         $controller->setEmbedded(true);
         $controller->run();
         $controller->moveFromSessionToTemplate();
         $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name');
         $this->assign('contactId', $contactId);
         $this->assign('display_name', $displayName);
         $this->assign('context', 'home');
         // check if case is enabled
         require_once 'CRM/Core/BAO/Preferences.php';
         $viewOptions = CRM_Core_BAO_Preferences::valueOptions('contact_view_options', true, null, true);
         $enableCase = false;
         if ($viewOptions[ts('CiviCase')]) {
             $enableCase = true;
         }
         $this->assign('enableCase', $enableCase);
     }
 }
Пример #11
0
 /**
  * Function to build profile form
  *
  * @params object  $form       form object
  * @params array   $field      array field properties
  * @params int     $mode       profile mode
  * @params int     $contactID  contact id
  *
  * @return null
  * @static
  * @access public
  */
 static function buildProfile(&$form, &$field, $mode, $contactId = null, $online = false)
 {
     require_once "CRM/Profile/Form.php";
     require_once "CRM/Core/OptionGroup.php";
     require_once 'CRM/Core/BAO/UFField.php';
     require_once 'CRM/Contact/BAO/ContactType.php';
     $defaultValues = array();
     $fieldName = $field['name'];
     $title = $field['title'];
     $attributes = $field['attributes'];
     $rule = $field['rule'];
     $view = $field['is_view'];
     $required = $mode == CRM_Profile_Form::MODE_SEARCH ? false : $field['is_required'];
     $search = $mode == CRM_Profile_Form::MODE_SEARCH ? true : false;
     // do not display view fields in drupal registration form
     // CRM-4632
     if ($view && $mode == CRM_Profile_Form::MODE_REGISTER) {
         return;
     }
     if ($contactId && !$online) {
         $name = "field[{$contactId}][{$fieldName}]";
     } else {
         $name = $fieldName;
     }
     require_once 'CRM/Core/BAO/Preferences.php';
     $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true);
     if (substr($fieldName, 0, 14) === 'state_province') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince(), $required);
     } else {
         if (substr($fieldName, 0, 7) === 'country') {
             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), $required);
             $config =& CRM_Core_Config::singleton();
             if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactCountry) {
                 $defaultValues[$name] = $config->defaultContactCountry;
                 $form->setDefaults($defaultValues);
             }
         } else {
             if (substr($fieldName, 0, 6) === 'county') {
                 if ($addressOptions['county']) {
                     $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::county(), $required);
                 }
             } else {
                 if (substr($fieldName, 0, 2) === 'im') {
                     if (!$contactId) {
                         $form->add('select', $name . '-provider_id', $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::IMProvider(), $required);
                         if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) {
                             $form->freeze($name . "-provider_id");
                         }
                     }
                     $form->add('text', $name, $title, $attributes, $required);
                 } else {
                     if ($fieldName === 'birth_date' || $fieldName === 'deceased_date') {
                         $form->addDate($name, $title, $required, array('formatType' => 'birth'));
                     } else {
                         if (in_array($fieldName, array("membership_start_date", "membership_end_date", "join_date"))) {
                             $form->addDate($name, $title, $required, array('formatType' => 'custom'));
                         } else {
                             if ($field['name'] == 'membership_type_id') {
                                 require_once 'CRM/Member/PseudoConstant.php';
                                 $form->add('select', 'membership_type_id', $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipType(), $required);
                             } else {
                                 if ($field['name'] == 'status_id') {
                                     require_once 'CRM/Member/PseudoConstant.php';
                                     $form->add('select', 'status_id', $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(), $required);
                                 } else {
                                     if ($fieldName === 'gender') {
                                         $genderOptions = array();
                                         $gender = CRM_Core_PseudoConstant::gender();
                                         foreach ($gender as $key => $var) {
                                             $genderOptions[$key] = HTML_QuickForm::createElement('radio', null, ts('Gender'), $var, $key);
                                         }
                                         $form->addGroup($genderOptions, $name, $title);
                                         if ($required) {
                                             $form->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
                                         }
                                     } else {
                                         if ($fieldName === 'individual_prefix') {
                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualPrefix(), $required);
                                         } else {
                                             if ($fieldName === 'individual_suffix') {
                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualSuffix(), $required);
                                             } else {
                                                 if ($fieldName === 'contact_sub_type') {
                                                     $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $form->_fields[$fieldName]);
                                                     $profileType = $gId ? CRM_Core_BAO_UFField::getProfileType($gId) : null;
                                                     $setSubtype = false;
                                                     if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                                                         $setSubtype = $profileType;
                                                         $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
                                                     }
                                                     $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : array();
                                                     if ($setSubtype) {
                                                         $subtypeList = array();
                                                         $subtypeList[$setSubtype] = $subtypes[$setSubtype];
                                                     } else {
                                                         $subtypeList = array('' => ts('- select -')) + $subtypes;
                                                     }
                                                     $form->add('select', $name, $title, $subtypeList, $required);
                                                 } else {
                                                     if (in_array($fieldName, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                         //add email greeting, postal greeting, addressee, CRM-4575
                                                         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field);
                                                         $profileType = CRM_Core_BAO_UFField::getProfileType($gId, true, false, true);
                                                         if (empty($profileType) || in_array($profileType, array('Contact', 'Contribution', 'Participant', 'Membership'))) {
                                                             $profileType = 'Individual';
                                                         }
                                                         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                                                             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
                                                         }
                                                         if ($fieldName == 'email_greeting') {
                                                             $emailGreeting = array('contact_type' => $profileType, 'greeting_type' => 'email_greeting');
                                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($emailGreeting), $required);
                                                             // adding custom email greeting element alongwith email greeting
                                                             $form->add('text', 'email_greeting_custom', ts('Custom Email Greeting'), null, false);
                                                         } else {
                                                             if ($fieldName === 'postal_greeting') {
                                                                 $postalGreeting = array('contact_type' => $profileType, 'greeting_type' => 'postal_greeting');
                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($postalGreeting), $required);
                                                                 // adding custom postal greeting element alongwith postal greeting
                                                                 $form->add('text', 'postal_greeting_custom', ts('Custom Postal Greeting'), null, false);
                                                             } else {
                                                                 if ($fieldName === 'addressee') {
                                                                     $addressee = array('contact_type' => $profileType, 'greeting_type' => 'addressee');
                                                                     $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($addressee), $required);
                                                                     // adding custom addressee  element alongwith addressee type
                                                                     $form->add('text', 'addressee_custom', ts('Custom Addressee'), null, false);
                                                                 }
                                                             }
                                                         }
                                                     } else {
                                                         if ($fieldName === 'preferred_communication_method') {
                                                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                                                             foreach ($communicationFields as $key => $var) {
                                                                 if ($key == '') {
                                                                     continue;
                                                                 }
                                                                 $communicationOptions[] =& HTML_QuickForm::createElement('checkbox', $key, null, $var);
                                                             }
                                                             $form->addGroup($communicationOptions, $name, $title, '<br/>');
                                                         } else {
                                                             if ($fieldName === 'preferred_mail_format') {
                                                                 $form->add('select', $name, $title, CRM_Core_SelectValues::pmf());
                                                             } else {
                                                                 if ($fieldName == 'external_identifier') {
                                                                     $form->add('text', $name, $title, $attributes, $required);
                                                                     $contID = $contactId;
                                                                     if (!$contID) {
                                                                         $contID = $form->get('id');
                                                                     }
                                                                     $form->addRule($name, ts('External ID already exists in Database.'), 'objectExists', array('CRM_Contact_DAO_Contact', $contID, 'external_identifier'));
                                                                 } else {
                                                                     if ($fieldName === 'group') {
                                                                         require_once 'CRM/Contact/Form/Edit/TagsAndGroups.php';
                                                                         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, true, $required, $title, null, $name);
                                                                     } else {
                                                                         if ($fieldName === 'tag') {
                                                                             require_once 'CRM/Contact/Form/Edit/TagsAndGroups.php';
                                                                             CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::TAG, false, $required, null, $title, $name);
                                                                         } else {
                                                                             if ($fieldName === 'home_URL') {
                                                                                 $form->addElement('text', $name, $title, array_merge(CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'home_URL'), array('onfocus' => "if (!this.value) this.value='http://'; else return false", 'onblur' => "if ( this.value == 'http://') this.value=''; else return false")));
                                                                                 $form->addRule($name, ts('Enter a valid Website.'), 'url');
                                                                             } else {
                                                                                 if (substr($fieldName, 0, 6) === 'custom') {
                                                                                     $customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName);
                                                                                     if ($customFieldID) {
                                                                                         CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, false, $required, $search, $title);
                                                                                     }
                                                                                 } else {
                                                                                     if (in_array($fieldName, array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date'))) {
                                                                                         $form->addDate($name, $title, $required, array('formatType' => 'custom'));
                                                                                     } else {
                                                                                         if ($fieldName == 'payment_instrument') {
                                                                                             require_once "CRM/Contribute/PseudoConstant.php";
                                                                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), $required);
                                                                                         } else {
                                                                                             if ($fieldName == 'contribution_type') {
                                                                                                 require_once "CRM/Contribute/PseudoConstant.php";
                                                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType(), $required);
                                                                                             } else {
                                                                                                 if ($fieldName == 'contribution_status_id') {
                                                                                                     require_once "CRM/Contribute/PseudoConstant.php";
                                                                                                     $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionStatus(), $required);
                                                                                                 } else {
                                                                                                     if ($fieldName == 'participant_register_date') {
                                                                                                         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
                                                                                                     } else {
                                                                                                         if ($fieldName == 'participant_status_id') {
                                                                                                             require_once "CRM/Event/PseudoConstant.php";
                                                                                                             $cond = null;
                                                                                                             if ($online == true) {
                                                                                                                 $cond = "visibility_id = 1";
                                                                                                             }
                                                                                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantStatus(null, $cond), $required);
                                                                                                         } else {
                                                                                                             if ($fieldName == 'participant_role_id') {
                                                                                                                 require_once "CRM/Event/PseudoConstant.php";
                                                                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantRole(), $required);
                                                                                                             } else {
                                                                                                                 if ($fieldName == 'scholarship_type_id') {
                                                                                                                     $form->add('select', $name, $title, array("" => "-- Select -- ") + array_flip(CRM_Core_OptionGroup::values('scholarship_type', true)));
                                                                                                                 } else {
                                                                                                                     if ($fieldName == 'applicant_status_id') {
                                                                                                                         $form->add('select', $name, $title, array("" => "-- Select -- ") + array_flip(CRM_Core_OptionGroup::values('applicant_status', true)));
                                                                                                                     } else {
                                                                                                                         if ($fieldName == 'highschool_gpa_id') {
                                                                                                                             $form->add('select', $name, $title, array("" => "-- Select -- ") + CRM_Core_OptionGroup::values('highschool_gpa'));
                                                                                                                         } else {
                                                                                                                             if ($fieldName == 'world_region') {
                                                                                                                                 require_once "CRM/Core/PseudoConstant.php";
                                                                                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::worldRegion(), $required);
                                                                                                                             } else {
                                                                                                                                 $processed = false;
                                                                                                                                 if (CRM_Core_Permission::access('Quest', false)) {
                                                                                                                                     require_once 'CRM/Quest/BAO/Student.php';
                                                                                                                                     $processed = CRM_Quest_BAO_Student::buildStudentForm($form, $fieldName, $title, $contactId);
                                                                                                                                 }
                                                                                                                                 if (!$processed) {
                                                                                                                                     if (substr($fieldName, 0, 3) === 'is_' or substr($fieldName, 0, 7) === 'do_not_') {
                                                                                                                                         $form->add('checkbox', $name, $title, $attributes, $required);
                                                                                                                                     } else {
                                                                                                                                         $form->add('text', $name, $title, $attributes, $required);
                                                                                                                                     }
                                                                                                                                 }
                                                                                                                             }
                                                                                                                         }
                                                                                                                     }
                                                                                                                 }
                                                                                                             }
                                                                                                         }
                                                                                                     }
                                                                                                 }
                                                                                             }
                                                                                         }
                                                                                     }
                                                                                 }
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     static $hiddenSubtype = false;
     if (!$hiddenSubtype && CRM_Contact_BAO_ContactType::isaSubType($field['field_type'])) {
         // In registration mode params are submitted via POST and we don't have any clue
         // about profile-id or the profile-type (which could be a subtype)
         // To generalize the  behavior and simplify the process,
         // lets always add the hidden
         //subtype value if there is any, and we won't have to
         // compute it while processing.
         $form->addElement('hidden', 'contact_sub_type_hidden', $field['field_type']);
         $hiddenSubtype = true;
     }
     if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) {
         $form->freeze($name);
     }
     //add the rules
     if (in_array($fieldName, array('non_deductible_amount', 'total_amount', 'fee_amount', 'net_amount'))) {
         $form->addRule($name, ts('Please enter a valid amount.'), 'money');
     }
     if ($rule) {
         if (!($rule == 'email' && $mode == CRM_Profile_Form::MODE_SEARCH)) {
             $form->addRule($name, ts('Please enter a valid %1', array(1 => $title)), $rule);
         }
     }
 }
Пример #12
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return void
  */
 public function postProcess()
 {
     $fv = $this->controller->exportValues($this->_name);
     $config =& CRM_Core_Config::singleton();
     $locName = null;
     //get the address format sequence from the config file
     require_once 'CRM/Core/BAO/Preferences.php';
     $sequence = CRM_Core_BAO_Preferences::value('mailing_sequence');
     foreach ($sequence as $v) {
         $address[$v] = 1;
     }
     if (array_key_exists('postal_code', $address)) {
         $address['postal_code_suffix'] = 1;
     }
     //build the returnproperties
     $returnProperties = array('display_name' => 1);
     $mailingFormat = CRM_Core_BAO_Preferences::value('mailing_format');
     $mailingFormatProperties = array();
     if ($mailingFormat) {
         $mailingFormatProperties = self::getReturnProperties($mailingFormat);
         $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
     }
     $customFormatProperties = array();
     if (stristr($mailingFormat, 'custom_')) {
         foreach ($mailingFormatProperties as $token => $true) {
             if (substr($token, 0, 7) == 'custom_') {
                 if (!CRM_Utils_Array::value($token, $customFormatProperties)) {
                     $customFormatProperties[$token] = $mailingFormatProperties[$token];
                 }
             }
         }
     }
     if (!empty($customFormatProperties)) {
         $returnProperties = array_merge($returnProperties, $customFormatProperties);
     }
     //get the contacts information
     $params = array();
     if (CRM_Utils_Array::value('location_type_id', $fv)) {
         $locType = CRM_Core_PseudoConstant::locationType();
         $locName = $locType[$fv['location_type_id']];
         $location = array('location' => array("{$locName}" => $address));
         $returnProperties = array_merge($returnProperties, $location);
         $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0);
     } else {
         $returnProperties = array_merge($returnProperties, $address);
     }
     $rows = array();
     foreach ($this->_contactIds as $key => $contactID) {
         $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0);
     }
     // fix for CRM-2651
     if (CRM_Utils_Array::value('do_not_mail', $fv)) {
         $params[] = array('do_not_mail', '=', 0, 0, 0);
     }
     // fix for CRM-2613
     $params[] = array('is_deceased', '=', 0, 0, 0);
     $custom = array();
     foreach ($returnProperties as $name => $dontCare) {
         $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
         if ($cfID) {
             $custom[] = $cfID;
         }
     }
     //get the total number of contacts to fetch from database.
     $numberofContacts = count($this->_contactIds);
     require_once 'CRM/Contact/BAO/Query.php';
     $query =& new CRM_Contact_BAO_Query($params, $returnProperties);
     $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
     // also get all token values
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::tokenValues($details[0], $this->_contactIds);
     $tokens = array();
     CRM_Utils_Hook::tokens($tokens);
     $tokenFields = array();
     foreach ($tokens as $category => $catTokens) {
         foreach ($catTokens as $token) {
             $tokenFields[] = $token;
         }
     }
     foreach ($this->_contactIds as $value) {
         foreach ($custom as $cfID) {
             if (isset($details[0][$value]["custom_{$cfID}"])) {
                 $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]);
             }
         }
         $contact = CRM_Utils_Array::value($value, $details['0']);
         if (is_a($contact, 'CRM_Core_Error')) {
             return null;
         }
         // we need to remove all the "_id"
         unset($contact['contact_id']);
         if ($locName && CRM_Utils_Array::value($locName, $contact)) {
             // If location type is not primary, $contact contains
             // one more array as "$contact[$locName] = array( values... )"
             $found = false;
             // we should replace all the tokens that are set in mailing label format
             foreach ($mailingFormatProperties as $key => $dontCare) {
                 if (CRM_Utils_Array::value($key, $contact)) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 continue;
             }
             unset($contact[$locName]);
             if (CRM_Utils_Array::value('county_id', $contact)) {
                 unset($contact['county_id']);
             }
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
             $valuesothers = array();
             $paramsothers = array('contact_id' => $value);
             require_once 'CRM/Core/BAO/Location.php';
             $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
             if (CRM_Utils_Array::value('location_type_id', $fv)) {
                 foreach ($valuesothers as $vals) {
                     if ($vals['location_type_id'] == CRM_Utils_Array::value('location_type_id', $fv)) {
                         foreach ($vals as $k => $v) {
                             if (in_array($k, array('email', 'phone', 'im', 'openid'))) {
                                 if ($k == 'im') {
                                     $rows[$value][$k] = $v['1']['name'];
                                 } else {
                                     $rows[$value][$k] = $v['1'][$k];
                                 }
                                 $rows[$value][$k . '_id'] = $v['1']['id'];
                             }
                         }
                     }
                 }
             }
         } else {
             $found = false;
             // we should replace all the tokens that are set in mailing label format
             foreach ($mailingFormatProperties as $key => $dontCare) {
                 if (CRM_Utils_Array::value($key, $contact)) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 continue;
             }
             if (CRM_Utils_Array::value('addressee', $contact)) {
                 $contact['addressee'] = $contact['addressee_display'];
             }
             // now create the rows for generating mailing labels
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
         }
     }
     $individualFormat = false;
     if (isset($fv['merge_same_address'])) {
         $this->mergeSameAddress($rows);
         $individualFormat = true;
     }
     // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327)
     require_once 'CRM/Utils/Address.php';
     foreach ($rows as $id => $row) {
         if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) {
             require_once 'CRM/Core/PseudoConstant.php';
             $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods));
             $comm = CRM_Core_PseudoConstant::pcm();
             $temp = array();
             foreach ($val as $vals) {
                 $temp[] = $comm[$vals];
             }
             $row['preferred_communication_method'] = implode(', ', $temp);
         }
         $row['id'] = $id;
         $formatted = CRM_Utils_Address::format($row, 'mailing_format', false, true, $individualFormat, $tokenFields);
         // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
         // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
         // Due to FriBidi peculiarities, this can't be called on
         // a multi-line string, hence the explode+implode approach.
         if (function_exists('fribidi_log2vis')) {
             $lines = explode("\n", $formatted);
             foreach ($lines as $i => $line) {
                 $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8);
             }
             $formatted = implode("\n", $lines);
         }
         $rows[$id] = array($formatted);
     }
     //call function to create labels
     self::createLabel($rows, $fv['label_id']);
     exit(1);
 }
Пример #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);
 }
Пример #14
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);
     }
 }
Пример #15
0
 /**
  * Function to get the count of  contact loctions
  * 
  * @param int $contactId contact id
  *
  * @return int $locationCount max locations for the contact
  * @static
  * @access public
  */
 static function maxLocations($contactId)
 {
     // find the system config related location blocks
     require_once 'CRM/Core/BAO/Preferences.php';
     $locationCount = CRM_Core_BAO_Preferences::value('location_count');
     $contactLocations = array();
     // find number of location blocks for this contact and adjust value accordinly
     // get location type from email
     $query = "\n( SELECT location_type_id FROM civicrm_email   WHERE contact_id = {$contactId} )\nUNION\n( SELECT location_type_id FROM civicrm_phone   WHERE contact_id = {$contactId} )\nUNION\n( SELECT location_type_id FROM civicrm_im      WHERE contact_id = {$contactId} )\nUNION\n( SELECT location_type_id FROM civicrm_address WHERE contact_id = {$contactId} )\n";
     $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     $locCount = $dao->N;
     if ($locCount && $locationCount < $locCount) {
         $locationCount = $locCount;
     }
     return $locationCount;
 }
Пример #16
0
 static function getContactList(&$config)
 {
     require_once 'CRM/Core/BAO/Preferences.php';
     $name = CRM_Utils_Array::value('s', $_GET);
     $name = CRM_Utils_Type::escape($name, 'String');
     $limit = '10';
     $list = array_keys(CRM_Core_BAO_Preferences::valueOptions('contact_autocomplete_options'), '1');
     $select = array('sort_name');
     $where = '';
     $from = array();
     foreach ($list as $value) {
         $suffix = substr($value, 0, 2) . substr($value, -1);
         switch ($value) {
             case 'street_address':
             case 'city':
                 $selectText = $value;
                 $value = "address";
                 $suffix = 'sts';
             case 'phone':
             case 'email':
                 $select[] = $value == 'address' ? $selectText : $value;
                 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
                 break;
             case 'country':
             case 'state_province':
                 $select[] = "{$suffix}.name";
                 if (!in_array('address', $from)) {
                     $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
                 }
                 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id  ) ";
                 break;
         }
     }
     $select = implode(', ', $select);
     $from = implode(' ', $from);
     if (CRM_Utils_Array::value('limit', $_GET)) {
         $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
     }
     // add acl clause here
     require_once 'CRM/Contact/BAO/Contact/Permission.php';
     list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
     if ($aclWhere) {
         $where .= " AND {$aclWhere} ";
     }
     if (CRM_Utils_Array::value('org', $_GET)) {
         $where .= " AND contact_type = \"Organization\"";
         //set default for current_employer
         if ($orgId = CRM_Utils_Array::value('id', $_GET)) {
             $where .= " AND cc.id = {$orgId}";
         }
     }
     //contact's based of relationhip type
     $relType = null;
     if (isset($_GET['rel'])) {
         $relation = explode('_', $_GET['rel']);
         $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
         $rel = CRM_Utils_Type::escape($relation[2], 'String');
     }
     $config =& CRM_Core_Config::singleton();
     if ($config->includeWildCardInName) {
         $strSearch = "%{$name}%";
     } else {
         $strSearch = "{$name}%";
     }
     $whereClause = " WHERE sort_name LIKE '{$strSearch}' {$where} ";
     $additionalFrom = '';
     if ($relType) {
         $additionalFrom = "\n            INNER JOIN civicrm_relationship_type r ON ( \n                r.id = {$relType}\n                AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )\n                AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )\n            )";
     }
     $query = "\nSELECT DISTINCT(cc.id) as id, CONCAT_WS( ' :: ', {$select} ) as data\nFROM civicrm_contact cc {$from}\n{$aclFrom}\n{$additionalFrom}\n{$whereClause} \nORDER BY sort_name\nLIMIT 0, {$limit}\n";
     // send query to hook to be modified if needed
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::contactListQuery($query, $name, CRM_Utils_Array::value('context', $_GET), CRM_Utils_Array::value('id', $_GET));
     $dao = CRM_Core_DAO::executeQuery($query);
     $contactList = null;
     while ($dao->fetch()) {
         echo $contactList = "{$dao->data}|{$dao->id}\n";
     }
     //return organization name if doesn't exist in db
     if (!$contactList) {
         if (CRM_Utils_Array::value('org', $_GET)) {
             echo CRM_Utils_Array::value('s', $_GET);
         } else {
             if (CRM_Utils_Array::value('context', $_GET) == 'customfield') {
                 echo "{$name}|{$name}\n";
             }
         }
     }
     exit;
 }
Пример #17
0
 /**
  * the initializer code, called before the processing
  *
  * @return void
  * @access public
  */
 function init()
 {
     require_once 'CRM/Contact/BAO/Contact.php';
     $fields =& CRM_Contact_BAO_Contact::importableFields($this->_contactType);
     //CRM-5125
     //supporting import for contact subtypes
     if (!empty($this->_contactSubType)) {
         //custom fields for sub type
         $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($this->_contactSubType);
         if (!empty($subTypeFields)) {
             foreach ($subTypeFields as $customSubTypeField => $details) {
                 $fields[$customSubTypeField] = $details;
             }
         }
     }
     //Relationship importables
     $this->_relationships = $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, $this->_contactType, false, 'label', true, $this->_contactSubType);
     asort($relations);
     foreach ($relations as $key => $var) {
         list($type) = explode('_', $key);
         $relationshipType[$key]['title'] = $var;
         $relationshipType[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
         $relationshipType[$key]['import'] = true;
         $relationshipType[$key]['relationship_type_id'] = $type;
         $relationshipType[$key]['related'] = true;
     }
     if (!empty($relationshipType)) {
         $fields = array_merge($fields, array('related' => array('title' => ts('- related contact info -'))), $relationshipType);
     }
     foreach ($fields as $name => $field) {
         $this->addField($name, $field['title'], CRM_Utils_Array::value('type', $field), CRM_Utils_Array::value('headerPattern', $field), CRM_Utils_Array::value('dataPattern', $field), CRM_Utils_Array::value('hasLocationType', $field));
     }
     $this->_newContacts = array();
     $this->setActiveFields($this->_mapperKeys);
     $this->setActiveFieldLocationTypes($this->_mapperLocType);
     $this->setActiveFieldPhoneTypes($this->_mapperPhoneType);
     //set active fields of IM provider of contact
     $this->setActiveFieldImProviders($this->_mapperImProvider);
     //related info
     $this->setActiveFieldRelated($this->_mapperRelated);
     $this->setActiveFieldRelatedContactType($this->_mapperRelatedContactType);
     $this->setActiveFieldRelatedContactDetails($this->_mapperRelatedContactDetails);
     $this->setActiveFieldRelatedContactLocType($this->_mapperRelatedContactLocType);
     $this->setActiveFieldRelatedContactPhoneType($this->_mapperRelatedContactPhoneType);
     //set active fields of IM provider of related contact
     $this->setActiveFieldRelatedContactImProvider($this->_mapperRelatedContactImProvider);
     $this->_phoneIndex = -1;
     $this->_emailIndex = -1;
     $this->_firstNameIndex = -1;
     $this->_lastNameIndex = -1;
     $this->_householdNameIndex = -1;
     $this->_organizationNameIndex = -1;
     $this->_externalIdentifierIndex = -1;
     $index = 0;
     foreach ($this->_mapperKeys as $key) {
         if (substr($key, 0, 5) == 'email' && substr($key, 0, 14) != 'email_greeting') {
             $this->_emailIndex = $index;
             $this->_allEmails = array();
         }
         if (substr($key, 0, 5) == 'phone') {
             $this->_phoneIndex = $index;
         }
         if ($key == 'first_name') {
             $this->_firstNameIndex = $index;
         }
         if ($key == 'last_name') {
             $this->_lastNameIndex = $index;
         }
         if ($key == 'household_name') {
             $this->_householdNameIndex = $index;
         }
         if ($key == 'organization_name') {
             $this->_organizationNameIndex = $index;
         }
         if ($key == 'external_identifier') {
             $this->_externalIdentifierIndex = $index;
             $this->_allExternalIdentifiers = array();
         }
         $index++;
     }
     $this->_updateWithId = false;
     if (in_array('id', $this->_mapperKeys) || $this->_externalIdentifierIndex >= 0 && in_array($this->_onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) {
         $this->_updateWithId = true;
     }
     require_once 'CRM/Core/BAO/Preferences.php';
     $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Preferences::valueOptions('address_options'), false);
 }
Пример #18
0
function run()
{
    session_start();
    require_once '../civicrm.config.php';
    require_once 'CRM/Core/Config.php';
    $config =& CRM_Core_Config::singleton();
    require_once 'Console/Getopt.php';
    $shortOptions = "n:p:s:e:k:g:parse";
    $longOptions = array('name=', 'pass='******'key=', 'start=', 'end=', 'geocoding=', 'parse=');
    $getopt = new Console_Getopt();
    $args = $getopt->readPHPArgv();
    array_shift($args);
    list($valid, $dontCare) = $getopt->getopt2($args, $shortOptions, $longOptions);
    $vars = array('start' => 's', 'end' => 'e', 'name' => 'n', 'pass' => 'p', 'key' => 'k', 'geocoding' => 'g', 'parse' => 'ap');
    foreach ($vars as $var => $short) {
        ${$var} = null;
        foreach ($valid as $v) {
            if ($v[0] == $short || $v[0] == "--{$var}") {
                ${$var} = $v[1];
                break;
            }
        }
        if (!${$var}) {
            ${$var} = CRM_Utils_Array::value($var, $_REQUEST);
        }
        $_REQUEST[$var] = ${$var};
    }
    // this does not return on failure
    // require_once 'CRM/Utils/System.php';
    CRM_Utils_System::authenticateScript(true, $name, $pass);
    // do check for geocoding.
    $processGeocode = false;
    if (empty($config->geocodeMethod)) {
        if ($geocoding == 'true') {
            echo ts('Error: You need to set a mapping provider under Global Settings');
            exit;
        }
    } else {
        $processGeocode = true;
        // user might want to over-ride.
        if ($geocoding == 'false') {
            $processGeocode = false;
        }
    }
    // do check for parse street address.
    require_once 'CRM/Core/BAO/Preferences.php';
    $parseAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Preferences::valueOptions('address_options'), false);
    $parseStreetAddress = false;
    if (!$parseAddress) {
        if ($parse == 'true') {
            echo ts('Error: You need to enable Street Address Parsing under Global Settings >> Address Settings.');
            exit;
        }
    } else {
        $parseStreetAddress = true;
        // user might want to over-ride.
        if ($parse == 'false') {
            $parseStreetAddress = false;
        }
    }
    // don't process.
    if (!$parseStreetAddress && !$processGeocode) {
        echo ts('Error: Both Geocode mapping as well as Street Address Parsing are disabled. You must configure one or both options to use this script.');
        exit;
    }
    $config->userFramework = 'Soap';
    $config->userFrameworkClass = 'CRM_Utils_System_Soap';
    $config->userHookClass = 'CRM_Utils_Hook_Soap';
    // we have an exclusive lock - run the mail queue
    processContacts($config, $processGeocode, $parseStreetAddress, $start, $end);
}
Пример #19
0
 static function location(&$form)
 {
     $form->addElement('hidden', 'hidden_location', 1);
     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('street_address' => array(ts('Street Address'), $attributes['street_address'], null, null), 'city' => array(ts('City'), $attributes['city'], null, null), 'postal_code' => array(ts('Zip / Postal Code'), $attributes['postal_code'], null, null), 'county' => array(ts('County'), $attributes['county_id'], 'county', false), 'state_province' => array(ts('State / Province'), $attributes['state_province_id'], 'stateProvince', true), 'country' => array(ts('Country'), $attributes['country_id'], 'country', false), 'address_name' => array(ts('Address Name'), $attributes['address_name'], null, null));
     foreach ($elements as $name => $v) {
         list($title, $attributes, $select, $multiSelect) = $v;
         if (!$addressOptions[$name]) {
             continue;
         }
         if (!$attributes) {
             $attributes = $attributes[$name];
         }
         if ($select) {
             $selectElements = array('' => ts('- select -')) + CRM_Core_PseudoConstant::$select();
             $element = $form->addElement('select', $name, $title, $selectElements);
             if ($multiSelect) {
                 $element->setMultiple(true);
             }
         } else {
             $form->addElement('text', $name, $title, $attributes);
         }
         if ($addressOptions['postal_code']) {
             $form->addElement('text', 'postal_code_low', ts('Range-From'), CRM_Utils_Array::value('postal_code', $attributes));
             $form->addElement('text', 'postal_code_high', ts('To'), CRM_Utils_Array::value('postal_code', $attributes));
         }
         // select for state province
         $stateProvince = array('' => ts('- any state/province -')) + CRM_Core_PseudoConstant::stateProvince();
     }
     $worldRegions = array('' => ts('- any region -')) + CRM_Core_PseudoConstant::worldRegion();
     $form->addElement('select', 'world_region', ts('World Region'), $worldRegions);
     // checkboxes for location type
     $location_type = array();
     $locationType = CRM_Core_PseudoConstant::locationType();
     foreach ($locationType as $locationTypeID => $locationTypeName) {
         $location_type[] = HTML_QuickForm::createElement('checkbox', $locationTypeID, null, $locationTypeName);
     }
     $form->addGroup($location_type, 'location_type', ts('Location Types'), '&nbsp;');
 }
Пример #20
0
 /**
  * This function retrieve component related contact information.
  *
  * @param array  $componentIds     array of component Ids.
  * @param array  $returnProperties array of return elements.
  *
  * @return $contactDetails array of contact info.
  * @static
  */
 static function contactDetails($componentIds, $componentName, $returnProperties = array())
 {
     $contactDetails = array();
     if (empty($componentIds) || !in_array($componentName, array('CiviContribute', 'CiviMember', 'CiviEvent', 'Activity'))) {
         return $contactDetails;
     }
     if (empty($returnProperties)) {
         require_once 'CRM/Core/BAO/Preferences.php';
         $autocompleteContactSearch = CRM_Core_BAO_Preferences::valueOptions('contact_autocomplete_options');
         $returnProperties = array_fill_keys(array_merge(array('sort_name'), array_keys($autocompleteContactSearch)), 1);
     }
     $compTable = null;
     if ($componentName == 'CiviContribute') {
         $compTable = 'civicrm_contribution';
     } elseif ($componentName == 'CiviMember') {
         $compTable = 'civicrm_membership';
     } elseif ($componentName == 'Activity') {
         $compTable = 'civicrm_activity';
     } else {
         $compTable = 'civicrm_participant';
     }
     $select = $from = array();
     foreach ($returnProperties as $property => $ignore) {
         $value = in_array($property, array('city', 'street_address')) ? 'address' : $property;
         switch ($property) {
             case 'sort_name':
                 $select[] = "{$property} as {$property}";
                 if ($componentName == 'Activity') {
                     $from[$value] = "INNER JOIN civicrm_contact contact ON ( contact.id = {$compTable}.source_contact_id )";
                 } else {
                     $from[$value] = "INNER JOIN civicrm_contact contact ON ( contact.id = {$compTable}.contact_id )";
                 }
                 break;
             case 'email':
             case 'phone':
             case 'city':
             case 'street_address':
                 $select[] = "{$property} as {$property}";
                 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
                 break;
             case 'country':
             case 'state_province':
                 $select[] = "{$property}.name as {$property}";
                 if (!in_array('address', $from)) {
                     $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
                 }
                 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id  ) ";
                 break;
         }
     }
     //finally retrieve contact details.
     if (!empty($select) && !empty($from)) {
         $fromClause = implode(' ', $from);
         $selectClause = implode(', ', $select);
         $whereClause = "{$compTable}.id IN (" . implode(',', $componentIds) . ')';
         $query = "\n  SELECT  contact.id as contactId, {$compTable}.id as componentId, {$selectClause} \n    FROM  {$compTable} as {$compTable} {$fromClause} \n   WHERE  {$whereClause}\nGroup By  componentId";
         $contact = CRM_Core_DAO::executeQuery($query);
         while ($contact->fetch()) {
             $contactDetails[$contact->componentId]['contact_id'] = $contact->contactId;
             foreach ($returnProperties as $property => $ignore) {
                 $contactDetails[$contact->componentId][$property] = $contact->{$property};
             }
         }
         $contact->free();
     }
     return $contactDetails;
 }
Пример #21
0
 /**
  * retrieve a mailer to send any mail from the applciation
  *
  * @param
  * @access private
  * @return object
  */
 static function &getMailer()
 {
     if (!isset(self::$_mail)) {
         require_once "CRM/Core/BAO/Preferences.php";
         $mailingInfo =& CRM_Core_BAO_Preferences::mailingPreferences();
         if (defined('CIVICRM_MAILER_SPOOL') && CIVICRM_MAILER_SPOOL) {
             require_once 'CRM/Mailing/BAO/Spool.php';
             self::$_mail = new CRM_Mailing_BAO_Spool();
         } elseif ($mailingInfo['outBound_option'] == 0) {
             if ($mailingInfo['smtpServer'] == '' || !$mailingInfo['smtpServer']) {
                 CRM_Core_Error::fatal(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer CiviCRM >> Global Settings</a> to set the SMTP Server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting', 'reset=1'))));
             }
             $params['host'] = $mailingInfo['smtpServer'] ? $mailingInfo['smtpServer'] : 'localhost';
             $params['port'] = $mailingInfo['smtpPort'] ? $mailingInfo['smtpPort'] : 25;
             if ($mailingInfo['smtpAuth']) {
                 require_once 'CRM/Utils/Crypt.php';
                 $params['username'] = $mailingInfo['smtpUsername'];
                 $params['password'] = CRM_Utils_Crypt::decrypt($mailingInfo['smtpPassword']);
                 $params['auth'] = true;
             } else {
                 $params['auth'] = false;
             }
             // set the localhost value, CRM-3153
             $params['localhost'] = $_SERVER['SERVER_NAME'];
             self::$_mail =& Mail::factory('smtp', $params);
         } elseif ($mailingInfo['outBound_option'] == 1) {
             if ($mailingInfo['sendmail_path'] == '' || !$mailingInfo['sendmail_path']) {
                 CRM_Core_Error::fatal(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer CiviCRM >> Global Settings</a> to set the Sendmail Server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting', 'reset=1'))));
             }
             $params['sendmail_path'] = $mailingInfo['sendmail_path'];
             $params['sendmail_args'] = $mailingInfo['sendmail_args'];
             self::$_mail =& Mail::factory('sendmail', $params);
         } else {
             CRM_Core_Session::setStatus(ts('There is no valid SMTP server Setting Or SendMail path setting. Click <a href=\'%1\'>Administer CiviCRM >> Global Settings</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting', 'reset=1'))));
         }
     }
     return self::$_mail;
 }
Пример #22
0
 /**
  * If the return Properties are set in a hierarchy, traverse the hierarchy to get
  * the return values
  *
  * @return void 
  * @access public 
  */
 function addHierarchicalElements()
 {
     if (!CRM_Utils_Array::value('location', $this->_returnProperties)) {
         return;
     }
     if (!is_array($this->_returnProperties['location'])) {
         return;
     }
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $processed = array();
     $index = 0;
     // CRM_Core_Error::debug( 'd', $this->_fields );
     // CRM_Core_Error::debug( 'r', $this->_returnProperties );
     $addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address');
     $addressCustomFieldIds = array();
     foreach ($this->_returnProperties['location'] as $name => $elements) {
         $lCond = self::getPrimaryCondition($name);
         if (!$lCond) {
             $locationTypeId = array_search($name, $locationTypes);
             if ($locationTypeId === false) {
                 continue;
             }
             $lCond = "location_type_id = {$locationTypeId}";
             $this->_useDistinct = true;
             //commented for CRM-3256
             $this->_useGroupBy = true;
         }
         $name = str_replace(' ', '_', $name);
         $tName = "{$name}-location_type";
         $ltName = "`{$name}-location_type`";
         $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
         $this->_select["{$tName}"] = "`{$tName}`.name as `{$tName}`";
         $this->_element["{$tName}_id"] = 1;
         $this->_element["{$tName}"] = 1;
         $locationTypeName = $tName;
         $locationTypeJoin = array();
         $addAddress = false;
         $addWhereCount = 0;
         foreach ($elements as $elementFullName => $dontCare) {
             $index++;
             $elementName = $elementCmpName = $elementFullName;
             if (substr($elementCmpName, 0, 5) == 'phone') {
                 $elementCmpName = 'phone';
             }
             if (in_array($elementCmpName, array_keys($addressCustomFields))) {
                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($elementCmpName)) {
                     $addressCustomFieldIds[$cfID][$name] = 1;
                 }
             }
             //add address table only once
             if ((in_array($elementCmpName, self::$_locationSpecificFields) || !empty($addressCustomFieldIds)) && !$addAddress && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))) {
                 $tName = "{$name}-address";
                 $aName = "`{$name}-address`";
                 $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
                 $this->_element["{$tName}_id"] = 1;
                 $addressJoin = "\nLEFT JOIN civicrm_address {$aName} ON ({$aName}.contact_id = contact_a.id AND {$aName}.{$lCond})";
                 $this->_tables[$tName] = $addressJoin;
                 $locationTypeJoin[$tName] = " ( {$aName}.location_type_id = {$ltName}.id ) ";
                 $processed[$aName] = 1;
                 $addAddress = true;
             }
             $cond = $elementType = '';
             if (strpos($elementName, '-') !== false) {
                 // this is either phone, email or IM
                 list($elementName, $elementType) = explode('-', $elementName);
                 if ($elementName != 'phone' && $elementName != 'im') {
                     $cond = self::getPrimaryCondition($elementType);
                 }
                 if (!$cond && $elementName == 'phone') {
                     $cond = "phone_type_id = '{$elementType}'";
                 } else {
                     if (!$cond && $elementName == 'im') {
                         // IM service provider id, CRM-3140
                         $cond = "provider_id = '{$elementType}'";
                     }
                 }
                 $elementType = '-' . $elementType;
             }
             $field = CRM_Utils_Array::value($elementName, $this->_fields);
             // hack for profile, add location id
             if (!$field) {
                 if ($elementType && !is_numeric($elementType)) {
                     //fix for CRM-882( to handle phone types )
                     if (is_numeric($name)) {
                         $field =& CRM_Utils_Array::value($elementName . "-Primary{$elementType}", $this->_fields);
                     } else {
                         $field =& CRM_Utils_Array::value($elementName . "-{$locationTypeId}{$elementType}", $this->_fields);
                     }
                 } else {
                     if (is_numeric($name)) {
                         //this for phone type to work
                         if ($elementName == "phone") {
                             $field =& CRM_Utils_Array::value($elementName . "-Primary" . $elementType, $this->_fields);
                         } else {
                             $field =& CRM_Utils_Array::value($elementName . "-Primary", $this->_fields);
                         }
                     } else {
                         //this is for phone type to work for profile edit
                         if ($elementName == "phone") {
                             $field =& CRM_Utils_Array::value($elementName . "-{$locationTypeId}{$elementType}", $this->_fields);
                         } else {
                             $field =& CRM_Utils_Array::value($elementName . "-{$locationTypeId}", $this->_fields);
                         }
                     }
                 }
             }
             // check if there is a value, if so also add to where Clause
             $addWhere = false;
             if ($this->_params) {
                 $nm = $elementName;
                 if (isset($locationTypeId)) {
                     $nm .= "-{$locationTypeId}";
                 }
                 if (!is_numeric($elementType)) {
                     $nm .= "{$elementType}";
                 }
                 foreach ($this->_params as $id => $values) {
                     if ($values[0] == $nm || in_array($elementName, array('phone', 'im')) && strpos($values[0], $nm) !== false) {
                         $addWhere = true;
                         $addWhereCount++;
                         break;
                     }
                 }
             }
             if ($field && isset($field['where'])) {
                 list($tableName, $fieldName) = explode('.', $field['where'], 2);
                 $tName = $name . '-' . substr($tableName, 8) . $elementType;
                 $fieldName = $fieldName;
                 if (isset($tableName)) {
                     $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
                     $this->_element["{$tName}_id"] = 1;
                     if (substr($tName, -15) == '-state_province') {
                         // FIXME: hack to fix CRM-1900
                         require_once 'CRM/Core/BAO/Preferences.php';
                         $a = CRM_Core_BAO_Preferences::value('address_format');
                         if (substr_count($a, 'state_province_name') > 0) {
                             $this->_select["{$name}-{$elementFullName}"] = "`{$tName}`.name as `{$name}-{$elementFullName}`";
                         } else {
                             $this->_select["{$name}-{$elementFullName}"] = "`{$tName}`.abbreviation as `{$name}-{$elementFullName}`";
                         }
                     } else {
                         if (substr($elementFullName, 0, 2) == 'im') {
                             $provider = "{$name}-{$elementFullName}-provider_id";
                             $this->_select[$provider] = "`{$tName}`.provider_id as `{$name}-{$elementFullName}-provider_id`";
                             $this->_element[$provider] = 1;
                         }
                         $this->_select["{$name}-{$elementFullName}"] = "`{$tName}`.{$fieldName} as `{$name}-{$elementFullName}`";
                     }
                     $this->_element["{$name}-{$elementFullName}"] = 1;
                     if (!CRM_Utils_Array::value("`{$tName}`", $processed)) {
                         $processed["`{$tName}`"] = 1;
                         $newName = $tableName . '_' . $index;
                         switch ($tableName) {
                             case 'civicrm_phone':
                             case 'civicrm_email':
                             case 'civicrm_im':
                             case 'civicrm_openid':
                                 $this->_tables[$tName] = "\nLEFT JOIN {$tableName} `{$tName}` ON contact_a.id = `{$tName}`.contact_id AND `{$tName}`.{$lCond}";
                                 // this special case to add phone type
                                 if ($cond) {
                                     $this->_tables[$tName] .= " AND `{$tName}`.{$cond} ";
                                 }
                                 //build locationType join
                                 $locationTypeJoin[$tName] = " ( `{$tName}`.location_type_id = {$ltName}.id )";
                                 if ($addWhere) {
                                     $this->_whereTables[$tName] = $this->_tables[$tName];
                                 }
                                 break;
                             case 'civicrm_state_province':
                                 $this->_tables[$tName] = "\nLEFT JOIN {$tableName} `{$tName}` ON `{$tName}`.id = {$aName}.state_province_id";
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                     $this->_whereTables[$tName] = $this->_tables[$tName];
                                 }
                                 break;
                             case 'civicrm_country':
                                 $this->_tables[$newName] = "\nLEFT JOIN {$tableName} `{$tName}` ON `{$tName}`.id = {$aName}.country_id";
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                     $this->_whereTables[$newName] = $this->_tables[$newName];
                                 }
                                 break;
                             case 'civicrm_county':
                                 $this->_tables[$newName] = "\nLEFT JOIN {$tableName} `{$tName}` ON `{$tName}`.id = {$aName}.county_id";
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                     $this->_whereTables[$newName] = $this->_tables[$newName];
                                 }
                                 break;
                             default:
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                 }
                                 break;
                         }
                     }
                 }
             }
         }
         // add location type  join
         $ltypeJoin = "\nLEFT JOIN civicrm_location_type {$ltName} ON ( " . implode('OR', $locationTypeJoin) . " )";
         $this->_tables[$locationTypeName] = $ltypeJoin;
         // table should be present in $this->_whereTables,
         // to add its condition in location type join, CRM-3939.
         if ($addWhereCount) {
             $locClause = array();
             foreach ($this->_whereTables as $tableName => $clause) {
                 if (CRM_Utils_Array::value($tableName, $locationTypeJoin)) {
                     $locClause[] = $locationTypeJoin[$tableName];
                 }
             }
             if (!empty($locClause)) {
                 $this->_whereTables[$locationTypeName] = "\nLEFT JOIN civicrm_location_type {$ltName} ON ( " . implode('OR', $locClause) . " )";
             }
         }
     }
     if (!empty($addressCustomFieldIds)) {
         require_once 'CRM/Core/BAO/CustomQuery.php';
         $cfIDs = $addressCustomFieldIds;
         $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
         foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
             foreach ($locTypeName as $name => $dnc) {
                 $fieldName = "{$name}-custom_{$cfID}";
                 $tName = "{$name}-address-custom";
                 $aName = "`{$name}-address-custom`";
                 $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
                 $this->_element["{$tName}_id"] = 1;
                 $this->_select[$fieldName] = "`{$tName}`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
                 $this->_element[$fieldName] = 1;
                 $this->_tables[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} {$aName} ON ({$aName}.entity_id = `{$name}-address`.id)";
             }
         }
     }
 }
Пример #23
0
 function getLocBlock()
 {
     // i wish i could retrieve loc block info based on loc_block_id,
     // Anyway, lets retrieve an event which has loc_block_id set to 'lbid'.
     if ($_POST['lbid']) {
         $params = array('1' => array($_POST['lbid'], 'Integer'));
         $eventId = CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_event WHERE loc_block_id=%1 LIMIT 1', $params);
     }
     // now lets use the event-id obtained above, to retrieve loc block information.
     if ($eventId) {
         $params = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
         require_once 'CRM/Core/BAO/Location.php';
         // second parameter is of no use, but since required, lets use the same variable.
         $location = CRM_Core_BAO_Location::getValues($params, $params);
     }
     $result = array();
     require_once 'CRM/Core/BAO/Preferences.php';
     $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true);
     // lets output only required fields.
     foreach ($addressOptions as $element => $isSet) {
         if ($isSet && !in_array($element, array('im', 'openid'))) {
             if (in_array($element, array('country', 'state_province', 'county'))) {
                 $element .= '_id';
             } else {
                 if ($element == 'address_name') {
                     $element = 'name';
                 }
             }
             $fld = "address[1][{$element}]";
             $value = CRM_Utils_Array::value($element, $location['address'][1]);
             $value = $value ? $value : "";
             $result[str_replace(array('][', '[', "]"), array('_', '_', ''), $fld)] = $value;
         }
     }
     foreach (array('email', 'phone_type_id', 'phone') as $element) {
         $block = $element == 'phone_type_id' ? 'phone' : $element;
         for ($i = 1; $i < 3; $i++) {
             $fld = "{$block}[{$i}][{$element}]";
             $value = CRM_Utils_Array::value($element, $location[$block][$i]);
             $value = $value ? $value : "";
             $result[str_replace(array('][', '[', "]"), array('_', '_', ''), $fld)] = $value;
         }
     }
     // set the message if loc block is being used by more than one event.
     require_once 'CRM/Event/BAO/Event.php';
     $result['count_loc_used'] = CRM_Event_BAO_Event::countEventsUsingLocBlockId($_POST['lbid']);
     echo json_encode($result);
     exit;
 }
Пример #24
0
 /**
  * class constructor
  *
  * @return CRM_Core_Smarty
  * @access private
  */
 function __construct()
 {
     parent::__construct();
     $config =& CRM_Core_Config::singleton();
     if (isset($config->customTemplateDir) && $config->customTemplateDir) {
         $this->template_dir = array($config->customTemplateDir, $config->templateDir);
     } else {
         $this->template_dir = $config->templateDir;
     }
     $this->compile_dir = $config->templateCompileDir;
     //Check for safe mode CRM-2207
     if (ini_get('safe_mode')) {
         $this->use_sub_dirs = false;
     } else {
         $this->use_sub_dirs = true;
     }
     $this->plugins_dir = array($config->smartyDir . 'plugins', $config->pluginsDir);
     // add the session and the config here
     $session =& CRM_Core_Session::singleton();
     $this->assign_by_ref('config', $config);
     $this->assign_by_ref('session', $session);
     // check default editor and assign to template, store it in session to reduce db calls
     $defaultWysiwygEditor = $session->get('defaultWysiwygEditor');
     if (!$defaultWysiwygEditor && !CRM_Core_Config::isUpgradeMode()) {
         require_once 'CRM/Core/BAO/Preferences.php';
         $defaultWysiwygEditor = CRM_Core_BAO_Preferences::value('editor_id');
         $session->set('defaultWysiwygEditor', $defaultWysiwygEditor);
     }
     $this->assign('defaultWysiwygEditor', $defaultWysiwygEditor);
     global $tsLocale;
     $this->assign('langSwitch', CRM_Core_I18n::languages(true));
     $this->assign('tsLocale', $tsLocale);
     //check if logged in use has access CiviCRM permission and build menu
     require_once 'CRM/Core/Permission.php';
     $buildNavigation = CRM_Core_Permission::check('access CiviCRM');
     $this->assign('buildNavigation', $buildNavigation);
     if (!CRM_Core_Config::isUpgradeMode() && $buildNavigation) {
         require_once 'CRM/Core/BAO/Navigation.php';
         $contactID = $session->get('userID');
         if ($contactID) {
             $navigation =& CRM_Core_BAO_Navigation::createNavigation($contactID);
             $this->assign('navigation', $navigation);
         }
     }
     $this->register_function('crmURL', array('CRM_Utils_System', 'crmURL'));
     $printerFriendly = CRM_Utils_System::makeURL('snippet', false, false) . '2';
     $this->assign('printerFriendly', $printerFriendly);
 }
 public function updateConstructedNames()
 {
     require_once 'CRM/Utils/Address.php';
     require_once 'CRM/Core/BAO/Preferences.php';
     require_once 'CRM/Core/DAO.php';
     require_once 'CRM/Core/PseudoConstant.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     //handle individuals using settings in the system
     $query = "SELECT * FROM civicrm_contact WHERE contact_type = 'Individual';";
     $dao = CRM_Core_DAO::executeQuery($query);
     $prefixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
     $suffixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id');
     $tokens = array();
     CRM_Utils_Hook::tokens($tokens);
     $tokenFields = array();
     foreach ($tokens as $category => $catTokens) {
         foreach ($catTokens as $token) {
             $tokenFields[] = $token;
         }
     }
     //determine sort name construction
     $sortFormat = CRM_Core_BAO_Preferences::value('sort_name_format');
     $sortFormat = str_replace('contact.', '', $sortFormat);
     //determine display name construction
     $displayFormat = CRM_Core_BAO_Preferences::value('display_name_format');
     $displayFormat = str_replace('contact.', '', $displayFormat);
     while ($dao->fetch()) {
         $contactID = $dao->id;
         $params = array('first_name' => $dao->first_name, 'middle_name' => $dao->middle_name, 'last_name' => $dao->last_name, 'prefix_id' => $dao->prefix_id, 'suffix_id' => $dao->suffix_id);
         $params['individual_prefix'] = $prefixes[$dao->prefix_id];
         $params['individual_suffix'] = $suffixes[$dao->suffix_id];
         $sortName = CRM_Utils_Address::format($params, $sortFormat, FALSE, FALSE, TRUE, $tokenFields);
         $sortName = trim(CRM_Core_DAO::escapeString($sortName));
         $displayName = CRM_Utils_Address::format($params, $displayFormat, FALSE, FALSE, TRUE, $tokenFields);
         $displayName = trim(CRM_Core_DAO::escapeString($displayName));
         //check for email
         if (empty($sortName) || empty($displayName)) {
             $email = NULL;
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contactID);
             if (empty($email)) {
                 $email = $contactID;
             }
             if (empty($sortName)) {
                 $sortName = $email;
             }
             if (empty($displayName)) {
                 $displayName = $email;
             }
         }
         //update record
         $updateQuery = "UPDATE civicrm_contact SET display_name = '{$displayName}', sort_name = '{$sortName}' WHERE id = {$contactID};";
         CRM_Core_DAO::executeQuery($updateQuery);
     }
     //end indiv
     echo "\n Individuals recached... ";
     //set organizations
     $query = "UPDATE civicrm_contact\n\t\t          SET display_name = organization_name,\n\t\t\t\t      sort_name = organization_name\n\t\t\t      WHERE contact_type = 'Organization';";
     $dao = CRM_Core_DAO::executeQuery($query);
     echo "\n Organizations recached... ";
     //set households
     $query = "UPDATE civicrm_contact\n\t\t          SET display_name = household_name,\n\t\t\t\t      sort_name = household_name\n\t\t\t      WHERE contact_type = 'Household';";
     $dao = CRM_Core_DAO::executeQuery($query);
     echo "\n Households recached... ";
 }
Пример #26
0
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     $this->applyFilter('__ALL__', 'trim');
     $this->addDate('renewal_date', ts('Date Renewal Entered'), false, array('formatType' => 'activityDate'));
     if (!$this->_mode) {
         $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), null, array('onclick' => "checkPayment();"));
         require_once 'CRM/Contribute/PseudoConstant.php';
         $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType());
         $this->add('text', 'total_amount', ts('Amount'));
         $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
         $this->add('select', 'payment_instrument_id', ts('Paid By'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), false, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
         $this->add('text', 'trxn_id', ts('Transaction ID'));
         $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id'));
         $this->add('select', 'contribution_status_id', ts('Payment Status'), CRM_Contribute_PseudoConstant::contributionStatus());
         $this->add('text', 'check_number', ts('Check Number'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number'));
     }
     $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), null, array('onclick' => "return showHideByValue('send_receipt','','notice','table-row','radio',false);"));
     $this->add('textarea', 'receipt_text_renewal', ts('Renewal Message'));
     if ($this->_mode) {
         $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, true);
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::buildCreditCard($this, true);
     }
     require_once 'CRM/Contact/BAO/Contact/Location.php';
     // Retrieve the name and email of the contact - this will be the TO for receipt email
     list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
     $this->assign('email', $this->_contributorEmail);
     require_once "CRM/Core/BAO/Preferences.php";
     $mailingInfo =& CRM_Core_BAO_Preferences::mailingPreferences();
     $this->assign('outBound_option', $mailingInfo['outBound_option']);
     $this->addFormRule(array('CRM_Member_Form_MembershipRenewal', 'formRule'));
 }
Пример #27
0
 function upgrade($rev)
 {
     // fix CRM-5270: if civicrm_report_instance.description is localised,
     // recreate it based on the first locale’s description_xx_YY contents
     // and drop all the description_xx_YY columns
     if (!CRM_Core_DAO::checkFieldExists('civicrm_report_instance', 'description')) {
         require_once 'CRM/Core/DAO/Domain.php';
         $domain = new CRM_Core_DAO_Domain();
         $domain->find(true);
         $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
         CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_report_instance ADD description VARCHAR(255)");
         CRM_Core_DAO::executeQuery("UPDATE civicrm_report_instance SET description = description_{$locales[0]}");
         CRM_Core_DAO::executeQuery("DROP TRIGGER civicrm_report_instance_before_insert");
         foreach ($locales as $locale) {
             CRM_Core_DAO::executeQuery("DROP VIEW civicrm_report_instance_{$locale}");
             CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_report_instance DROP description_{$locale}");
         }
     }
     //We execute some part of php after sql and then again sql
     //So using conditions for skipping some part of sql CRM-4575
     $upgrade =& new CRM_Upgrade_Form();
     //Run the SQL file (1)
     $upgrade->processSQL($rev);
     //replace  with ; in report instance
     $sql = "UPDATE civicrm_report_instance \n                       SET form_values = REPLACE(form_values,'#',';') ";
     CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     //delete unnecessary activities
     $bulkEmailID = CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name');
     if ($bulkEmailID) {
         $mailingActivityIds = array();
         $query = " \n            SELECT max( ca.id ) as aid, \n                   ca.source_record_id sid\n            FROM civicrm_activity ca\n            WHERE ca.activity_type_id = %1 \n            GROUP BY ca.source_record_id";
         $params = array(1 => array($bulkEmailID, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             $updateQuery = "\n                UPDATE civicrm_activity_target cat, civicrm_activity ca \n                    SET cat.activity_id = {$dao->aid}  \n                WHERE ca.source_record_id IS NOT NULL   AND\n                      ca.activity_type_id = %1          AND \n                      ca.id <> {$dao->aid}              AND \n                      ca.source_record_id = {$dao->sid} AND \n                      ca.id = cat.activity_id";
             $updateParams = array(1 => array($bulkEmailID, 'Integer'));
             CRM_Core_DAO::executeQuery($updateQuery, $updateParams);
             $deleteQuery = " \n                DELETE ca.* \n                FROM civicrm_activity ca \n                WHERE ca.source_record_id IS NOT NULL  AND \n                      ca.activity_type_id = %1         AND \n                      ca.id <> {$dao->aid}             AND \n                      ca.source_record_id = {$dao->sid}";
             $deleteParams = array(1 => array($bulkEmailID, 'Integer'));
             CRM_Core_DAO::executeQuery($deleteQuery, $deleteParams);
         }
     }
     //CRM-4453
     //lets insert column in civicrm_aprticipant table
     $query = "\n        ALTER TABLE `civicrm_participant` \n            ADD `fee_currency` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL COMMENT '3 character string, value derived from config setting.' AFTER `discount_id`";
     CRM_Core_DAO::executeQuery($query);
     //get currency from contribution table if exists/default
     //insert currency when fee_amount != NULL or event is paid.
     $query = "\n        SELECT  civicrm_participant.id \n        FROM    civicrm_participant\n            LEFT JOIN  civicrm_event \n                   ON ( civicrm_participant.event_id = civicrm_event.id )\n        WHERE  civicrm_participant.fee_amount IS NOT NULL OR \n               civicrm_event.is_monetary = 1";
     $participant = CRM_Core_DAO::executeQuery($query);
     while ($participant->fetch()) {
         $query = "\n            SELECT civicrm_contribution.currency \n            FROM   civicrm_contribution, \n                   civicrm_participant_payment\n            WHERE  civicrm_contribution.id = civicrm_participant_payment.contribution_id AND  \n                   civicrm_participant_payment.participant_id = {$participant->id}";
         $currencyID = CRM_Core_DAO::singleValueQuery($query);
         if (!$currencyID) {
             $config =& CRM_Core_Config::singleton();
             $currencyID = $config->defaultCurrency;
         }
         //finally update participant record.
         CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participant->id, 'fee_currency', $currencyID);
     }
     //CRM-4575
     //check whether {contact.name} is set in mailing labels
     require_once 'CRM/Core/BAO/Preferences.php';
     $mailingFormat = CRM_Core_BAO_Preferences::value('mailing_format');
     $addNewAddressee = true;
     if (strpos($mailingFormat, '{contact.contact_name}') === false) {
         $addNewAddressee = false;
     } else {
         //else compare individual name format with default individual addressee.
         $individualNameFormat = CRM_Core_BAO_Preferences::value('individual_name_format');
         $defaultAddressee = CRM_Core_OptionGroup::values('addressee', false, false, false, " AND v.filter = 1 AND v.is_default =  1", 'label');
         if (array_search($individualNameFormat, $defaultAddressee) !== false) {
             $addNewAddressee = false;
         }
     }
     require_once 'CRM/Utils/System.php';
     $docURL = CRM_Utils_System::docURL2('Update Greetings and Address Data for Contacts', false, null, null, 'color: white; text-decoration: underline;');
     if ($addNewAddressee) {
         //otherwise insert new token in addressee and set as a default
         $addresseeGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'addressee', 'id', 'name');
         $optionValueParams = array('label' => $individualNameFormat, 'is_active' => 1, 'contactOptions' => 1, 'filter' => 1, 'is_default' => 1, 'reset_default_for' => array('filter' => "0, 1"));
         $action = CRM_Core_Action::ADD;
         $addresseeGroupParams = array('name' => 'addressee');
         $fieldValues = array('option_group_id' => $addresseeGroupId);
         $weight = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
         $optionValueParams['weight'] = $weight;
         $addresseeToken = CRM_Core_OptionValue::addOptionValue($optionValueParams, $addresseeGroupParams, $action, $optionId = null);
         $afterUpgradeMessage = ts("During this upgrade, Postal Addressee values have been stored for each contact record using the system default format - %2.You will need to run the included command-line script to update your Individual contact records to use the \"Individual Name Format\" previously specified for your site %1", array(1 => $docURL, 2 => array_pop($defaultAddressee)));
     } else {
         $afterUpgradeMessage = ts("Email Greeting, Postal Greeting and Postal Addressee values have been stored for all contact records based on the system default formats. If you want to use a different format for any of these contact fields - you can run the provided command line script to update contacts to a different format %1 ", array(1 => $docURL));
     }
     //replace contact.contact_name with contact.addressee in civicrm_preference.mailing_format
     $updateQuery = "\n        UPDATE civicrm_preferences \n               SET `mailing_format` = \n                    replace(`mailing_format`, '{contact.contact_name}','{contact.addressee}')";
     CRM_Core_DAO::executeQuery($updateQuery);
     //drop column individual_name_format
     $alterQuery = "\n        ALTER TABLE `civicrm_preferences`\n              DROP `individual_name_format`";
     CRM_Core_DAO::executeQuery($alterQuery);
     //set status message for default greetings
     $template =& CRM_Core_Smarty::singleton();
     $template->assign('afterUpgradeMessage', $afterUpgradeMessage);
 }
Пример #28
0
 /**
  * Function to build user dashboard
  *
  * @return none
  * @access public
  */
 function buildUserDashBoard()
 {
     //build component selectors
     $dashboardElements = array();
     $config =& CRM_Core_Config::singleton();
     require_once 'CRM/Core/BAO/Preferences.php';
     $this->_userOptions = CRM_Core_BAO_Preferences::valueOptions('user_dashboard_options');
     $components = CRM_Core_Component::getEnabledComponents();
     foreach ($components as $name => $component) {
         $elem = $component->getUserDashboardElement();
         if (!$elem) {
             continue;
         }
         if (CRM_Utils_Array::value($name, $this->_userOptions) && (CRM_Core_Permission::access($component->name) || CRM_Core_Permission::check($elem['perm'][0]))) {
             $userDashboard = $component->getUserDashboardObject();
             $dashboardElements[] = array('templatePath' => $userDashboard->getTemplateFileName(), 'sectionTitle' => $elem['title'], 'weight' => $elem['weight']);
             $userDashboard->run();
         }
     }
     $sectionName = 'Permissioned Orgs';
     if ($this->_userOptions[$sectionName]) {
         $dashboardElements[] = array('templatePath' => 'CRM/Contact/Page/View/Relationship.tpl', 'sectionTitle' => ts('Your Contacts / Organizations'), 'weight' => 40);
         $links =& self::links();
         $currentRelationships = CRM_Contact_BAO_Relationship::getRelationship($this->_contactId, CRM_Contact_BAO_Relationship::CURRENT, 0, 0, 0, $links, null, true);
         $this->assign('currentRelationships', $currentRelationships);
     }
     if ($this->_userOptions['PCP']) {
         require_once 'CRM/Contribute/BAO/PCP.php';
         $dashboardElements[] = array('templatePath' => 'CRM/Contribute/Page/PcpUserDashboard.tpl', 'sectionTitle' => ts('Personal Campaign Pages'), 'weight' => 40);
         list($pcpBlock, $pcpInfo) = CRM_Contribute_BAO_PCP::getPcpDashboardInfo($this->_contactId);
         $this->assign('pcpBlock', $pcpBlock);
         $this->assign('pcpInfo', $pcpInfo);
     }
     require_once 'CRM/Utils/Sort.php';
     usort($dashboardElements, array('CRM_Utils_Sort', 'cmpFunc'));
     $this->assign('dashboardElements', $dashboardElements);
     if ($this->_userOptions['Groups']) {
         $this->assign('showGroup', true);
         //build group selector
         require_once "CRM/Contact/Page/View/UserDashBoard/GroupContact.php";
         $gContact = new CRM_Contact_Page_View_UserDashBoard_GroupContact();
         $gContact->run();
     } else {
         $this->assign('showGroup', false);
     }
 }
Пример #29
0
 /**
  * global validation rules for the form
  *
  * @param array $fields     posted values of the form
  * @param array $errors     list of errors to be posted back to the form
  * @param int   $contactId  contact id if doing update.
  *
  * @return $primaryID emal/openId
  * @static
  * @access public
  */
 static function formRule(&$fields, &$errors, $contactId = null)
 {
     $config =& CRM_Core_Config::singleton();
     if ($config->civiHRD && !isset($fields['tag'])) {
         $errors["tag"] = ts('Please select at least one tag.');
     }
     // validations.
     //1. for each block only single value can be marked as is_primary = true.
     //2. location type id should be present if block data present.
     //3. check open id across db and other each block for duplicate.
     //4. at least one location should be primary.
     //5. also get primaryID from email or open id block.
     // take the location blocks.
     $blocks = CRM_Core_BAO_Preferences::valueOptions('contact_edit_options', true, null, false, 'name', true, 'AND v.filter = 1');
     $otherEditOptions = CRM_Core_BAO_Preferences::valueOptions('contact_edit_options', true, null, false, 'name', true, 'AND v.filter = 0');
     //get address block inside.
     if (array_key_exists('Address', $otherEditOptions)) {
         $blocks['Address'] = $otherEditOptions['Address'];
     }
     $openIds = array();
     $primaryID = false;
     foreach ($blocks as $name => $label) {
         $hasData = $hasPrimary = array();
         $name = strtolower($name);
         if (is_array($fields[$name])) {
             foreach ($fields[$name] as $instance => $blockValues) {
                 $dataExists = self::blockDataExists($blockValues);
                 if (!$dataExists && $name == 'address' && $instance == 1) {
                     $dataExists = CRM_Utils_Array::value('use_household_address', $fields);
                 }
                 if ($dataExists) {
                     $hasData[] = $instance;
                     if (CRM_Utils_Array::value('is_primary', $blockValues)) {
                         $hasPrimary[] = $instance;
                         if (!$primaryID && in_array($name, array('email', 'openid')) && CRM_Utils_Array::value($name, $blockValues)) {
                             $primaryID = $blockValues[$name];
                         }
                     }
                     if (!CRM_Utils_Array::value('location_type_id', $blockValues)) {
                         $errors["{$name}[{$instance}][location_type_id]"] = ts('The Location Type should be set if there is  %1 information.', array(1 => $label));
                     }
                 }
                 if ($name == 'openid' && CRM_Utils_Array::value($name, $blockValues)) {
                     require_once 'CRM/Core/DAO/OpenID.php';
                     $oid =& new CRM_Core_DAO_OpenID();
                     $oid->openid = $openIds[$instance] = CRM_Utils_Array::value($name, $blockValues);
                     $cid = isset($contactId) ? $contactId : 0;
                     if ($oid->find(true) && $oid->contact_id != $cid) {
                         $errors["{$name}[{$instance}][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
                     }
                 }
             }
             if (empty($hasPrimary) && !empty($hasData)) {
                 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
             }
             if (count($hasPrimary) > 1) {
                 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.', array(1 => $label));
             }
         }
     }
     //do validations for all opend ids they should be distinct.
     if (!empty($openIds) && count(array_unique($openIds)) != count($openIds)) {
         foreach ($openIds as $instance => $value) {
             if (!array_key_exists($instance, array_unique($openIds))) {
                 $errors["openid[{$instance}][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
             }
         }
     }
     return $primaryID;
 }
Пример #30
0
 /** 
  * Function to build the form 
  * 
  * @return None 
  * @access public 
  */
 public function buildQuickForm()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if ($this->_context == 'standalone') {
         require_once 'CRM/Contact/Form/NewContact.php';
         CRM_Contact_Form_NewContact::buildQuickForm($this);
     }
     $showAdditionalInfo = false;
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     //fix to load honoree pane on edit.
     $defaults = array();
     if ($this->_honorID) {
         $defaults['hidden_Honoree'] = 1;
     }
     $paneNames = array('Honoree Information' => 'Honoree', 'Payment Reminders' => 'PaymentReminders');
     foreach ($paneNames as $name => $type) {
         $urlParams = "snippet=4&formType={$type}";
         $allPanes[$name] = array('url' => CRM_Utils_System::url('civicrm/contact/view/pledge', $urlParams), 'open' => 'false', 'id' => $type);
         //see if we need to include this paneName in the current form
         if ($this->_formType == $type || CRM_Utils_Array::value("hidden_{$type}", $_POST) || CRM_Utils_Array::value("hidden_{$type}", $defaults)) {
             $showAdditionalInfo = true;
             $allPanes[$name]['open'] = 'true';
         }
         eval('CRM_Contribute_Form_AdditionalInfo::build' . $type . '( $this );');
     }
     $this->assign('allPanes', $allPanes);
     $this->assign('showAdditionalInfo', $showAdditionalInfo);
     if ($this->_formType) {
         $this->assign('formType', $this->_formType);
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     //pledge fields.
     $attributes = CRM_Core_DAO::getAttribute('CRM_Pledge_DAO_Pledge');
     $this->assign('isPending', $this->_isPending);
     $js = array('onblur' => "calculatedPaymentAmount( );", 'onkeyup' => "calculatedPaymentAmount( );");
     $element =& $this->add('text', 'amount', ts('Total Pledge Amount'), array_merge($attributes['pledge_amount'], $js), true);
     $this->addRule('amount', ts('Please enter a valid monetary amount.'), 'money');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'installments', ts('To be paid in'), array_merge($attributes['installments'], $js), true);
     $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_interval', ts('every'), $attributes['frequency_interval'], true);
     $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     // Fix frequency unit display for use with frequency_interval
     $freqUnitsDisplay = array();
     foreach ($this->_freqUnits as $val => $label) {
         $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $val));
     }
     $element =& $this->add('select', 'frequency_unit', ts('Frequency'), array('' => ts('- select -')) + $freqUnitsDisplay, true);
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], true);
     $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 'READONLY'));
     //add various dates
     if (!$this->_id || $this->_isPending) {
         $this->addDate('create_date', ts('Pledge Made'));
         $this->addDate('start_date', ts('Payments Start'));
     }
     if ($this->_id && !$this->_isPending) {
         $eachPaymentAmount = floor($this->_values['amount'] / $this->_values['installments']);
         $this->assign("eachPaymentAmount", $eachPaymentAmount);
         $this->assign("hideCalender", true);
     }
     if (CRM_Utils_Array::value('status_id', $this->_values) != array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus())) {
         $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), null, array('onclick' => "return showHideByValue('is_acknowledge','','acknowledgeDate','table-row','radio',true);"));
     }
     $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
     $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType(), true);
     $pageIds = array();
     CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table', 'civicrm_contribution_page', $pageIds, array('entity_id'));
     $pages = CRM_Contribute_PseudoConstant::contributionPage();
     $pledgePages = array();
     foreach ($pageIds as $key => $value) {
         $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
     }
     $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'), array('' => ts('- select -')) + $pledgePages);
     require_once "CRM/Core/BAO/Preferences.php";
     $mailingInfo =& CRM_Core_BAO_Preferences::mailingPreferences();
     $this->assign('outBound_option', $mailingInfo['outBound_option']);
     //build custom data
     CRM_Custom_Form_Customdata::buildQuickForm($this);
     // make this form an upload since we dont know if the custom data injected dynamically
     // is of type file etc $uploadNames = $this->get( 'uploadNames' );
     $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save'), 'js' => array('onclick' => "return verify( );"), 'isDefault' => true), array('type' => 'upload', 'name' => ts('Save and New'), 'js' => array('onclick' => "return verify( );"), 'subName' => 'new'), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->freeze();
     }
 }