Example #1
0
 /**
  * Returns the list of fields that can be exported
  *
  * @param bool $prefix
  *
  * @return array
  */
 static function &export($prefix = false)
 {
     if (!self::$_export) {
         self::$_export = array();
         $fields = self::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     self::$_export['address'] =& $fields[$name];
                 } else {
                     self::$_export[$name] =& $fields[$name];
                 }
             }
         }
         self::$_export = array_merge(self::$_export, CRM_Core_DAO_County::export(true));
         self::$_export = array_merge(self::$_export, CRM_Core_DAO_StateProvince::export(true));
         self::$_export = array_merge(self::$_export, CRM_Core_DAO_Country::export(true));
     }
     return self::$_export;
 }
Example #2
0
/**
 * function convert params to v3.0 format before add location.
 */
function _civicrm_format_params_v2_to_v3(&$params, $locationTypeId = null)
{
    // get the loc type id.
    if (!$locationTypeId) {
        // get location type.
        $locationTypeId = CRM_Utils_Array::value('location_type_id', $params);
        if (!$locationTypeId && array_key_exists('location_type', $params)) {
            require_once 'CRM/Core/PseudoConstant.php';
            $locTypes =& CRM_Core_PseudoConstant::locationType();
            $locType = $params['location_type'];
            if (is_array($params['location_type'])) {
                $locType = array_pop($params['location_type']);
            }
            $locationTypeId = CRM_Utils_Array::key($locType, $locTypes);
        }
    }
    // convert params into v3.0 format.
    $primary = $billing = array();
    $blocks = array('Email', 'Phone', 'IM', 'OpenID');
    // format params array.
    $firstBlockCount = null;
    foreach ($blocks as $block) {
        require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_DAO_" . $block) . ".php";
        eval('$fields =& CRM_Core_DAO_' . $block . '::fields( );');
        $name = strtolower($block);
        $blockCount = 0;
        if (CRM_Utils_Array::value($name, $params)) {
            if (is_array($params[$name])) {
                $values = $params[$name];
                $params[$name] = array();
                foreach ($values as $val) {
                    _civicrm_store_values($fields, $val, $params[$name][++$blockCount]);
                    // check for primary and billing.
                    if (CRM_Utils_Array::value('is_primary', $val)) {
                        $primary[$name][$blockCount] = true;
                    }
                    if (CRM_Utils_Array::value('is_billing', $val)) {
                        $primary[$name][$blockCount] = true;
                    }
                    if (!$firstBlockCount) {
                        $firstBlockCount = $blockCount;
                    }
                }
            } else {
                //need to get ids.
                if (in_array($name, array('im', 'phone'))) {
                    require_once 'CRM/Core/PseudoConstant.php';
                    if ($name == 'im') {
                        CRM_Utils_Array::lookupValue($params, 'provider', CRM_Core_PseudoConstant::IMProvider(), true);
                    } else {
                        CRM_Utils_Array::lookupValue($params, 'phone_type', CRM_Core_PseudoConstant::phoneType(), true);
                    }
                }
                $locValues[$name] = array();
                _civicrm_store_values($fields, $params, $locValues[$name][++$blockCount]);
                $params[$name] = $locValues[$name];
                $firstBlockCount = $blockCount;
                unset($locValues[$name]);
            }
            // make first block as default primary when is_primary
            // is not set in sub array and set in main params array.
            if (!CRM_Utils_Array::value($name, $primary) && CRM_Utils_Array::value('is_primary', $params)) {
                $primary[$name][$firstBlockCount] = true;
                $params[$name][$firstBlockCount]['is_primary'] = true;
            }
            if (!CRM_Utils_Array::value($name, $billing) && CRM_Utils_Array::value('is_billing', $params)) {
                $billing[$name][$firstBlockCount] = true;
                $params[$name][$firstBlockCount]['is_billing'] = true;
            }
        }
    }
    //get the address fields.
    $addressCount = 1;
    $ids = array('county', 'country_id', 'country', 'state_province_id', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name', 'city', 'street_address');
    $addressTaken = false;
    foreach ($ids as $id) {
        if (array_key_exists($id, $params)) {
            if (!$addressTaken) {
                require_once 'CRM/Core/DAO/Address.php';
                $fields =& CRM_Core_DAO_Address::fields();
                _civicrm_store_values($fields, $params, $params['address'][$addressCount]);
                $addressTaken = true;
            }
            $params['address'][$addressCount][$id] = $params[$id];
            unset($params[$id]);
        }
    }
    // format state and country.
    foreach (array('state_province', 'country') as $field) {
        $fName = $field == 'state_province' ? 'stateProvinceAbbreviation' : 'countryIsoCode';
        if (CRM_Utils_Array::value('address', $params) && CRM_Utils_Array::value($field, $params['address'][$addressCount]) && is_numeric($params['address'][$addressCount][$field])) {
            $fValue =& $params['address'][$addressCount][$field];
            eval('$fValue = CRM_Core_PseudoConstant::' . $fName . '( $fValue );');
            //kill the reference.
            unset($fValue);
        }
    }
    // check for primary address.
    if (CRM_Utils_Array::value('is_primary', $params)) {
        if ($addressTaken) {
            $primary['address'][$addressCount] = true;
            $params['address'][$addressCount]['is_primary'] = true;
        }
        unset($params['is_primary']);
    }
    if (CRM_Utils_Array::value('is_billing', $params)) {
        if ($addressTaken) {
            $billing['address'][$addressCount] = true;
            $params['address'][$addressCount]['is_billing'] = true;
        }
        unset($params['is_billing']);
    }
    // handle primary and billing reset.
    foreach (array('email', 'phone', 'im', 'address', 'openid') as $name) {
        if (!array_key_exists($name, $params) || CRM_Utils_System::isNull($params[$name])) {
            continue;
        }
        $errorMsg = null;
        $primaryBlockIndex = $billingBlockIndex = 0;
        if (array_key_exists($name, $primary)) {
            if (count($primary[$name]) > 1) {
                $errorMsg .= ts("<br />Multiple Primary %1.", array(1 => $block));
            } else {
                $primaryBlockIndex = key($primary[$name]);
            }
        }
        if (array_key_exists($name, $billing)) {
            if (count($billing[$name]) > 1) {
                $errorMsg .= ts("<br />Multiple Billing %1.", array(1 => $block));
            } else {
                $billingBlockIndex = key($billing[$name]);
            }
        }
        if ($errorMsg) {
            return civicrm_create_error($errorMsg);
        }
        foreach ($params[$name] as $count => &$values) {
            if ($primaryBlockIndex && $count != $primaryBlockIndex) {
                $values['is_primary'] = false;
            }
            if ($billingBlockIndex && $count != $billingBlockIndex) {
                $values['is_billing'] = false;
            }
            // get location type if not present in sub array.
            if (!CRM_Utils_Array::value('location_type_id', $values)) {
                $values['location_type_id'] = $locationTypeId;
            }
            //kill the reference.
            unset($values);
        }
    }
    // finally unset location_type and location type id.
    foreach (array('location_type', 'location_type_id') as $f) {
        if (isset($params[$f])) {
            unset($params[$f]);
        }
    }
    return $params;
}
Example #3
0
function processContacts(&$config, $processGeocode, $parseStreetAddress, $start = null, $end = null)
{
    // build where clause.
    $clause = array('( c.id = a.contact_id )');
    if ($start) {
        $clause[] = "( c.id >= {$start} )";
    }
    if ($end) {
        $clause[] = "( c.id <= {$end} )";
    }
    if ($processGeocode) {
        $clause[] = '( a.geo_code_1 is null OR a.geo_code_1 = 0 )';
        $clause[] = '( a.geo_code_2 is null OR a.geo_code_2 = 0 )';
        $clause[] = '( a.country_id is not null )';
    }
    $whereClause = implode(' AND ', $clause);
    $query = "\nSELECT     c.id,\n           a.id as address_id,\n           a.street_address,\n           a.city,\n           a.postal_code,\n           s.name as state,\n           o.name as country\nFROM       civicrm_contact  c\nINNER JOIN civicrm_address        a ON a.contact_id = c.id\nLEFT  JOIN civicrm_country        o ON a.country_id = o.id\nLEFT  JOIN civicrm_state_province s ON a.state_province_id = s.id\nWHERE      {$whereClause}\n  ORDER BY a.id\n";
    $totalGeocoded = $totalAddresses = $totalAddressParsed = 0;
    $dao =& CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
    if ($processGeocode) {
        require_once str_replace('_', DIRECTORY_SEPARATOR, $config->geocodeMethod) . '.php';
    }
    require_once 'CRM/Core/DAO/Address.php';
    require_once 'CRM/Core/BAO/Address.php';
    while ($dao->fetch()) {
        $totalAddresses++;
        $params = array('street_address' => $dao->street_address, 'postal_code' => $dao->postal_code, 'city' => $dao->city, 'state_province' => $dao->state, 'country' => $dao->country);
        $addressParams = array();
        // process geocode.
        if ($processGeocode) {
            // loop through the address removing more information
            // so we can get some geocode for a partial address
            // i.e. city -> state -> country
            $maxTries = 5;
            do {
                if (defined('THROTTLE_REQUESTS') && THROTTLE_REQUESTS) {
                    usleep(50000);
                }
                eval($config->geocodeMethod . '::format( $params, true );');
                array_shift($params);
                $maxTries--;
            } while (!isset($params['geo_code_1']) && $maxTries > 1);
            if (isset($params['geo_code_1'])) {
                $totalGeocoded++;
                $addressParams['geo_code_1'] = $params['geo_code_1'];
                $addressParams['geo_code_2'] = $params['geo_code_2'];
            }
        }
        // parse street address
        if ($parseStreetAddress) {
            $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($dao->street_address);
            $success = true;
            // consider address is automatically parseable,
            // when we should found street_number and street_name
            if (!CRM_Utils_Array::value('street_name', $parsedFields) || !CRM_Utils_Array::value('street_number', $parsedFields)) {
                $success = false;
            }
            // do check for all elements.
            if ($success) {
                $totalAddressParsed++;
            } else {
                // reset element values.
                $parsedFields = array_fill_keys(array_keys($parsedFields), '');
            }
            $addressParams = array_merge($addressParams, $parsedFields);
        }
        // finally update address object.
        if (!empty($addressParams)) {
            $address = new CRM_Core_DAO_Address();
            $address->id = $dao->address_id;
            $address->copyValues($addressParams);
            $address->save();
            $address->free();
        }
    }
    echo ts("Addresses Evaluated: {$totalAddresses}\n");
    if ($processGeocode) {
        echo ts("Addresses Geocoded : {$totalGeocoded}\n");
    }
    if ($parseStreetAddress) {
        echo ts("Street Address Parsed : {$totalAddressParsed}\n");
    }
    return;
}
/**
 * This function format location blocks w/ v3.0 format.
 *
 * @param array $values
 *   The variable(s) to be added.
 * @param array $params
 *   The structured parameter list.
 *
 * @return bool
 */
function _civicrm_api3_deprecated_add_formatted_location_blocks(&$values, &$params)
{
    static $fields = NULL;
    if ($fields == NULL) {
        $fields = array();
    }
    foreach (array('Phone', 'Email', 'IM', 'OpenID', 'Phone_Ext') as $block) {
        $name = strtolower($block);
        if (!array_key_exists($name, $values)) {
            continue;
        }
        if ($name == 'phone_ext') {
            $block = 'Phone';
        }
        // block present in value array.
        if (!array_key_exists($name, $params) || !is_array($params[$name])) {
            $params[$name] = array();
        }
        if (!array_key_exists($block, $fields)) {
            $className = "CRM_Core_DAO_{$block}";
            $fields[$block] =& $className::fields();
        }
        $blockCnt = count($params[$name]);
        // copy value to dao field name.
        if ($name == 'im') {
            $values['name'] = $values[$name];
        }
        _civicrm_api3_store_values($fields[$block], $values, $params[$name][++$blockCnt]);
        if (empty($params['id']) && $blockCnt == 1) {
            $params[$name][$blockCnt]['is_primary'] = TRUE;
        }
        // we only process single block at a time.
        return TRUE;
    }
    // handle address fields.
    if (!array_key_exists('address', $params) || !is_array($params['address'])) {
        $params['address'] = array();
    }
    $addressCnt = 1;
    foreach ($params['address'] as $cnt => $addressBlock) {
        if (CRM_Utils_Array::value('location_type_id', $values) == CRM_Utils_Array::value('location_type_id', $addressBlock)) {
            $addressCnt = $cnt;
            break;
        }
        $addressCnt++;
    }
    if (!array_key_exists('Address', $fields)) {
        require_once 'CRM/Core/DAO/Address.php';
        $fields['Address'] = CRM_Core_DAO_Address::fields();
    }
    // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
    // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
    // the address in CRM_Core_BAO_Address::create method
    if (!empty($values['location_type_id'])) {
        static $customFields = array();
        if (empty($customFields)) {
            $customFields = CRM_Core_BAO_CustomField::getFields('Address');
        }
        // make a copy of values, as we going to make changes
        $newValues = $values;
        foreach ($values as $key => $val) {
            $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
            if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
                // mark an entry in fields array since we want the value of custom field to be copied
                $fields['Address'][$key] = NULL;
                $htmlType = CRM_Utils_Array::value('html_type', $customFields[$customFieldID]);
                switch ($htmlType) {
                    case 'CheckBox':
                    case 'AdvMulti-Select':
                    case 'Multi-Select':
                        if ($val) {
                            $mulValues = explode(',', $val);
                            $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                            $newValues[$key] = array();
                            foreach ($mulValues as $v1) {
                                foreach ($customOption as $v2) {
                                    if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) {
                                        if ($htmlType == 'CheckBox') {
                                            $newValues[$key][$v2['value']] = 1;
                                        } else {
                                            $newValues[$key][] = $v2['value'];
                                        }
                                    }
                                }
                            }
                        }
                        break;
                }
            }
        }
        // consider new values
        $values = $newValues;
    }
    _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
    $addressFields = array('county', 'country', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name');
    foreach ($addressFields as $field) {
        if (array_key_exists($field, $values)) {
            if (!array_key_exists('address', $params)) {
                $params['address'] = array();
            }
            $params['address'][$addressCnt][$field] = $values[$field];
        }
    }
    if ($addressCnt == 1) {
        $params['address'][$addressCnt]['is_primary'] = TRUE;
    }
    return TRUE;
}
/**
 * This function format location blocks w/ v3.0 format.
 *
 * @param array  $values    The variable(s) to be added
 * @param array  $params    The structured parameter list
 *
 * @return bool
 * @access public
 */
