/**
  * Get a list of Commendations matching the params, where each param key is:
  *  1. the key of a field in civicrm_activity, except for activity_type_id
  *  2. the key of a custom field on the activity (volunteer_project_id)
  *  3. the key of a field in civicrm_contact
  *
  * @param array $params
  * @return array of CRM_Volunteer_BAO_Project objects
  */
 public static function retrieve(array $params)
 {
     $activity_fields = CRM_Activity_DAO_Activity::fields();
     $contact_fields = CRM_Contact_DAO_Contact::fields();
     $custom_fields = self::getCustomFields();
     // This is the "real" id
     $activity_fields['id'] = $activity_fields['activity_id'];
     unset($activity_fields['activity_id']);
     // enforce restrictions on parameters
     $allowed_params = array_flip(array_merge(array_keys($activity_fields), array_keys($contact_fields), array_keys($custom_fields)));
     unset($allowed_params['activity_type_id']);
     $filtered_params = array_intersect_key($params, $allowed_params);
     $custom_group = self::getCustomGroup();
     $customTableName = $custom_group['table_name'];
     foreach ($custom_fields as $name => $field) {
         $selectClause[] = "{$customTableName}.{$field['column_name']} AS {$name}";
     }
     $customSelect = implode(', ', $selectClause);
     $activityContactTypes = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContactTypes);
     $placeholders = array(1 => array($targetID, 'Integer'), 2 => array(self::getActivityTypeId(), 'Integer'));
     $i = count($placeholders) + 1;
     $where = array();
     $whereClause = NULL;
     foreach ($filtered_params as $key => $value) {
         if (CRM_Utils_Array::value($key, $activity_fields)) {
             $dataType = CRM_Utils_Type::typeToString($activity_fields[$key]['type']);
             $fieldName = $activity_fields[$key]['name'];
             $tableName = CRM_Activity_DAO_Activity::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $contact_fields)) {
             $dataType = CRM_Utils_Type::typeToString($contact_fields[$key]['type']);
             $fieldName = $contact_fields[$key]['name'];
             $tableName = CRM_Contact_DAO_Contact::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $custom_fields)) {
             $dataType = $custom_fields[$key]['data_type'];
             $fieldName = $custom_fields[$key]['column_name'];
             $tableName = $customTableName;
         }
         $where[] = "{$tableName}.{$fieldName} = %{$i}";
         $placeholders[$i] = array($value, $dataType);
         $i++;
     }
     if (count($where)) {
         $whereClause = 'AND ' . implode("\nAND ", $where);
     }
     $query = "\n      SELECT\n        civicrm_activity.*,\n        {$customSelect},\n        activityContact.contact_id AS volunteer_contact_id,\n        volunteer_contact.sort_name AS volunteer_sort_name,\n        volunteer_contact.display_name AS volunteer_display_name\n      FROM civicrm_activity\n      INNER JOIN civicrm_activity_contact activityContact\n        ON (\n          activityContact.activity_id = civicrm_activity.id\n          AND activityContact.record_type_id = %1\n        )\n      INNER JOIN civicrm_contact volunteer_contact\n        ON activityContact.contact_id = volunteer_contact.id\n      INNER JOIN {$customTableName}\n        ON ({$customTableName}.entity_id = civicrm_activity.id)\n      WHERE civicrm_activity.activity_type_id = %2\n      {$whereClause}\n    ";
     $dao = CRM_Core_DAO::executeQuery($query, $placeholders);
     $rows = array();
     while ($dao->fetch()) {
         $rows[$dao->id] = $dao->toArray();
     }
     return $rows;
 }
 /**
  * Get a list of Assignments matching the params, where each param key is:
  *  1. the key of a field in civicrm_activity
  *     except for activity_type_id and activity_duration
  *  2. the key of a custom field on the activity
  *     (volunteer_need_id, time_scheduled, time_completed)
  *  3. the key of a field in civicrm_contact
  *  4. project_id
  *
  * @param array $params
  * @return array of CRM_Volunteer_BAO_Project objects
  */
 static function retrieve(array $params)
 {
     $activity_fields = CRM_Activity_DAO_Activity::fields();
     $contact_fields = CRM_Contact_DAO_Contact::fields();
     $custom_fields = self::getCustomFields();
     $foreign_fields = array('project_id', 'target_contact_id');
     // This is the "real" id
     $activity_fields['id'] = $activity_fields['activity_id'];
     unset($activity_fields['activity_id']);
     // enforce restrictions on parameters
     $allowed_params = array_flip(array_merge(array_keys($activity_fields), array_keys($contact_fields), array_keys($custom_fields), $foreign_fields));
     unset($allowed_params['activity_type_id']);
     unset($allowed_params['activity_duration']);
     $filtered_params = array_intersect_key($params, $allowed_params);
     $custom_group = self::getCustomGroup();
     $customTableName = $custom_group['table_name'];
     foreach ($custom_fields as $name => $field) {
         $selectClause[] = "{$customTableName}.{$field['column_name']} AS {$name}";
     }
     $customSelect = implode(', ', $selectClause);
     $activityContactTypes = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContactTypes);
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContactTypes);
     $volunteerStatus = CRM_Activity_BAO_Activity::buildOptions('status_id', 'validate');
     $available = CRM_Utils_Array::key('Available', $volunteerStatus);
     $scheduled = CRM_Utils_Array::key('Scheduled', $volunteerStatus);
     $placeholders = array(1 => array($assigneeID, 'Integer'), 2 => array(self::volunteerActivityTypeId(), 'Integer'), 3 => array($scheduled, 'Integer'), 4 => array($available, 'Integer'), 5 => array($targetID, 'Integer'));
     $i = count($placeholders) + 1;
     $where = array();
     $whereClause = NULL;
     foreach ($filtered_params as $key => $value) {
         if (CRM_Utils_Array::value($key, $activity_fields)) {
             $dataType = CRM_Utils_Type::typeToString($activity_fields[$key]['type']);
             $fieldName = $activity_fields[$key]['name'];
             $tableName = CRM_Activity_DAO_Activity::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $contact_fields)) {
             $dataType = CRM_Utils_Type::typeToString($contact_fields[$key]['type']);
             $fieldName = $contact_fields[$key]['name'];
             $tableName = CRM_Contact_DAO_Contact::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $custom_fields)) {
             $dataType = $custom_fields[$key]['data_type'];
             $fieldName = $custom_fields[$key]['column_name'];
             $tableName = $customTableName;
         } elseif ($key == 'project_id') {
             $dataType = 'Int';
             $fieldName = 'id';
             $tableName = CRM_Volunteer_DAO_Project::$_tableName;
         } elseif ($key == 'target_contact_id') {
             $dataType = 'Int';
             $fieldName = 'contact_id';
             $tableName = 'tgt';
             // this is an alias for civicrm_activity_contact
         }
         $where[] = "{$tableName}.{$fieldName} = %{$i}";
         $placeholders[$i] = array($value, $dataType);
         $i++;
     }
     if (count($where)) {
         $whereClause = 'AND ' . implode("\nAND ", $where);
     }
     $query = "\n      SELECT\n        civicrm_activity.*,\n        assignee.contact_id AS assignee_contact_id,\n        {$customSelect},\n        civicrm_volunteer_need.start_time,\n        civicrm_volunteer_need.is_flexible,\n        civicrm_volunteer_need.role_id,\n        assignee_contact.sort_name AS assignee_sort_name,\n        assignee_contact.display_name AS assignee_display_name,\n        assignee_phone.phone AS assignee_phone,\n        assignee_phone.phone_ext AS assignee_phone_ext,\n        assignee_email.email AS assignee_email,\n        -- begin target contact fields\n        tgt.contact_id AS target_contact_id,\n        tgt_contact.sort_name AS target_sort_name,\n        tgt_contact.display_name AS target_display_name,\n        tgt_phone.phone AS target_phone,\n        tgt_phone.phone_ext AS target_phone_ext,\n        tgt_email.email AS target_email\n        -- end target contact fields\n      FROM civicrm_activity\n      INNER JOIN civicrm_activity_contact assignee\n        ON (\n          assignee.activity_id = civicrm_activity.id\n          AND assignee.record_type_id = %1\n        )\n      INNER JOIN civicrm_contact assignee_contact\n        ON assignee.contact_id = assignee_contact.id\n      LEFT JOIN civicrm_email assignee_email\n        ON assignee_email.contact_id = assignee_contact.id AND assignee_email.is_primary = 1\n      LEFT JOIN civicrm_phone assignee_phone\n        ON assignee_phone.contact_id = assignee_contact.id AND assignee_phone.is_primary = 1\n      -- begin target contact joins\n      LEFT JOIN civicrm_activity_contact tgt\n        ON (\n          tgt.activity_id = civicrm_activity.id\n          AND tgt.record_type_id = %5\n        )\n      LEFT JOIN civicrm_contact tgt_contact\n        ON tgt.contact_id = tgt_contact.id\n      LEFT JOIN civicrm_email tgt_email\n        ON tgt_email.contact_id = tgt_contact.id AND tgt_email.is_primary = 1\n      LEFT JOIN civicrm_phone tgt_phone\n        ON tgt_phone.contact_id = tgt_contact.id AND tgt_phone.is_primary = 1\n      -- end target contact joins\n      INNER JOIN {$customTableName}\n        ON ({$customTableName}.entity_id = civicrm_activity.id)\n      INNER JOIN civicrm_volunteer_need\n        ON (civicrm_volunteer_need.id = {$customTableName}.{$custom_fields['volunteer_need_id']['column_name']})\n      INNER JOIN civicrm_volunteer_project\n        ON (civicrm_volunteer_project.id = civicrm_volunteer_need.project_id)\n      WHERE civicrm_activity.activity_type_id = %2\n      AND civicrm_activity.status_id IN (%3, %4 )\n      {$whereClause}\n    ";
     $dao = CRM_Core_DAO::executeQuery($query, $placeholders);
     $rows = array();
     while ($dao->fetch()) {
         $rows[$dao->id] = $dao->toArray();
     }
     /*
      * For clarity we want the fields associated with each contact prefixed with
      * the contact type (e.g., target_phone). For backwards compatibility,
      * however, we want the fields associated with each assignee contact to be
      * accessible sans prefix. Eventually we should deprecate the non-prefixed
      * field names.
      */
     foreach ($rows as $id => $fields) {
         foreach ($fields as $key => $value) {
             if (substr($key, 0, 9) == 'assignee_') {
                 $rows[$id][substr($key, 9)] = $value;
             }
         }
     }
     return $rows;
 }
 /**
  * @return array
  *   Array of field names which will be compared, so everything except ID.
  */
 public static function getContactFields()
 {
     $contactFields = CRM_Contact_DAO_Contact::fields();
     $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date', 'primary_contact_id', 'sort_name', 'user_unique_id');
     foreach ($contactFields as $field => $value) {
         if (in_array($field, $invalidFields)) {
             unset($contactFields[$field]);
         }
     }
     return array_keys($contactFields);
 }