function _civicrm_add_formatted_location_blocks(&$values, &$params)
{
    static $fields = NULL;
    if ($fields == NULL) {
        $fields = array();
    }
    foreach (array('Phone', 'Email', 'IM', 'OpenID') as $block) {
        $name = strtolower($block);
        if (!array_key_exists($name, $values)) {
            continue;
        }
        // block present in value array.
        if (!array_key_exists($name, $params) || !is_array($params[$name])) {
            $params[$name] = array();
        }
        if (!array_key_exists($block, $fields)) {
            require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_DAO_" . $block) . ".php";
            eval('$fields[$block] =& CRM_Core_DAO_' . $block . '::fields( );');
        }
        $blockCnt = count($params[$name]);
        // copy value to dao field name.
        if ($name == 'im') {
            $values['name'] = $values[$name];
        }
        _civicrm_store_values($fields[$block], $values, $params[$name][++$blockCnt]);
        if (!CRM_Utils_Array::value('id', $params) && $blockCnt == 1) {
            $params[$name][$blockCnt]['is_primary'] = TRUE;
        }
        // we only process single block at a time.
        return TRUE;
    }
    // handle address fields.
    if (!array_key_exists('address', $params) || !is_array($params['address'])) {
        $params['address'] = array();
    }
    $addressCnt = 1;
    foreach ($params['address'] as $cnt => $addressBlock) {
        if (CRM_Utils_Array::value('location_type_id', $values) == CRM_Utils_Array::value('location_type_id', $addressBlock)) {
            $addressCnt = $cnt;
            break;
        }
        $addressCnt++;
    }
    if (!array_key_exists('Address', $fields)) {
        require_once 'CRM/Core/DAO/Address.php';
        $fields['Address'] = CRM_Core_DAO_Address::fields();
    }
    _civicrm_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
    $addressFields = array('county', 'country', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name');
    foreach ($addressFields as $field) {
        if (array_key_exists($field, $values)) {
            if (!array_key_exists('address', $params)) {
                $params['address'] = array();
            }
            $params['address'][$addressCnt][$field] = $values[$field];
        }
    }
    //Handle Address Custom data
    $fields['address_custom'] = CRM_Core_BAO_CustomField::getFields('Address');
    foreach ($values as $key => $value) {
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            /* check if it's a valid custom field id */
            if (array_key_exists($customFieldID, $fields['address_custom'])) {
                $type = $fields['address_custom'][$customFieldID]['html_type'];
                _civicrm_add_custom_formatted_param($customFieldID, $key, $value, $params['address'][$addressCnt], $type);
            } else {
                return civicrm_create_error('Invalid custom field ID');
            }
        }
    }
    if ($addressCnt == 1) {
        $params['address'][$addressCnt]['is_primary'] = TRUE;
    }
    return TRUE;
}
Example #6
0
 /**
  * @param $config
  * @param $processGeocode
  * @param $parseStreetAddress
  *
  * @return array
  * @throws Exception
  */
 public function processContacts(&$config, $processGeocode, $parseStreetAddress)
 {
     // build where clause.
     $clause = array('( c.id = a.contact_id )');
     $params = array();
     if ($this->start) {
         $clause[] = "( c.id >= %1 )";
         $params[1] = array($this->start, 'Integer');
     }
     if ($this->end) {
         $clause[] = "( c.id <= %2 )";
         $params[2] = array($this->end, 'Integer');
     }
     if ($processGeocode) {
         $clause[] = '( a.geo_code_1 is null OR a.geo_code_1 = 0 )';
         $clause[] = '( a.geo_code_2 is null OR a.geo_code_2 = 0 )';
         $clause[] = '( a.country_id is not null )';
     }
     $whereClause = implode(' AND ', $clause);
     $query = "\n    SELECT     c.id,\n               a.id as address_id,\n               a.street_address,\n               a.city,\n               a.postal_code,\n               s.name as state,\n               o.name as country\n    FROM       civicrm_contact  c\n    INNER JOIN civicrm_address        a ON a.contact_id = c.id\n    LEFT  JOIN civicrm_country        o ON a.country_id = o.id\n    LEFT  JOIN civicrm_state_province s ON a.state_province_id = s.id\n    WHERE      {$whereClause}\n      ORDER BY a.id\n    ";
     $totalGeocoded = $totalAddresses = $totalAddressParsed = 0;
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     if ($processGeocode) {
         require_once str_replace('_', DIRECTORY_SEPARATOR, $config->geocodeMethod) . '.php';
     }
     $unparseableContactAddress = array();
     while ($dao->fetch()) {
         $totalAddresses++;
         $params = array('street_address' => $dao->street_address, 'postal_code' => $dao->postal_code, 'city' => $dao->city, 'state_province' => $dao->state, 'country' => $dao->country);
         $addressParams = array();
         // process geocode.
         if ($processGeocode) {
             // loop through the address removing more information
             // so we can get some geocode for a partial address
             // i.e. city -> state -> country
             $maxTries = 5;
             do {
                 if ($this->throttle) {
                     usleep(5000000);
                 }
                 $className = $config->geocodeMethod;
                 $className::format($params, TRUE);
                 // see if we got a geocode error, in this case we'll trigger a fatal
                 // CRM-13760
                 if (isset($params['geo_code_error']) && $params['geo_code_error'] == 'OVER_QUERY_LIMIT') {
                     CRM_Core_Error::fatal('Aborting batch geocoding. Hit the over query limit on geocoder.');
                 }
                 array_shift($params);
                 $maxTries--;
             } while ((!isset($params['geo_code_1']) || $params['geo_code_1'] == 'null') && $maxTries > 1);
             if (isset($params['geo_code_1']) && $params['geo_code_1'] != 'null') {
                 $totalGeocoded++;
                 $addressParams['geo_code_1'] = $params['geo_code_1'];
                 $addressParams['geo_code_2'] = $params['geo_code_2'];
                 $addressParams['postal_code'] = $params['postal_code'];
                 $addressParams['postal_code_suffix'] = CRM_Utils_Array::value('postal_code_suffix', $params);
             }
         }
         // parse street address
         if ($parseStreetAddress) {
             $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($dao->street_address);
             $success = TRUE;
             // consider address is automatically parseable,
             // when we should found street_number and street_name
             if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
                 $success = FALSE;
             }
             // do check for all elements.
             if ($success) {
                 $totalAddressParsed++;
             } elseif ($dao->street_address) {
                 //build contact edit url,
                 //so that user can manually fill the street address fields if the street address is not parsed, CRM-5886
                 $url = CRM_Utils_System::url('civicrm/contact/add', "reset=1&action=update&cid={$dao->id}");
                 $unparseableContactAddress[] = " Contact ID: " . $dao->id . " <a href =\"{$url}\"> " . $dao->street_address . " </a> ";
                 // reset element values.
                 $parsedFields = array_fill_keys(array_keys($parsedFields), '');
             }
             $addressParams = array_merge($addressParams, $parsedFields);
         }
         // finally update address object.
         if (!empty($addressParams)) {
             $address = new CRM_Core_DAO_Address();
             $address->id = $dao->address_id;
             $address->copyValues($addressParams);
             $address->save();
             $address->free();
         }
     }
     $this->returnMessages[] = ts("Addresses Evaluated: %1", array(1 => $totalAddresses)) . "\n";
     if ($processGeocode) {
         $this->returnMessages[] = ts("Addresses Geocoded: %1", array(1 => $totalGeocoded)) . "\n";
     }
     if ($parseStreetAddress) {
         $this->returnMessages[] = ts("Street Addresses Parsed: %1", array(1 => $totalAddressParsed)) . "\n";
         if ($unparseableContactAddress) {
             $this->returnMessages[] = "<br />\n" . ts("Following is the list of contacts whose address is not parsed:") . "<br />\n";
             foreach ($unparseableContactAddress as $contactLink) {
                 $this->returnMessages[] = $contactLink . "<br />\n";
             }
         }
     }
     return $this->returnResult();
 }
Example #7
0
/**
 * This function adds the contact variable in $values to the
 * parameter list $params.  For most cases, $values should have length 1.  If
 * the variable being added is a child of Location, a location_type_id must
 * also be included.  If it is a child of phone, a phone_type must be included.
 *
 * @param array  $values    The variable(s) to be added
 * @param array  $params    The structured parameter list
 * 
 * @return bool|CRM_Utils_Error
 * @access public
 */
function _crm_add_formatted_param(&$values, &$params)
{
    /* Crawl through the possible classes: 
     * Contact 
     *      Individual 
     *      Household
     *      Organization
     *          Location 
     *              Address 
     *              Email 
     *              Phone 
     *              IM 
     *      Note
     *      Custom 
     */
    /* Cache the various object fields */
    static $fields = null;
    if ($fields == null) {
        $fields = array();
    }
    if (isset($values['contact_type'])) {
        /* we're an individual/household/org property */
        if (!isset($fields[$values['contact_type']])) {
            require_once str_replace('_', DIRECTORY_SEPARATOR, 'CRM_Contact_DAO_' . $values['contact_type']) . '.php';
            eval('$fields[' . $values['contact_type'] . '] =& 
                    CRM_Contact_DAO_' . $values['contact_type'] . '::fields();');
        }
        _crm_store_values($fields[$values['contact_type']], $values, $params);
        return true;
    }
    if (isset($values['individual_prefix'])) {
        $params['prefix'] = $values['individual_prefix'];
        return true;
    }
    if (isset($values['individual_suffix'])) {
        $params['suffix'] = $values['individual_suffix'];
        return true;
    }
    if (isset($values['gender'])) {
        $params['gender'] = $values['gender'];
        return true;
    }
    if (isset($values['location_type_id'])) {
        /* find and/or initialize the correct location block in $params */
        $locBlock = null;
        if (!isset($params['location'])) {
            /* if we don't have a location field yet, make one */
            $locBlock = 1;
            $params['location'][$locBlock] = array('location_type_id' => $values['location_type_id'], 'is_primary' => true);
        } else {
            /* search through the location array for a matching loc. type */
            foreach ($params['location'] as $key => $loc) {
                if ($loc['location_type_id'] == $values['location_type_id']) {
                    $locBlock = $key;
                }
            }
            /* if no locBlock has the correct type, make a new one */
            if ($locBlock == null) {
                $locBlock = count($params['location']) + 1;
                $params['location'][$locBlock] = array('location_type_id' => $values['location_type_id']);
            }
        }
        //add location name
        if (isset($values['name'])) {
            $params['location'][$locBlock]['name'] = $values['name'];
        }
        /* if this is a phone value, find or create the correct block */
        if (isset($values['phone'])) {
            if (!isset($params['location'][$locBlock]['phone'])) {
                /* if we don't have a phone array yet, make one */
                $params['location'][$locBlock]['phone'] = array();
            }
            /* add a new phone block to the array */
            $phoneBlock = count($params['location'][$locBlock]['phone']) + 1;
            $params['location'][$locBlock]['phone'][$phoneBlock] = array();
            if (!isset($fields['Phone'])) {
                $fields['Phone'] = CRM_Core_DAO_Phone::fields();
            }
            _crm_store_values($fields['Phone'], $values, $params['location'][$locBlock]['phone'][$phoneBlock]);
            if ($phoneBlock == 1) {
                $params['location'][$locBlock]['phone'][$phoneBlock]['is_primary'] = true;
            }
            return true;
        }
        /* If this is an email value, create a new block to store it */
        if (isset($values['email'])) {
            if (!isset($params['location'][$locBlock]['email'])) {
                $params['location'][$locBlock]['email'] = array();
            }
            /* add a new email block */
            $emailBlock = count($params['location'][$locBlock]['email']) + 1;
            $params['location'][$locBlock]['email'][$emailBlock] = array();
            if (!isset($fields['Email'])) {
                $fields['Email'] = CRM_Core_DAO_Email::fields();
            }
            _crm_store_values($fields['Email'], $values, $params['location'][$locBlock]['email'][$emailBlock]);
            if ($emailBlock == 1) {
                $params['location'][$locBlock]['email'][$emailBlock]['is_primary'] = true;
            }
            return true;
        }
        /* if this is an IM value, create a new block */
        if (isset($values['im'])) {
            if (!isset($params['location'][$locBlock]['im'])) {
                $params['location'][$locBlock]['im'] = array();
            }
            /* add a new IM block */
            $imBlock = count($params['location'][$locBlock]['im']) + 1;
            $params['location'][$locBlock]['im'][$imBlock] = array();
            if (!isset($fields['IM'])) {
                $fields['IM'] = CRM_Core_DAO_IM::fields();
            }
            _crm_store_values($fields['IM'], $values, $params['location'][$locBlock]['im'][$imBlock]);
            if ($imBlock == 1) {
                $params['location'][$locBlock]['im'][$imBlock]['is_primary'] = true;
            }
            return true;
        }
        /* Otherwise we must be an address */
        if (!isset($params['location'][$locBlock]['address'])) {
            $params['location'][$locBlock]['address'] = array();
        }
        if (!isset($fields['Address'])) {
            $fields['Address'] = CRM_Core_DAO_Address::fields();
        }
        _crm_store_values($fields['Address'], $values, $params['location'][$locBlock]['address']);
        $ids = array('county', 'country', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name');
        foreach ($ids as $id) {
            if (array_key_exists($id, $values)) {
                $params['location'][$locBlock]['address'][$id] = $values[$id];
            }
        }
        return true;
    }
    if (isset($values['note'])) {
        /* add a note field */
        if (!isset($params['note'])) {
            $params['note'] = array();
        }
        $noteBlock = count($params['note']) + 1;
        $params['note'][$noteBlock] = array();
        if (!isset($fields['Note'])) {
            $fields['Note'] = CRM_Core_DAO_Note::fields();
        }
        _crm_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
        return true;
    }
    /* Check for custom field values */
    if ($fields['custom'] == null) {
        $fields['custom'] =& CRM_Core_BAO_CustomField::getFields($values['contact_type']);
    }
    foreach ($values as $key => $value) {
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            /* check if it's a valid custom field id */
            if (!array_key_exists($customFieldID, $fields['custom'])) {
                return _crm_error('Invalid custom field ID');
            }
            if (!isset($params['custom'])) {
                $params['custom'] = array();
            }
            // fixed for Import
            $newMulValues = array();
            if ($fields['custom'][$customFieldID][3] == 'CheckBox' || $fields['custom'][$customFieldID][3] == 'Multi-Select') {
                $value = str_replace("|", ",", $value);
                $mulValues = explode(',', $value);
                $custuomOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                foreach ($mulValues as $v1) {
                    foreach ($custuomOption as $v2) {
                        if (strtolower($v2['label']) == strtolower(trim($v1))) {
                            $newMulValues[] = $v2['value'];
                        }
                    }
                }
                $value = implode(CRM_CORE_BAO_CUSTOMOPTION_VALUE_SEPERATOR, $newMulValues);
            } else {
                if ($fields['custom'][$customFieldID][3] == 'Select' || $fields['custom'][$customFieldID][3] == 'Radio') {
                    $custuomOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                    foreach ($custuomOption as $v2) {
                        if (strtolower($v2['label']) == strtolower(trim($value))) {
                            $value = $v2['value'];
                            break;
                        }
                    }
                }
            }
            $customBlock = count($params['custom']) + 1;
            $params['custom'][$customBlock] = array('custom_field_id' => $customFieldID, 'value' => $value, 'type' => $fields['custom'][$customFieldID][2], 'name' => $fields['custom'][$customFieldID][0]);
        }
    }
    /* Finally, check for contact fields */
    if (!isset($fields['Contact'])) {
        $fields['Contact'] =& CRM_Contact_DAO_Contact::fields();
    }
    _crm_store_values($fields['Contact'], $values, $params);
}
 /**
  * Create an address for a contact
  *
  * @param $cid int: contact id
  * @param $masterContactId int: set if this is a shared address
  *
  * @return array
  */
 private function _addAddress($cid, $masterContactId = NULL)
 {
     // Share existing address
     if ($masterContactId) {
         $dao = new CRM_Core_DAO_Address();
         $dao->is_primary = 1;
         $dao->contact_id = $masterContactId;
         $dao->find(TRUE);
         $dao->master_id = $dao->id;
         $dao->id = NULL;
         $dao->contact_id = $cid;
         $dao->is_primary = $this->isPrimary($cid, 'Address');
         $dao->location_type_id = $this->getContactType($masterContactId) == 'Organization' ? self::WORK : self::HOME;
         $this->_insert($dao);
     } else {
         $params = array('contact_id' => $cid, 'location_type_id' => $this->getContactType($cid) == 'Organization' ? self::MAIN : self::HOME, 'street_number' => mt_rand(1, 1000), 'street_number_suffix' => ucfirst($this->randomChar()), 'street_name' => $this->randomItem('street_name'), 'street_type' => $this->randomItem('street_type'), 'street_number_postdirectional' => $this->randomItem('address_direction'), 'county_id' => 1);
         $params['street_address'] = $params['street_number'] . $params['street_number_suffix'] . " " . $params['street_name'] . " " . $params['street_type'] . " " . $params['street_number_postdirectional'];
         if ($params['location_type_id'] == self::MAIN) {
             $params['supplemental_address_1'] = $this->randomItem('supplemental_addresses_1');
         }
         // Hack to add lat/long (limited to USA based addresses)
         list($params['country_id'], $params['state_province_id'], $params['city'], $params['postal_code'], $params['geo_code_1'], $params['geo_code_2'], ) = $this->getZipCodeInfo();
         $this->_addDAO('Address', $params);
         $params['state'] = $this->states[$params['state_province_id']];
         return $params;
     }
 }
Example #9
0
 /**
  * combine all the exportable fields from the lower levels object
  * 
  * currentlty we are using importable fields as exportable fields
  *
  * @param int     $contactType contact Type
  * $param boolean $status true while exporting primary contacts
  * $param boolean $export true when used during export
  *
  * @return array array of exportable Fields
  * @access public
  */
 function &exportableFields($contactType = 'Individual', $status = false, $export = false)
 {
     if (empty($contactType)) {
         $contactType = 'All';
     }
     $cacheKeyString = "exportableFields {$contactType}";
     $cacheKeyString .= $export ? "_1" : "_0";
     $cacheKeyString .= $status ? "_1" : "_0";
     if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
         if (!self::$_exportableFields) {
             self::$_exportableFields = array();
         }
         // check if we can retrieve from database cache
         require_once 'CRM/Core/BAO/Cache.php';
         $fields =& CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
         if (!$fields) {
             $fields = array();
             $fields = array_merge($fields, CRM_Contact_DAO_Contact::export());
             // the fields are meant for contact types
             if (in_array($contactType, array('Individual', 'Household', 'Organization', 'All'))) {
                 require_once 'CRM/Core/OptionValue.php';
                 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
             }
             // add current employer for individuals
             $fields = array_merge($fields, array('current_employer' => array('name' => 'organization_name', 'title' => ts('Current Employer'))));
             $locationType = array();
             if ($status) {
                 $locationType['location_type'] = array('name' => 'location_type', 'where' => 'civicrm_location_type.name', 'title' => ts('Location Type'));
             }
             $IMProvider = array();
             if ($status) {
                 $IMProvider['im_provider'] = array('name' => 'im_provider', 'where' => 'im_provider.name', 'title' => ts('IM Provider'));
             }
             $locationFields = array_merge($locationType, CRM_Core_DAO_Address::export(), CRM_Core_DAO_Phone::export(), CRM_Core_DAO_Email::export(), $IMProvider, CRM_Core_DAO_IM::export(true), CRM_Core_DAO_OpenID::export());
             foreach ($locationFields as $key => $field) {
                 $locationFields[$key]['hasLocationType'] = true;
             }
             $fields = array_merge($fields, $locationFields);
             //add world region
             require_once "CRM/Core/DAO/Worldregion.php";
             $fields = array_merge($fields, CRM_Core_DAO_Worldregion::export());
             $fields = array_merge($fields, CRM_Contact_DAO_Contact::export());
             if ($contactType != 'All') {
                 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, true));
             } else {
                 foreach (array('Individual', 'Household', 'Organization') as $type) {
                     $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($type));
                 }
             }
             //fix for CRM-791
             if ($export) {
                 $fields = array_merge($fields, array('groups' => array('title' => ts('Group(s)')), 'tags' => array('title' => ts('Tag(s)')), 'notes' => array('title' => ts('Note(s)'))));
             } else {
                 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)')), 'tag' => array('title' => ts('Tag(s)')), 'note' => array('title' => ts('Note(s)'))));
             }
             //Sorting fields in alphabetical order(CRM-1507)
             foreach ($fields as $k => $v) {
                 $sortArray[$k] = CRM_Utils_Array::value('title', $v);
             }
             $fields = array_merge($sortArray, $fields);
             //unset the field which are not related to their contact type.
             if ($contactType != 'All') {
                 $commonValues = array('Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom'), 'Household' => array('first_name', 'middle_name', 'last_name', 'job_title', 'gender_id', 'birth_date', 'organization_name', 'legal_name', 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased', 'deceased_date', 'current_employer', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'individual_prefix', 'individual_suffix', 'gender'), 'Organization' => array('first_name', 'middle_name', 'last_name', 'job_title', 'gender_id', 'birth_date', 'household_name', 'email_greeting', 'postal_greeting', 'email_greeting_custom', 'postal_greeting_custom', 'individual_prefix', 'individual_suffix', 'gender', 'addressee_custom', 'is_deceased', 'deceased_date', 'current_employer'));
                 foreach ($commonValues[$contactType] as $value) {
                     unset($fields[$value]);
                 }
             }
             CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
         }
         self::$_exportableFields[$cacheKeyString] = $fields;
     }
     if (!$status) {
         $fields = self::$_exportableFields[$cacheKeyString];
     } else {
         $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))), self::$_exportableFields[$cacheKeyString]);
     }
     return $fields;
 }