/**
 * 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
 */
function _civicrm_api3_deprecated_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();
    }
    // first add core contact values since for other Civi modules they are not added
    require_once 'CRM/Contact/BAO/Contact.php';
    $contactFields = CRM_Contact_DAO_Contact::fields();
    _civicrm_api3_store_values($contactFields, $values, $params);
    if (isset($values['contact_type'])) {
        // we're an individual/household/org property
        $fields[$values['contact_type']] = CRM_Contact_DAO_Contact::fields();
        _civicrm_api3_store_values($fields[$values['contact_type']], $values, $params);
        return TRUE;
    }
    if (isset($values['individual_prefix'])) {
        if (!empty($params['prefix_id'])) {
            $prefixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
            $params['prefix'] = $prefixes[$params['prefix_id']];
        } else {
            $params['prefix'] = $values['individual_prefix'];
        }
        return TRUE;
    }
    if (isset($values['individual_suffix'])) {
        if (!empty($params['suffix_id'])) {
            $suffixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id');
            $params['suffix'] = $suffixes[$params['suffix_id']];
        } else {
            $params['suffix'] = $values['individual_suffix'];
        }
        return TRUE;
    }
    // CRM-4575
    if (isset($values['email_greeting'])) {
        if (!empty($params['email_greeting_id'])) {
            $emailGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params), 'greeting_type' => 'email_greeting');
            $emailGreetings = CRM_Core_PseudoConstant::greeting($emailGreetingFilter);
            $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
        } else {
            $params['email_greeting'] = $values['email_greeting'];
        }
        return TRUE;
    }
    if (isset($values['postal_greeting'])) {
        if (!empty($params['postal_greeting_id'])) {
            $postalGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params), 'greeting_type' => 'postal_greeting');
            $postalGreetings = CRM_Core_PseudoConstant::greeting($postalGreetingFilter);
            $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
        } else {
            $params['postal_greeting'] = $values['postal_greeting'];
        }
        return TRUE;
    }
    if (isset($values['addressee'])) {
        if (!empty($params['addressee_id'])) {
            $addresseeFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params), 'greeting_type' => 'addressee');
            $addressee = CRM_Core_PseudoConstant::addressee($addresseeFilter);
            $params['addressee'] = $addressee[$params['addressee_id']];
        } else {
            $params['addressee'] = $values['addressee'];
        }
        return TRUE;
    }
    if (isset($values['gender'])) {
        if (!empty($params['gender_id'])) {
            $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
            $params['gender'] = $genders[$params['gender_id']];
        } else {
            $params['gender'] = $values['gender'];
        }
        return TRUE;
    }
    if (!empty($values['preferred_communication_method'])) {
        $comm = array();
        $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method')), CASE_LOWER);
        $preffComm = explode(',', $values['preferred_communication_method']);
        foreach ($preffComm as $v) {
            $v = strtolower(trim($v));
            if (array_key_exists($v, $pcm)) {
                $comm[$pcm[$v]] = 1;
            }
        }
        $params['preferred_communication_method'] = $comm;
        return TRUE;
    }
    // format the website params.
    if (!empty($values['url'])) {
        static $websiteFields;
        if (!is_array($websiteFields)) {
            require_once 'CRM/Core/DAO/Website.php';
            $websiteFields = CRM_Core_DAO_Website::fields();
        }
        if (!array_key_exists('website', $params) || !is_array($params['website'])) {
            $params['website'] = array();
        }
        $websiteCount = count($params['website']);
        _civicrm_api3_store_values($websiteFields, $values, $params['website'][++$websiteCount]);
        return TRUE;
    }
    // get the formatted location blocks into params - w/ 3.0 format, CRM-4605
    if (!empty($values['location_type_id'])) {
        _civicrm_api3_deprecated_add_formatted_location_blocks($values, $params);
        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();
        }
        // get the current logged in civicrm user
        $session = CRM_Core_Session::singleton();
        $userID = $session->get('userID');
        if ($userID) {
            $values['contact_id'] = $userID;
        }
        _civicrm_api3_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
        return TRUE;
    }
    // Check for custom field values
    if (empty($fields['custom'])) {
        $fields['custom'] =& CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $values), FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
    }
    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 civicrm_api3_create_error('Invalid custom field ID');
            } else {
                $params[$key] = $value;
            }
        }
    }
}
Beispiel #5
0
 /**
  * returns the list of fields that can be exported
  *
  * @access public
  * return array
  */
 function &export($prefix = false)
 {
     if (!$GLOBALS['_CRM_CONTACT_DAO_CONTACT']['_export']) {
         $GLOBALS['_CRM_CONTACT_DAO_CONTACT']['_export'] = array();
         $fields =& CRM_Contact_DAO_Contact::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     $GLOBALS['_CRM_CONTACT_DAO_CONTACT']['_export']['contact'] =& $fields[$name];
                 } else {
                     $GLOBALS['_CRM_CONTACT_DAO_CONTACT']['_export'][$name] =& $fields[$name];
                 }
             }
         }
     }
     return $GLOBALS['_CRM_CONTACT_DAO_CONTACT']['_export'];
 }
 private function diffsInTable($table)
 {
     // caches for pretty field titles and value mappings
     static $titles = null;
     static $values = null;
     $params = array(1 => array($this->log_conn_id, 'Integer'), 2 => array($this->log_date, 'String'));
     // we look for the last change in the given connection that happended less than 10 seconds later than log_date to catch multi-query changes
     $changedSQL = "SELECT * FROM `{$this->loggingDB}`.`{$table}` WHERE log_conn_id = %1 AND log_date < DATE_ADD(%2, INTERVAL 10 SECOND) ORDER BY log_date DESC LIMIT 1";
     $changed = $this->sqlToArray($changedSQL, $params);
     // return early if nothing found
     if (empty($changed)) {
         return array();
     }
     // seed caches with civicrm_contact titles/values
     if (!isset($titles['log_civicrm_contact']) or !isset($values['log_civicrm_contact'])) {
         $titles['log_civicrm_contact'] = array('gender_id' => ts('Gender'), 'preferred_communication_method' => ts('Preferred Communication Method'), 'preferred_language' => ts('Preferred Language'), 'prefix_id' => ts('Prefix'), 'suffix_id' => ts('Suffix'));
         $values['log_civicrm_contact'] = array('gender_id' => CRM_Core_PseudoConstant::gender(), 'preferred_communication_method' => CRM_Core_PseudoConstant::pcm(), 'preferred_language' => CRM_Core_PseudoConstant::languages(), 'prefix_id' => CRM_Core_PseudoConstant::individualPrefix(), 'suffix_id' => CRM_Core_PseudoConstant::individualSuffix());
         require_once 'CRM/Contact/DAO/Contact.php';
         $dao = new CRM_Contact_DAO_Contact();
         foreach ($dao->fields() as $field) {
             if (!isset($titles['log_civicrm_contact'][$field['name']])) {
                 $titles['log_civicrm_contact'][$field['name']] = $field['title'];
             }
             if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
                 $values['log_civicrm_contact'][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
             }
         }
     }
     // add custom data titles/values for the given table
     if (!isset($titles[$table]) or !isset($values[$table])) {
         $titles[$table] = array();
         $values[$table] = array();
         $params[3] = array(substr($table, 4), 'String');
         $sql = "SELECT id, title FROM `{$this->loggingDB}`.log_civicrm_custom_group WHERE log_date <= %2 AND table_name = %3 ORDER BY log_date DESC LIMIT 1";
         $cgDao =& CRM_Core_DAO::executeQuery($sql, $params);
         $cgDao->fetch();
         $params[3] = array($cgDao->id, 'Integer');
         $sql = "SELECT column_name, data_type, label, name FROM `{$this->loggingDB}`.log_civicrm_custom_field WHERE log_date <= %2 AND custom_group_id = %3 ORDER BY log_date";
         $cfDao =& CRM_Core_DAO::executeQuery($sql, $params);
         while ($cfDao->fetch()) {
             $titles[$table][$cfDao->column_name] = "{$cgDao->title}: {$cfDao->label}";
             switch ($cfDao->data_type) {
                 case 'Boolean':
                     $values[$table][$cfDao->column_name] = array('0' => ts('false'), '1' => ts('true'));
                     break;
                 case 'String':
                     $values[$table][$cfDao->column_name] = array();
                     $params[3] = array("custom_{$cfDao->name}", 'String');
                     $sql = "SELECT id FROM `{$this->loggingDB}`.log_civicrm_option_group WHERE log_date <= %2 AND name = %3 ORDER BY log_date DESC LIMIT 1";
                     $ogId = CRM_Core_DAO::singleValueQuery($sql, $params);
                     $params[3] = array($ogId, 'Integer');
                     $sql = "SELECT label, value FROM `{$this->loggingDB}`.log_civicrm_option_value WHERE log_date <= %2 AND option_group_id = %3 ORDER BY log_date";
                     $ovDao =& CRM_Core_DAO::executeQuery($sql, $params);
                     while ($ovDao->fetch()) {
                         $values[$table][$cfDao->column_name][$ovDao->value] = $ovDao->label;
                     }
                     break;
             }
         }
     }
     // we look for the previous state (different log_conn_id) of the found id
     $params[3] = array($changed['id'], 'Integer');
     $originalSQL = "SELECT * FROM `{$this->loggingDB}`.`{$table}` WHERE log_conn_id != %1 AND log_date < %2 AND id = %3 ORDER BY log_date DESC LIMIT 1";
     $original = $this->sqlToArray($originalSQL, $params);
     $rows = array();
     // populate $rows with only the differences between $changed and $original (skipping certain columns and NULL ↔ empty changes)
     $skipped = array('entity_id', 'id', 'log_action', 'log_conn_id', 'log_date', 'log_user_id');
     foreach (array_keys(array_diff_assoc($changed, $original)) as $diff) {
         if (in_array($diff, $skipped)) {
             continue;
         }
         if ($original[$diff] == $changed[$diff]) {
             continue;
         }
         $rows[] = array('field' => isset($titles[$table][$diff]) ? $titles[$table][$diff] : substr($table, 4) . ".{$diff}", 'from' => isset($values[$table][$diff][$original[$diff]]) ? $values[$table][$diff][$original[$diff]] : $original[$diff], 'to' => isset($values[$table][$diff][$changed[$diff]]) ? $values[$table][$diff][$changed[$diff]] : $changed[$diff]);
     }
     return $rows;
 }