/**
 * @param $config
 * @param $processGeocode
 * @param $parseStreetAddress
 * @param null $start
 * @param null $end
 */
function processContacts(&$config, $processGeocode, $parseStreetAddress, $start = NULL, $end = NULL)
{
    // build where clause.
    $clause = array('( c.id = a.contact_id )');
    if ($start) {
        $clause[] = "( c.id >= {$start} )";
    }
    if ($end) {
        $clause[] = "( c.id <= {$end} )";
    }
    if ($processGeocode) {
        $clause[] = '( a.geo_code_1 is null OR a.geo_code_1 = 0 )';
        $clause[] = '( a.geo_code_2 is null OR a.geo_code_2 = 0 )';
        $clause[] = '( a.country_id is not null )';
    }
    $whereClause = implode(' AND ', $clause);
    $query = "\nSELECT     c.id,\n           a.id as address_id,\n           a.street_address,\n           a.city,\n           a.postal_code,\n           s.name as state,\n           o.name as country\nFROM       civicrm_contact  c\nINNER JOIN civicrm_address        a ON a.contact_id = c.id\nLEFT  JOIN civicrm_country        o ON a.country_id = o.id\nLEFT  JOIN civicrm_state_province s ON a.state_province_id = s.id\nWHERE      {$whereClause}\n  ORDER BY a.id\n";
    $totalGeocoded = $totalAddresses = $totalAddressParsed = 0;
    $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
    if ($processGeocode) {
        require_once str_replace('_', DIRECTORY_SEPARATOR, $config->geocodeMethod) . '.php';
    }
    require_once 'CRM/Core/DAO/Address.php';
    require_once 'CRM/Core/BAO/Address.php';
    $unparseableContactAddress = array();
    while ($dao->fetch()) {
        $totalAddresses++;
        $params = array('street_address' => $dao->street_address, 'postal_code' => $dao->postal_code, 'city' => $dao->city, 'state_province' => $dao->state, 'country' => $dao->country);
        $addressParams = array();
        // process geocode.
        if ($processGeocode) {
            // loop through the address removing more information
            // so we can get some geocode for a partial address
            // i.e. city -> state -> country
            $maxTries = 5;
            do {
                if (defined('THROTTLE_REQUESTS') && THROTTLE_REQUESTS) {
                    usleep(50000);
                }
                eval($config->geocodeMethod . '::format( $params, true );');
                array_shift($params);
                $maxTries--;
            } while (!isset($params['geo_code_1']) && $maxTries > 1);
            if (isset($params['geo_code_1']) && $params['geo_code_1'] != 'null') {
                $totalGeocoded++;
                $addressParams['geo_code_1'] = $params['geo_code_1'];
                $addressParams['geo_code_2'] = $params['geo_code_2'];
            }
        }
        // parse street address
        if ($parseStreetAddress) {
            $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($dao->street_address);
            $success = TRUE;
            // consider address is automatically parseable,
            // when we should found street_number and street_name
            if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
                $success = FALSE;
            }
            // do check for all elements.
            if ($success) {
                $totalAddressParsed++;
            } elseif ($dao->street_address) {
                //build contact edit url,
                //so that user can manually fill the street address fields if the street address is not parsed, CRM-5886
                $url = CRM_Utils_System::url('civicrm/contact/add', "reset=1&action=update&cid={$dao->id}");
                $unparseableContactAddress[] = " Contact ID: " . $dao->id . " <a href =\"{$url}\"> " . $dao->street_address . " </a> ";
                // reset element values.
                $parsedFields = array_fill_keys(array_keys($parsedFields), '');
            }
            $addressParams = array_merge($addressParams, $parsedFields);
        }
        // finally update address object.
        if (!empty($addressParams)) {
            $address = new CRM_Core_DAO_Address();
            $address->id = $dao->address_id;
            $address->copyValues($addressParams);
            $address->save();
            $address->free();
        }
    }
    echo ts("Addresses Evaluated: {$totalAddresses}\n");
    if ($processGeocode) {
        echo ts("Addresses Geocoded : {$totalGeocoded}\n");
    }
    if ($parseStreetAddress) {
        echo ts("Street Address Parsed : {$totalAddressParsed}\n");
        if ($unparseableContactAddress) {
            echo ts("<br />\nFollowing is the list of contacts whose address is not parsed :<br />\n");
            foreach ($unparseableContactAddress as $contactLink) {
                echo ts("%1<br />\n", array(1 => $contactLink));
            }
        }
    }
}
Example #11
0
 /**
  * returns the list of fields that can be exported
  *
  * @access public
  * return array
  */
 function &export($prefix = false)
 {
     if (!$GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export']) {
         $GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export'] = array();
         $fields =& CRM_Core_DAO_Address::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     $GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export']['address'] =& $fields[$name];
                 } else {
                     $GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export'][$name] =& $fields[$name];
                 }
             }
         }
         $GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export'] = array_merge($GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export'], CRM_Core_DAO_StateProvince::export(true));
         $GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export'] = array_merge($GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export'], CRM_Core_DAO_Country::export(true));
     }
     return $GLOBALS['_CRM_CORE_DAO_ADDRESS']['_export'];
 }
Example #12
0
/**
 *  Update a specified location with the provided property values.
 * 
 *  @param  object  $contact        A valid Contact object (passed by reference).
 *  @param  string  $location_id    Valid (db-level) id for location to be updated. 
 *  @param  Array   $params         Associative array of property name/value pairs to be updated
 *
 *  @return Location object with updated property values
 * 
 *  @access public
 *
 */
function crm_update_location(&$contact, $location_id, $params)
{
    _crm_initialize();
    if (!isset($contact->id)) {
        return _crm_error('$contact is not valid contact datatype');
    }
    $locationId = (int) $location_id;
    if ($locationId == 0) {
        return _crm_error('missing or invalid $location_id');
    }
    // $locationNumber is the contact-level number of the location (1, 2, 3, etc.)
    $locationNumber = null;
    $locations =& crm_get_locations($contact);
    foreach ($locations as $locNumber => $locValue) {
        if ($locValue->id == $locationId) {
            $locationNumber = $locNumber;
            break;
        }
    }
    if (!$locationNumber) {
        return _crm_error('invalid $location_id');
    }
    $values = array('contact_id' => $contact->id, 'location' => array($locationNumber => array()));
    $loc =& $values['location'][$locationNumber];
    $loc['address'] = array();
    require_once 'CRM/Core/DAO/Address.php';
    $fields =& CRM_Core_DAO_Address::fields();
    _crm_store_values($fields, $params, $loc['address']);
    //$ids = array( 'county', 'country_id', 'state_province_id', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name' );
    $ids = array('county', 'country_id', 'country', 'state_province_id', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name', 'street_address');
    foreach ($ids as $id) {
        if (array_key_exists($id, $params)) {
            $loc['address'][$id] = $params[$id];
        }
    }
    if (is_numeric($loc['address']['state_province'])) {
        $loc['address']['state_province'] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($loc['address']['state_province']);
    }
    if (is_numeric($loc['address']['country'])) {
        $loc['address']['country'] = CRM_Core_PseudoConstant::countryIsoCode($loc['address']['country']);
    }
    if (array_key_exists('location_type_id', $params)) {
        $loc['location_type_id'] = $params['location_type_id'];
    }
    if (array_key_exists('location_type', $params)) {
        $locTypes =& CRM_Core_PseudoConstant::locationType();
        $loc['location_type_id'] = CRM_Utils_Array::key($params['location_type'], $locTypes);
    }
    if (array_key_exists('name', $params)) {
        $loc['name'] = $params['name'];
    }
    if (array_key_exists('is_primary', $params)) {
        $loc['is_primary'] = (int) $params['is_primary'];
    }
    $loc['id'] = $locationId;
    $blocks = array('Email', 'Phone', 'IM');
    foreach ($blocks as $block) {
        $name = strtolower($block);
        $loc[$name] = array();
        if ($params[$name]) {
            $count = 1;
            foreach ($params[$name] as $val) {
                CRM_Core_DAO::storeValues($val, $loc[$name][$count++]);
            }
        }
    }
    $par = array('id' => $contact->id, 'contact_id' => $contact->id);
    $contact = CRM_Contact_BAO_Contact::retrieve($par, $defaults, $ids);
    CRM_Contact_BAO_Contact::resolveDefaults($values, true);
    $location = CRM_Core_BAO_Location::add($values, $ids, $locationNumber);
    return $location;
}
Example #13
0
function processContacts(&$config, $start = null, $end = null)
{
    $contactClause = array();
    if ($start) {
        $contactClause[] = "c.id >= {$start}";
    }
    if ($end) {
        $contactClause[] = "c.id <= {$end}";
    }
    if (!empty($contactClause)) {
        $contactClause = ' AND ' . implode(' AND ', $contactClause);
    } else {
        $contactClause = null;
    }
    $query = "\nSELECT     c.id,\n           a.id as address_id,\n           a.street_address,\n           a.city,\n           a.postal_code,\n           s.name as state,\n           o.name as country\nFROM       civicrm_contact  c\nINNER JOIN civicrm_address        a ON a.contact_id = c.id\nINNER JOIN civicrm_country        o ON a.country_id = o.id\nLEFT  JOIN civicrm_state_province s ON a.state_province_id = s.id\nWHERE      c.id           = a.contact_id\n  AND      ( a.geo_code_1 is null OR a.geo_code_1 = 0 )\n  AND      ( a.geo_code_2 is null OR a.geo_code_2 = 0 )\n  AND      a.country_id is not null\n  {$contactClause}\nORDER BY a.id\n";
    $totalGeocoded = $totalAddresses = 0;
    $dao =& CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
    require_once str_replace('_', DIRECTORY_SEPARATOR, $config->geocodeMethod) . '.php';
    require_once 'CRM/Core/DAO/Address.php';
    while ($dao->fetch()) {
        $totalAddresses++;
        $params = array('street_address' => $dao->street_address, 'postal_code' => $dao->postal_code, 'city' => $dao->city, 'state_province' => $dao->state, 'country' => $dao->country);
        // loop through the address removing more information
        // so we can get some geocode for a partial address
        // i.e. city -> state -> country
        $maxTries = 5;
        do {
            if (defined('THROTTLE_REQUESTS') && THROTTLE_REQUESTS) {
                usleep(50000);
            }
            eval($config->geocodeMethod . '::format( $params, true );');
            array_shift($params);
            $maxTries--;
        } while (!isset($params['geo_code_1']) && $maxTries > 1);
        if (isset($params['geo_code_1'])) {
            $address = new CRM_Core_DAO_Address();
            $address->id = $dao->address_id;
            $address->geo_code_1 = $params['geo_code_1'];
            $address->geo_code_2 = $params['geo_code_2'];
            $address->save();
            $totalGeocoded++;
        }
    }
    echo ts("Addresses Evaluated: {$totalAddresses}\n");
    echo ts("Addresses Geocoded : {$totalGeocoded}\n");
    return;
}
 /**
  * Combine all the exportable fields from the lower levels object.
  *
  * Currently we are using importable fields as exportable fields
  *
  * @param int|string $contactType contact Type
  * @param bool $status
  *   True while exporting primary contacts.
  * @param bool $export
  *   True when used during export.
  * @param bool $search
  *   True when used during search, might conflict with export param?.
  *
  * @param bool $withMultiRecord
  *
  * @return array
  *   array of exportable Fields
  */
 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE)
 {
     if (empty($contactType)) {
         $contactType = 'All';
     }
     $cacheKeyString = "exportableFields {$contactType}";
     $cacheKeyString .= $export ? '_1' : '_0';
     $cacheKeyString .= $status ? '_1' : '_0';
     $cacheKeyString .= $search ? '_1' : '_0';
     //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
     //calculates custom fields takes into account the logged in user & caches that for all users
     //as an interim fix we will cache the fields by contact
     $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
     if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
         if (!self::$_exportableFields) {
             self::$_exportableFields = array();
         }
         // check if we can retrieve from database cache
         $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
         if (!$fields) {
             $fields = CRM_Contact_DAO_Contact::export();
             // The fields are meant for contact types.
             if (in_array($contactType, array('Individual', 'Household', 'Organization', 'All'))) {
                 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
             }
             // add current employer for individuals
             $fields = array_merge($fields, array('current_employer' => array('name' => 'organization_name', 'title' => ts('Current Employer'))));
             $locationType = array('location_type' => array('name' => 'location_type', 'where' => 'civicrm_location_type.name', 'title' => ts('Location Type')));
             $IMProvider = array('im_provider' => array('name' => 'im_provider', 'where' => 'civicrm_im.provider_id', 'title' => ts('IM Provider')));
             $locationFields = array_merge($locationType, CRM_Core_DAO_Address::export(), CRM_Core_DAO_Phone::export(), CRM_Core_DAO_Email::export(), $IMProvider, CRM_Core_DAO_IM::export(TRUE), CRM_Core_DAO_OpenID::export());
             $locationFields = array_merge($locationFields, CRM_Core_BAO_CustomField::getFieldsForImport('Address'));
             foreach ($locationFields as $key => $field) {
                 $locationFields[$key]['hasLocationType'] = TRUE;
             }
             $fields = array_merge($fields, $locationFields);
             //add world region
             $fields = array_merge($fields, CRM_Core_DAO_Worldregion::export());
             $fields = array_merge($fields, CRM_Contact_DAO_Contact::export());
             //website fields
             $fields = array_merge($fields, CRM_Core_DAO_Website::export());
             if ($contactType != 'All') {
                 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord));
             } else {
                 foreach (array('Individual', 'Household', 'Organization') as $type) {
                     $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord));
                 }
             }
             //fix for CRM-791
             if ($export) {
                 $fields = array_merge($fields, array('groups' => array('title' => ts('Group(s)'), 'name' => 'groups'), 'tags' => array('title' => ts('Tag(s)'), 'name' => 'tags'), 'notes' => array('title' => ts('Note(s)'), 'name' => 'notes')));
             } else {
                 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'), 'name' => 'group'), 'tag' => array('title' => ts('Tag(s)'), 'name' => 'tag'), 'note' => array('title' => ts('Note(s)'), 'name' => 'note')));
             }
             //Sorting fields in alphabetical order(CRM-1507)
             foreach ($fields as $k => $v) {
                 $sortArray[$k] = CRM_Utils_Array::value('title', $v);
             }
             $fields = array_merge($sortArray, $fields);
             //unset the field which are not related to their contact type.
             if ($contactType != 'All') {
                 $commonValues = array('Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom'), 'Household' => array('first_name', 'middle_name', 'last_name', 'formal_title', 'job_title', 'gender_id', 'prefix_id', 'suffix_id', 'birth_date', 'organization_name', 'legal_name', 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased', 'deceased_date', 'current_employer', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'prefix_id', 'suffix_id'), 'Organization' => array('first_name', 'middle_name', 'last_name', 'formal_title', 'job_title', 'gender_id', 'prefix_id', 'suffix_id', 'birth_date', 'household_name', 'email_greeting_custom', 'postal_greeting_custom', 'prefix_id', 'suffix_id', 'gender_id', 'addressee_custom', 'is_deceased', 'deceased_date', 'current_employer'));
                 foreach ($commonValues[$contactType] as $value) {
                     unset($fields[$value]);
                 }
             }
             CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
         }
         self::$_exportableFields[$cacheKeyString] = $fields;
     }
     if (!$status) {
         $fields = self::$_exportableFields[$cacheKeyString];
     } else {
         $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))), self::$_exportableFields[$cacheKeyString]);
     }
     return $fields;
 }