Beispiel #7
0
 function preProcess()
 {
     require_once 'api/v2/Contact.php';
     require_once 'CRM/Core/BAO/CustomGroup.php';
     require_once 'CRM/Core/OptionGroup.php';
     require_once 'CRM/Core/OptionValue.php';
     if (!CRM_Core_Permission::check('administer CiviCRM')) {
         CRM_Core_Error::fatal(ts('You do not have access to this page'));
     }
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, true);
     $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, true);
     $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, false);
     $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, false);
     $session =& CRM_Core_Session::singleton();
     // context fixed.
     if ($rgid) {
         $urlParam = "reset=1&action=browse&rgid={$rgid}";
         if ($gid) {
             $urlParam .= "&gid={$gid}";
         }
         $session->pushUserContext(CRM_Utils_system::url('civicrm/admin/dedupefind', $urlParam));
     }
     // ensure that oid is not the current user, if so refuse to do the merge
     if ($session->get('userID') == $oid) {
         $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name');
         $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.', array(1 => $display_name));
         CRM_Core_Error::statusBounce($message);
     }
     $diffs = CRM_Dedupe_Merger::findDifferences($cid, $oid);
     $mainParams = array('contact_id' => $cid, 'return.display_name' => 1);
     $otherParams = array('contact_id' => $oid, 'return.display_name' => 1);
     // API 2 has to have the requested fields spelt-out for it
     foreach (CRM_Dedupe_Merger::$validFields as $field) {
         $mainParams["return.{$field}"] = $otherParams["return.{$field}"] = 1;
     }
     $main =& civicrm_contact_get($mainParams);
     //CRM-4524
     $main = reset($main);
     if ($main['contact_id'] != $cid) {
         CRM_Core_Error::fatal(ts('The main contact record does not exist'));
     }
     $other =& civicrm_contact_get($otherParams);
     //CRM-4524
     $other = reset($other);
     if ($other['contact_id'] != $oid) {
         CRM_Core_Error::fatal(ts('The other contact record does not exist'));
     }
     $this->assign('contact_type', $main['contact_type']);
     $this->assign('main_name', $main['display_name']);
     $this->assign('other_name', $other['display_name']);
     $this->assign('main_cid', $main['contact_id']);
     $this->assign('other_cid', $other['contact_id']);
     $this->_cid = $cid;
     $this->_oid = $oid;
     $this->_rgid = $rgid;
     $this->_contactType = $main['contact_type'];
     $this->addElement('checkbox', 'toggleSelect', null, null, array('onclick' => "return toggleCheckboxVals('move_',this);"));
     require_once "CRM/Contact/DAO/Contact.php";
     $fields =& CRM_Contact_DAO_Contact::fields();
     // FIXME: there must be a better way
     foreach (array('main', 'other') as $moniker) {
         $contact =& ${$moniker};
         $specialValues[$moniker] = array('preferred_communication_method' => $contact['preferred_communication_method']);
         $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method'));
         CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
     }
     foreach (CRM_Core_OptionValue::getFields() as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     if (!isset($diffs['contact'])) {
         $diffs['contact'] = array();
     }
     foreach ($diffs['contact'] as $field) {
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             $label = isset($specialValues[$moniker][$field]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if ($fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif ($fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
                 if ($label === '0') {
                     $label = ts('[ ]');
                 }
                 if ($label === '1') {
                     $label = ts('[x]');
                 }
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 if ($value === null) {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $this->_qfZeroBug;
                 }
                 $this->addElement('advcheckbox', "move_{$field}", null, null, null, $value);
             }
         }
         $rows["move_{$field}"]['title'] = $fields[$field]['title'];
     }
     // handle location blocks.
     require_once 'api/v2/Location.php';
     $mainParams['version'] = $otherParams['version'] = '3.0';
     $locations['main'] =& civicrm_location_get($mainParams);
     $locations['other'] =& civicrm_location_get($otherParams);
     $allLocationTypes = CRM_Core_PseudoConstant::locationType();
     $mainLocAddress = array();
     foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
         $name = strtolower($block);
         foreach (array('main', 'other') as $moniker) {
             $blockValue = CRM_Utils_Array::value($name, $locations[$moniker], array());
             if (empty($blockValue)) {
                 $locValue[$moniker][$name] = 0;
                 $locLabel[$moniker][$name] = array();
                 $locTypes[$moniker][$name] = array();
             } else {
                 $locValue[$moniker][$name] = true;
                 foreach ($blockValue as $count => $blkValues) {
                     $fldName = $name;
                     $locTypeId = $blkValues['location_type_id'];
                     if ($name == 'im') {
                         $fldName = 'name';
                     }
                     if ($name == 'address') {
                         $fldName = 'display';
                     }
                     $locLabel[$moniker][$name][$count] = $blkValues[$fldName];
                     $locTypes[$moniker][$name][$count] = $locTypeId;
                     if ($moniker == 'main' && $name == 'address') {
                         $mainLocAddress["main_{$locTypeId}"] = $blkValues[$fldName];
                         $this->_locBlockIds['main']['address'][$locTypeId] = $blkValues['id'];
                     } else {
                         $this->_locBlockIds[$moniker][$name][$count] = $blkValues['id'];
                     }
                 }
             }
         }
         if ($locValue['other'][$name] != 0) {
             foreach ($locLabel['other'][$name] as $count => $value) {
                 $locTypeId = $locTypes['other'][$name][$count];
                 $rows["move_location_{$name}_{$count}"]['other'] = $value;
                 $rows["move_location_{$name}_{$count}"]['main'] = $locLabel['main'][$name][$count];
                 $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId]));
                 $this->addElement('advcheckbox', "move_location_{$name}_{$count}");
                 // make sure default location type is always on top
                 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
                 $locTypeValues = $allLocationTypes;
                 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
                 unset($locTypeValues[$mainLocTypeId]);
                 // keep 1-1 mapping for address - location type.
                 $js = null;
                 if ($name == 'address' && !empty($mainLocAddress)) {
                     $js = array('onChange' => "mergeAddress( this, {$count} );");
                 }
                 $this->addElement('select', "location[{$name}][{$count}][locTypeId]", null, $defaultLocType + $locTypeValues, $js);
                 if ($name != 'address') {
                     $this->addElement('advcheckbox', "location[{$name}][{$count}][operation]", null, ts('add new'));
                 }
             }
         }
     }
     $this->assign('mainLocAddress', json_encode($mainLocAddress));
     // handle custom fields
     $mainTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, $this->_cid, -1);
     $otherTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, $this->_oid, -1);
     if (!isset($diffs['custom'])) {
         $diffs['custom'] = array();
     }
     foreach ($otherTree as $gid => $group) {
         $foundField = false;
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             if (in_array($fid, $diffs['custom'])) {
                 if (!$foundField) {
                     $rows["custom_group_{$gid}"]['title'] = $group['title'];
                     $foundField = true;
                 }
                 if (is_array($mainTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field);
                     }
                 }
                 if (is_array($otherTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field);
                         $value = $values['data'] ? $values['data'] : $this->_qfZeroBug;
                     }
                 }
                 $rows["move_custom_{$fid}"]['title'] = $field['label'];
                 $this->addElement('advcheckbox', "move_custom_{$fid}", null, null, null, $value);
             }
         }
     }
     $this->assign('rows', $rows);
     // add the related tables and unset the ones that don't sport any of the duplicate contact's info
     $relTables = CRM_Dedupe_Merger::relTables();
     $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($oid);
     foreach ($relTables as $name => $null) {
         if (!in_array($name, $activeRelTables)) {
             unset($relTables[$name]);
             continue;
         }
         $this->addElement('checkbox', "move_{$name}");
         $relTables[$name]['main_url'] = str_replace('$cid', $cid, $relTables[$name]['url']);
         $relTables[$name]['other_url'] = str_replace('$cid', $oid, $relTables[$name]['url']);
     }
     foreach ($relTables as $name => $null) {
         $relTables["move_{$name}"] = $relTables[$name];
         unset($relTables[$name]);
     }
     $this->assign('rel_tables', $relTables);
 }