Example #15
0
/**
 * This function format location blocks w/ v3.0 format.
 *
 * @param array  $values    The variable(s) to be added
 * @param array  $params    The structured parameter list
 * 
 * @return bool
 * @access public
 */
function _civicrm_add_formatted_location_blocks(&$values, &$params)
{
    static $fields = null;
    if ($fields == null) {
        $fields = array();
    }
    foreach (array('Phone', 'Email', 'IM', 'OpenID') as $block) {
        $name = strtolower($block);
        if (!array_key_exists($name, $values)) {
            continue;
        }
        // block present in value array.
        if (!array_key_exists($name, $params) || !is_array($params[$name])) {
            $params[$name] = array();
        }
        if (!array_key_exists($block, $fields)) {
            require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_DAO_" . $block) . ".php";
            eval('$fields[$block] =& CRM_Core_DAO_' . $block . '::fields( );');
        }
        $blockCnt = count($params[$name]);
        // copy value to dao field name.
        if ($name == 'im') {
            $values['name'] = $values[$name];
        }
        _civicrm_store_values($fields[$block], $values, $params[$name][++$blockCnt]);
        if ($blockCnt == 1) {
            $params[$name][$blockCnt]['is_primary'] = true;
        }
        // we only process single block at a time.
        return true;
    }
    // handle address fields.
    if (!array_key_exists('address', $params) || !is_array($params['address'])) {
        $params['address'] = array();
    }
    $addressCnt = 1;
    foreach ($params['address'] as $cnt => $addressBlock) {
        if (CRM_Utils_Array::value('location_type_id', $values) == CRM_Utils_Array::value('location_type_id', $addressBlock)) {
            $addressCnt = $cnt;
            break;
        }
        $addressCnt++;
    }
    if (!array_key_exists('Address', $fields)) {
        require_once 'CRM/Core/DAO/Address.php';
        $fields['Address'] =& CRM_Core_DAO_Address::fields();
    }
    _civicrm_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
    $addressFields = array('county', 'country', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name');
    foreach ($addressFields as $field) {
        if (array_key_exists($field, $values)) {
            if (!array_key_exists('address', $params)) {
                $params['address'] = array();
            }
            $params['address'][$addressCnt][$field] = $values[$field];
        }
    }
    if ($addressCnt == 1) {
        $params['address'][$addressCnt]['is_primary'] = true;
    }
    return true;
}
Example #16
0
 /**
  * Update the shared addresses if master address is modified.
  *
  * @param int $addressId
  *   Address id.
  * @param array $params
  *   Associated array of address params.
  */
 public static function processSharedAddress($addressId, $params)
 {
     $query = 'SELECT id FROM civicrm_address WHERE master_id = %1';
     $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($addressId, 'Integer')));
     // unset contact id
     $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id', 'contact_id');
     foreach ($skipFields as $value) {
         unset($params[$value]);
     }
     $addressDAO = new CRM_Core_DAO_Address();
     while ($dao->fetch()) {
         $addressDAO->copyValues($params);
         $addressDAO->id = $dao->id;
         $addressDAO->save();
         $addressDAO->free();
     }
 }
Example #17
0
 /**
  * Function to Copy household address, if use_household_address option is checked.
  *
  * @param array $params  the input form values
  *
  * @return void
  * @access public
  * @static
  */
 static function copyHouseholdAddress(&$params)
 {
     if ($params['shared_household']) {
         $params['mail_to_household_id'] = $params['shared_household'];
     }
     if (!$params['mail_to_household_id']) {
         CRM_Core_Error::statusBounce(ts("Shared Household-ID not found."));
     }
     $locParams = array('version' => '3.0', 'contact_id' => $params['mail_to_household_id']);
     $location_types = array();
     require_once 'api/v2/Location.php';
     $values =& _civicrm_location_get($locParams, $location_types);
     $addressFields = CRM_Core_DAO_Address::fields();
     foreach ($addressFields as $key => $val) {
         if (!CRM_Utils_Array::value($key, $values['address'][1])) {
             $values['address'][1][$key] = "";
         }
     }
     if ($is_billing = $params['address'][1]['is_billing']) {
         $values['address'][1]['is_billing'] = $is_billing;
     }
     if ($values['address'][1]['country_id'] == "null") {
         $values['address'][1]['country_id'] = 0;
     }
     if ($values['address'][1]['state_province_id'] == "null") {
         $values['address'][1]['state_province_id'] = 0;
     }
     $params['address'][1] = $values['address'][1];
     // unset all the ids and unwanted fields
     $unsetFields = array('id', 'location_id', 'timezone', 'note');
     foreach ($unsetFields as $fld) {
         unset($params['address'][1][$fld]);
     }
 }