Beispiel #8
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 _civicrm_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();
    }
    //first add core contact values since for other Civi modules they are not added
    require_once 'CRM/Contact/BAO/Contact.php';
    $contactFields =& CRM_Contact_DAO_Contact::fields();
    _civicrm_store_values($contactFields, $values, $params);
    if (isset($values['contact_type'])) {
        /* we're an individual/household/org property */
        $fields[$values['contact_type']] = CRM_Contact_DAO_Contact::fields();
        _civicrm_store_values($fields[$values['contact_type']], $values, $params);
        return true;
    }
    if (isset($values['individual_prefix'])) {
        if ($params['prefix_id']) {
            $prefixes = array();
            $prefixes = CRM_Core_PseudoConstant::individualPrefix();
            $params['prefix'] = $prefixes[$params['prefix_id']];
        } else {
            $params['prefix'] = $values['individual_prefix'];
        }
        return true;
    }
    if (isset($values['individual_suffix'])) {
        if ($params['suffix_id']) {
            $suffixes = array();
            $suffixes = CRM_Core_PseudoConstant::individualSuffix();
            $params['suffix'] = $suffixes[$params['suffix_id']];
        } else {
            $params['suffix'] = $values['individual_suffix'];
        }
        return true;
    }
    //CRM-4575
    if (isset($values['email_greeting'])) {
        if ($params['email_greeting_id']) {
            $emailGreetings = array();
            $emailGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params), 'greeting_type' => 'email_greeting');
            $emailGreetings = CRM_Core_PseudoConstant::greeting($emailGreetingFilter);
            $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
        } else {
            $params['email_greeting'] = $values['email_greeting'];
        }
        return true;
    }
    if (isset($values['postal_greeting'])) {
        if ($params['postal_greeting_id']) {
            $postalGreetings = array();
            $postalGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params), 'greeting_type' => 'postal_greeting');
            $postalGreetings = CRM_Core_PseudoConstant::greeting($postalGreetingFilter);
            $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
        } else {
            $params['postal_greeting'] = $values['postal_greeting'];
        }
        return true;
    }
    if (isset($values['addressee'])) {
        if ($params['addressee_id']) {
            $addressee = array();
            $addresseeFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params), 'greeting_type' => 'addressee');
            $addressee = CRM_Core_PseudoConstant::addressee($addresseeFilter);
            $params['addressee'] = $addressee[$params['addressee_id']];
        } else {
            $params['addressee'] = $values['addressee'];
        }
        return true;
    }
    if (isset($values['gender'])) {
        if ($params['gender_id']) {
            $genders = array();
            $genders = CRM_Core_PseudoConstant::gender();
            $params['gender'] = $genders[$params['gender_id']];
        } else {
            $params['gender'] = $values['gender'];
        }
        return true;
    }
    if (isset($values['preferred_communication_method'])) {
        $comm = array();
        $preffComm = array();
        $pcm = array();
        $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant::pcm()), CASE_LOWER);
        $preffComm = explode(',', $values['preferred_communication_method']);
        foreach ($preffComm as $v) {
            $v = strtolower(trim($v));
            if (array_key_exists($v, $pcm)) {
                $comm[$pcm[$v]] = 1;
            }
        }
        $params['preferred_communication_method'] = $comm;
        return true;
    }
    // get the formatted location blocks into params - w/ 3.0 format, CRM-4605
    if (CRM_Utils_Array::value('location_type_id', $values)) {
        _civicrm_add_formatted_location_blocks($values, $params);
        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();
        }
        // get the current logged in civicrm user
        $session =& CRM_Core_Session::singleton();
        $userID = $session->get('userID');
        if ($userID) {
            $values['contact_id'] = $userID;
        }
        _civicrm_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 civicrm_create_error('Invalid custom field ID');
            } else {
                $params[$key] = $value;
            }
        }
    }
}
Beispiel #9
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);
}
Beispiel #10
0
 /**
  * Get the metadata for the merge fields.
  *
  * This is basically the contact metadata, augmented with fields to
  * represent email greeting, postal greeting & addressee.
  *
  * @return array
  */
 public static function getMergeFieldsMetadata()
 {
     if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
         return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
     }
     $fields = CRM_Contact_DAO_Contact::fields();
     static $optionValueFields = array();
     if (empty($optionValueFields)) {
         $optionValueFields = CRM_Core_OptionValue::getFields();
     }
     foreach ($optionValueFields as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
     return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
 }
 /**
  * A function to build an array of information required by merge function and the merge UI.
  *
  * @param  int     $mainId         main contact with whom merge has to happen
  * @param  int     $otherId        duplicate contact which would be deleted after merge operation
  *
  * @static void
  * @access public
  */
 function &getRowsElementsAndInfo($mainId, $otherId)
 {
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     $mainParams = array('contact_id' => $mainId, 'return.display_name' => 1, 'return.contact_sub_type' => 1);
     $otherParams = array('contact_id' => $otherId, 'return.display_name' => 1, 'return.contact_sub_type' => 1);
     $mainParams['version'] = $otherParams['version'] = 3;
     foreach (CRM_Dedupe_Merger::$validFields as $field) {
         $mainParams["return.{$field}"] = $otherParams["return.{$field}"] = 1;
     }
     $main = civicrm_api('contact', 'get', $mainParams);
     // CRM-4524
     $main = reset($main['values']);
     if ($main['contact_id'] != $mainId) {
         // FIXME: The main contact record does not exist
         return FALSE;
     }
     $other = civicrm_api('contact', 'get', $otherParams);
     // CRM-4524
     $other = reset($other['values']);
     if ($other['contact_id'] != $otherId) {
         // FIXME: The other contact record does not exist
         return FALSE;
     }
     static $fields = array();
     if (empty($fields)) {
         $fields = CRM_Contact_DAO_Contact::fields();
         CRM_Core_DAO::freeResult();
     }
     // FIXME: there must be a better way
     $monikers = array('main', 'other');
     foreach ($monikers as $moniker) {
         $contact =& ${$moniker};
         $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
         $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
         $specialValues[$moniker] = array('preferred_communication_method' => $value);
         // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
         $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
         $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
         $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method'));
         CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
     }
     static $optionValueFields = array();
     if (empty($optionValueFields)) {
         $optionValueFields = CRM_Core_OptionValue::getFields();
     }
     foreach ($optionValueFields as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     $diffs = CRM_Dedupe_Merger::findDifferences($mainId, $otherId);
     if (!isset($diffs['contact'])) {
         $diffs['contact'] = array();
     }
     $rows = $elements = $relTableElements = $migrationInfo = array();
     foreach ($diffs['contact'] as $field) {
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             if (isset($specialValues[$moniker][$field])) {
                 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
             }
             $label = isset($specialValues[$moniker][$field]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if (CRM_Utils_Array::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif (CRM_Utils_Array::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
                 if ($label === '0') {
                     $label = ts('[ ]');
                 }
                 if ($label === '1') {
                     $label = ts('[x]');
                 }
             } elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
                 $label = CRM_Utils_Array::value('prefix', $contact);
                 $value = CRM_Utils_Array::value('prefix_id', $contact);
                 $field = 'prefix_id';
             } elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
                 $label = CRM_Utils_Array::value('suffix', $contact);
                 $value = CRM_Utils_Array::value('suffix_id', $contact);
                 $field = 'suffix_id';
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 if ($value === NULL) {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $qfZeroBug;
                 }
                 if (is_array($value) && !CRM_Utils_Array::value(1, $value)) {
                     $value[1] = NULL;
                 }
                 $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value);
                 $migrationInfo["move_{$field}"] = $value;
             }
         }
         $rows["move_{$field}"]['title'] = $fields[$field]['title'];
     }
     // handle location blocks.
     $locationBlocks = array('email', 'phone', 'address');
     foreach ($locationBlocks as $block) {
         foreach (array('main', 'other') as $locBlocks) {
             $cnt = 1;
             $blockName = "{$locBlocks}Params";
             $values = civicrm_api($block, 'get', ${$blockName});
             $count = $values['count'];
             if ($count) {
                 if ($count > $cnt) {
                     foreach ($values['values'] as $value) {
                         if ($block == 'address') {
                             CRM_Core_BAO_Address::fixAddress($value);
                             $display = CRM_Utils_Address::format($value);
                             $locations[$locBlocks][$block][$cnt] = $value;
                             $locations[$locBlocks][$block][$cnt]['display'] = $display;
                         } else {
                             $locations[$locBlocks][$block][$cnt] = $value;
                         }
                         $cnt++;
                     }
                 } else {
                     $id = $values['id'];
                     if ($block == 'address') {
                         CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
                         $display = CRM_Utils_Address::format($values['values'][$id]);
                         $locations[$locBlocks][$block][$cnt] = $values['values'][$id];
                         $locations[$locBlocks][$block][$cnt]['display'] = $display;
                     } else {
                         $locations[$locBlocks][$block][$cnt] = $values['values'][$id];
                     }
                 }
             }
         }
     }
     $allLocationTypes = CRM_Core_PseudoConstant::locationType();
     $mainLocBlock = $locBlockIds = array();
     $locBlockIds['main'] = $locBlockIds['other'] = array();
     foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
         $name = strtolower($block);
         foreach (array('main', 'other') as $moniker) {
             $blockValue = CRM_Utils_Array::value($name, $locations[$moniker], array());
             if (empty($blockValue)) {
                 $locValue[$moniker][$name] = 0;
                 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
             } else {
                 $locValue[$moniker][$name] = TRUE;
                 foreach ($blockValue as $count => $blkValues) {
                     $fldName = $name;
                     $locTypeId = $blkValues['location_type_id'];
                     if ($name == 'im') {
                         $fldName = 'name';
                     }
                     if ($name == 'address') {
                         $fldName = 'display';
                     }
                     $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName, $blkValues);
                     $locTypes[$moniker][$name][$count] = $locTypeId;
                     if ($moniker == 'main' && in_array($name, $locationBlocks)) {
                         $mainLocBlock["main_{$name}{$locTypeId}"] = CRM_Utils_Array::value($fldName, $blkValues);
                         $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
                     } else {
                         $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
                     }
                 }
             }
         }
         if ($locValue['other'][$name] != 0) {
             foreach ($locLabel['other'][$name] as $count => $value) {
                 $locTypeId = $locTypes['other'][$name][$count];
                 $rows["move_location_{$name}_{$count}"]['other'] = $value;
                 $rows["move_location_{$name}_{$count}"]['main'] = CRM_Utils_Array::value($count, $locLabel['main'][$name]);
                 $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId]));
                 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
                 $migrationInfo["move_location_{$name}_{$count}"] = 1;
                 // make sure default location type is always on top
                 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
                 $locTypeValues = $allLocationTypes;
                 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
                 unset($locTypeValues[$mainLocTypeId]);
                 // keep 1-1 mapping for address - location type.
                 $js = NULL;
                 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
                     $js = array('onChange' => "mergeBlock('{$name}', this, {$count} );");
                 }
                 $elements[] = array('select', "location[{$name}][{$count}][locTypeId]", NULL, $defaultLocType + $locTypeValues, $js);
                 // keep location-type-id same as that of other-contact
                 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
                 if ($name != 'address') {
                     $elements[] = array('advcheckbox', "location[{$name}][{$count}][operation]", NULL, ts('add new'));
                     // always use add operation
                     $migrationInfo['location'][$name][$count]['operation'] = 1;
                 }
             }
         }
     }
     // add the related tables and unset the ones that don't sport any of the duplicate contact's info
     $config = CRM_Core_Config::singleton();
     $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
     $mainUser = NULL;
     if ($mainUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $mainUser = user_load($mainUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $mainUser = JFactory::getUser($mainUfId);
         }
     }
     $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
     $otherUser = NULL;
     if ($otherUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $otherUser = user_load($otherUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $otherUser = JFactory::getUser($otherUfId);
         }
     }
     $relTables = CRM_Dedupe_Merger::relTables();
     $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
     $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
     foreach ($relTables as $name => $null) {
         if (!in_array($name, $activeRelTables) && !($name == 'rel_table_users' && in_array($name, $activeMainRelTables))) {
             unset($relTables[$name]);
             continue;
         }
         $relTableElements[] = array('checkbox', "move_{$name}");
         $migrationInfo["move_{$name}"] = 1;
         $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
         $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
         if ($name == 'rel_table_users') {
             $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
             $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
             $find = array('$ufid', '$ufname');
             if ($mainUser) {
                 $replace = array($mainUfId, $mainUser->name);
                 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
             if ($otherUser) {
                 $replace = array($otherUfId, $otherUser->name);
                 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
         }
         if ($name == 'rel_table_memberships') {
             $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
             $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
         }
     }
     foreach ($relTables as $name => $null) {
         $relTables["move_{$name}"] = $relTables[$name];
         unset($relTables[$name]);
     }
     // handle custom fields
     $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, CRM_Utils_Array::value('contact_sub_type', $main));
     $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, CRM_Utils_Array::value('contact_sub_type', $other));
     CRM_Core_DAO::freeResult();
     if (!isset($diffs['custom'])) {
         $diffs['custom'] = array();
     }
     foreach ($otherTree as $gid => $group) {
         $foundField = FALSE;
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             if (in_array($fid, $diffs['custom'])) {
                 if (!$foundField) {
                     $rows["custom_group_{$gid}"]['title'] = $group['title'];
                     $foundField = TRUE;
                 }
                 if (CRM_Utils_Array::value('customValue', $mainTree[$gid]['fields'][$fid])) {
                     foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                     }
                 }
                 $value = "null";
                 if (CRM_Utils_Array::value('customValue', $otherTree[$gid]['fields'][$fid])) {
                     foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                         if ($values['data'] === 0 || $values['data'] === '0') {
                             $values['data'] = $qfZeroBug;
                         }
                         $value = $values['data'] ? $values['data'] : $value;
                     }
                 }
                 $rows["move_custom_{$fid}"]['title'] = $field['label'];
                 $elements[] = array('advcheckbox', "move_custom_{$fid}", NULL, NULL, NULL, $value);
                 $migrationInfo["move_custom_{$fid}"] = $value;
             }
         }
     }
     $result = array('rows' => $rows, 'elements' => $elements, 'rel_table_elements' => $relTableElements, 'main_loc_block' => $mainLocBlock, 'rel_tables' => $relTables, 'main_details' => $main, 'other_details' => $other, 'migration_info' => $migrationInfo);
     $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
     $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
     // unset all vars to avoid any possible leaks
     unset($diffs, $contact, $mainTree, $otherTree, $rows, $elements, $relTableElements, $mainLocBlock, $relTables, $main, $other, $migrationInfo);
     return $result;
 }