Example #18
0
 /**
  * Formats a token list for the select2 widget
  *
  * @param $tokens
  * @return array
  */
 public static function formatTokensForDisplay($tokens)
 {
     $sorted = $output = array();
     // Sort in ascending order by ignoring word case
     natcasesort($tokens);
     // Attempt to place tokens into optgroups
     // @todo These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
     foreach ($tokens as $k => $v) {
         // Check to see if this token is already in a group e.g. for custom fields
         $split = explode(' :: ', $v);
         if (!empty($split[1])) {
             $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
         } else {
             $split = explode('.', trim($k, '{}'));
             if (isset($split[1])) {
                 $entity = array_key_exists($split[1], CRM_Core_DAO_Address::export()) ? 'Address' : ucfirst($split[0]);
             } else {
                 $entity = 'Contact';
             }
             $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
         }
     }
     ksort($sorted);
     foreach ($sorted as $k => $v) {
         $output[] = array('text' => $k, 'children' => $v);
     }
     return $output;
 }
Example #19
0
 /**
  * combine all the exportable fields from the lower levels object
  * 
  * currentlty we are using importable fields as exportable fields
  *
  * @param int     $contactType contact Type
  * $param boolean $status true while exporting primary contacts
  * $param boolean $export true when used during export
  *
  * @return array array of exportable Fields
  * @access public
  */
 function &exportableFields($contactType = 'Individual', $status = false, $export = false)
 {
     if (empty($contactType)) {
         $contactType = 'All';
     }
     if (!$GLOBALS['_CRM_CONTACT_BAO_CONTACT']['_exportableFields'] || !CRM_Utils_Array::value($contactType, $GLOBALS['_CRM_CONTACT_BAO_CONTACT']['_exportableFields'])) {
         if (!$GLOBALS['_CRM_CONTACT_BAO_CONTACT']['_exportableFields']) {
             $GLOBALS['_CRM_CONTACT_BAO_CONTACT']['_exportableFields'] = array();
         }
         if (!$status) {
             $fields = array();
         } else {
             $fields = array('' => array('title' => ts('- Contact Fields -')));
         }
         if ($contactType != 'All') {
             require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_DAO_" . $contactType) . ".php";
             eval('$fields = array_merge($fields, CRM_Contact_DAO_' . $contactType . '::export( ));');
         } else {
             foreach (array('Individual', 'Household', 'Organization') as $type) {
                 require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_DAO_" . $type) . ".php";
                 eval('$fields = array_merge($fields, CRM_Contact_DAO_' . $type . '::export( ));');
                 if ($type == 'Individual') {
                     $fields = array_merge($fields, CRM_Core_DAO_IndividualPrefix::export(true), CRM_Core_DAO_IndividualSuffix::export(true), CRM_Core_DAO_Gender::export(true));
                 }
             }
         }
         // the fields are only meant for Individual contact type
         if ($contactType == 'Individual') {
             $fields = array_merge($fields, CRM_Core_DAO_IndividualPrefix::export(true), CRM_Core_DAO_IndividualSuffix::export(true), CRM_Core_DAO_Gender::export(true));
         }
         $locationType = array();
         if ($status) {
             $locationType['location_type'] = array('name' => 'location_type', 'where' => 'civicrm_location_type.name', 'title' => 'Location Type');
         }
         $IMProvider = array();
         if ($status) {
             $IMProvider['im_provider'] = array('name' => 'im_provider', 'where' => 'civicrm_im_provider.name', 'title' => 'IM Provider');
         }
         $locationFields = array_merge($locationType, CRM_Core_DAO_Location::export(), CRM_Core_DAO_Address::export(), CRM_Core_DAO_Phone::export(), CRM_Core_DAO_Email::export(), $IMProvider, CRM_Core_DAO_IM::export(true));
         foreach ($locationFields as $key => $field) {
             $locationFields[$key]['hasLocationType'] = true;
         }
         $fields = array_merge($fields, $locationFields);
         $fields = array_merge($fields, CRM_Contact_DAO_Contact::export());
         $fields = array_merge($fields, CRM_Core_DAO_Note::export());
         if ($contactType != 'All') {
             $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status));
         } else {
             foreach (array('Individual', 'Household', 'Organization') as $type) {
                 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($type));
             }
         }
         //fix for CRM-791
         if ($export) {
             $fields = array_merge($fields, array('groups' => array('title' => ts('Group(s)'))));
             $fields = array_merge($fields, array('tags' => array('title' => ts('Tag(s)'))));
         } else {
             $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'))));
             $fields = array_merge($fields, array('tag' => array('title' => ts('Tag(s)'))));
         }
         $GLOBALS['_CRM_CONTACT_BAO_CONTACT']['_exportableFields'][$contactType] = $fields;
     }
     return $GLOBALS['_CRM_CONTACT_BAO_CONTACT']['_exportableFields'][$contactType];
 }