Example #1
0
/**
 * Create activity type.
 *
 * @param array $params
 *
 * @return array
 *   created / updated activity type
 *
 * @deprecated use the OptionValue api instead
 */
function civicrm_api3_activity_type_create($params)
{
    $action = 1;
    $groupParams = array('name' => 'activity_type');
    if ($optionValueID = CRM_Utils_Array::value('option_value_id', $params)) {
        $action = 2;
    }
    $activityObject = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $action, $optionValueID);
    $activityType = array();
    _civicrm_api3_object_to_array($activityObject, $activityType[$activityObject->id]);
    return civicrm_api3_create_success($activityType, $params, 'activity_type', 'create');
}
 function run()
 {
     CRM_Utils_System::setTitle(ts("Configuration Checklist"));
     $this->assign('recentlyViewed', FALSE);
     $destination = CRM_Utils_System::url('civicrm/admin/configtask', 'reset=1', FALSE, NULL, FALSE);
     $destination = urlencode($destination);
     $this->assign('destination', $destination);
     CRM_Core_OptionValue::getValues(array('name' => 'from_email_address'), $optionValue);
     if (!empty($optionValue)) {
         list($id) = array_keys($optionValue);
         $this->assign('fromEmailId', $id);
     }
     return parent::run();
 }
/**
 * Function to create activity type
 *
 * @param array   $params  associated array of fields
 *                 $params['option_value_id'] is required for updation of activity type
 *
 * @return array $activityType created / updated activity type
 *
 * @access public
 */
function civicrm_activity_type_create($params)
{
    require_once 'CRM/Core/OptionGroup.php';
    if (!isset($params['label']) || !isset($params['weight'])) {
        return civicrm_create_error(ts('Required parameter "label / weight" not found'));
    }
    $action = 1;
    $groupParams = array('name' => 'activity_type');
    if ($optionValueID = CRM_Utils_Array::value('option_value_id', $params)) {
        $action = 2;
    }
    require_once 'CRM/Core/OptionValue.php';
    $activityObject = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $action, $optionValueID);
    $activityType = array();
    _civicrm_object_to_array($activityObject, $activityType);
    return $activityType;
}
Example #4
0
 function run()
 {
     CRM_Utils_System::setTitle(ts("Configuration Checklist"));
     $this->assign('recentlyViewed', FALSE);
     $destination = CRM_Utils_System::url('civicrm/admin/configtask', 'reset=1', FALSE, NULL, FALSE);
     $destination = urlencode($destination);
     $this->assign('destination', $destination);
     CRM_Core_OptionValue::getValues(array('name' => 'from_email_address'), $optionValue);
     if (!empty($optionValue)) {
         list($id) = array_keys($optionValue);
         $this->assign('fromEmailId', $id);
     }
     $payPalProId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal', 'id', 'name');
     if ($payPalProId) {
         $this->assign('payPalProId', $payPalProId);
     }
     return parent::run();
 }
 static function &longForShortMapping()
 {
     static $longForShortMapping = null;
     if ($longForShortMapping === null) {
         $rows = array();
         CRM_Core_OptionValue::getValues(array('name' => 'languages'), $rows);
         $longForShortMapping = array();
         foreach ($rows as $row) {
             $longForShortMapping[$row['value']] = $row['name'];
         }
         // hand-crafted enforced overrides for language variants
         $longForShortMapping['zh'] = 'zh_CN';
         $longForShortMapping['en'] = 'en_US';
         $longForShortMapping['fr'] = 'fr_FR';
         $longForShortMapping['pt'] = 'pt_PT';
         $longForShortMapping['es'] = 'es_ES';
     }
     return $longForShortMapping;
 }
Example #6
0
 /**
  * @return array
  */
 public static function &longForShortMapping()
 {
     static $longForShortMapping = NULL;
     if ($longForShortMapping === NULL) {
         $rows = array();
         CRM_Core_OptionValue::getValues(array('name' => 'languages'), $rows);
         $longForShortMapping = array();
         foreach ($rows as $row) {
             $longForShortMapping[$row['value']] = $row['name'];
         }
         // hand-crafted enforced overrides for language variants
         // NB: when adding support for a regional override for a new language below, update
         // relevant comments in templates/CRM/common/civicrm.settings.php.template as well
         $longForShortMapping['zh'] = defined("CIVICRM_LANGUAGE_MAPPING_ZH") ? CIVICRM_LANGUAGE_MAPPING_ZH : 'zh_CN';
         $longForShortMapping['en'] = defined("CIVICRM_LANGUAGE_MAPPING_EN") ? CIVICRM_LANGUAGE_MAPPING_EN : 'en_US';
         $longForShortMapping['fr'] = defined("CIVICRM_LANGUAGE_MAPPING_FR") ? CIVICRM_LANGUAGE_MAPPING_FR : 'fr_FR';
         $longForShortMapping['pt'] = defined("CIVICRM_LANGUAGE_MAPPING_PT") ? CIVICRM_LANGUAGE_MAPPING_PT : 'pt_PT';
         $longForShortMapping['es'] = defined("CIVICRM_LANGUAGE_MAPPING_ES") ? CIVICRM_LANGUAGE_MAPPING_ES : 'es_ES';
     }
     return $longForShortMapping;
 }
 /**
  * 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;
 }
 /**
  * Function to get list of contribution fields for profile
  * For now we only allow custom contribution fields to be in
  * profile
  *
  * @return return the list of contribution fields
  * @static
  * @access public
  */
 static function getContributionFields()
 {
     $contributionFields =& CRM_Contribute_DAO_Contribution::export();
     require_once 'CRM/Core/OptionValue.php';
     $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
     require_once 'CRM/Contribute/DAO/ContributionType.php';
     $contributionFields = array_merge($contributionFields, CRM_Contribute_DAO_ContributionType::export());
     foreach ($contributionFields as $key => $var) {
         if ($key == 'contribution_contact_id') {
             continue;
         }
         $fields[$key] = $var;
     }
     $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
     return $fields;
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $fieldValues = array('option_group_id' => $this->_gid);
         $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
         if (CRM_Core_BAO_OptionValue::del($this->_id)) {
             CRM_Core_Session::setStatus(ts('Selected Survey type has been deleted.'), ts('Record Deleted'), 'success');
         }
     } else {
         $params = $ids = array();
         $params = $this->exportValues();
         // set db value of filter in params if filter is non editable
         if ($this->_id && !array_key_exists('filter', $params)) {
             $params['filter'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'filter', 'id');
         }
         $groupParams = array('name' => $this->_gName);
         $params['component_id'] = CRM_Core_Component::getComponentID('CiviCampaign');
         $optionValue = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $this->_action, $this->_id);
         CRM_Core_Session::setStatus(ts('The Survey type \'%1\' has been saved.', array(1 => $optionValue->label)), ts('Saved'), 'success');
     }
 }
Example #10
0
 /**
  * Get list of contribution fields for profile.
  * For now we only allow custom contribution fields to be in
  * profile
  *
  * @param bool $addExtraFields
  *   True if special fields needs to be added.
  *
  * @return array
  *   the list of contribution fields
  */
 public static function getContributionFields($addExtraFields = TRUE)
 {
     $contributionFields = CRM_Contribute_DAO_Contribution::export();
     $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
     if ($addExtraFields) {
         $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
     }
     $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
     foreach ($contributionFields as $key => $var) {
         if ($key == 'contribution_contact_id') {
             continue;
         } elseif ($key == 'contribution_campaign_id') {
             $var['title'] = ts('Campaign');
         }
         $fields[$key] = $var;
     }
     $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
     return $fields;
 }
Example #11
0
 function upgrade($rev)
 {
     // fix CRM-5270: if civicrm_report_instance.description is localised,
     // recreate it based on the first locale’s description_xx_YY contents
     // and drop all the description_xx_YY columns
     if (!CRM_Core_DAO::checkFieldExists('civicrm_report_instance', 'description')) {
         require_once 'CRM/Core/DAO/Domain.php';
         $domain = new CRM_Core_DAO_Domain();
         $domain->find(true);
         $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
         CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_report_instance ADD description VARCHAR(255)");
         CRM_Core_DAO::executeQuery("UPDATE civicrm_report_instance SET description = description_{$locales[0]}");
         CRM_Core_DAO::executeQuery("DROP TRIGGER civicrm_report_instance_before_insert");
         foreach ($locales as $locale) {
             CRM_Core_DAO::executeQuery("DROP VIEW civicrm_report_instance_{$locale}");
             CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_report_instance DROP description_{$locale}");
         }
     }
     //We execute some part of php after sql and then again sql
     //So using conditions for skipping some part of sql CRM-4575
     $upgrade =& new CRM_Upgrade_Form();
     //Run the SQL file (1)
     $upgrade->processSQL($rev);
     //replace  with ; in report instance
     $sql = "UPDATE civicrm_report_instance \n                       SET form_values = REPLACE(form_values,'#',';') ";
     CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     //delete unnecessary activities
     $bulkEmailID = CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name');
     if ($bulkEmailID) {
         $mailingActivityIds = array();
         $query = " \n            SELECT max( ca.id ) as aid, \n                   ca.source_record_id sid\n            FROM civicrm_activity ca\n            WHERE ca.activity_type_id = %1 \n            GROUP BY ca.source_record_id";
         $params = array(1 => array($bulkEmailID, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             $updateQuery = "\n                UPDATE civicrm_activity_target cat, civicrm_activity ca \n                    SET cat.activity_id = {$dao->aid}  \n                WHERE ca.source_record_id IS NOT NULL   AND\n                      ca.activity_type_id = %1          AND \n                      ca.id <> {$dao->aid}              AND \n                      ca.source_record_id = {$dao->sid} AND \n                      ca.id = cat.activity_id";
             $updateParams = array(1 => array($bulkEmailID, 'Integer'));
             CRM_Core_DAO::executeQuery($updateQuery, $updateParams);
             $deleteQuery = " \n                DELETE ca.* \n                FROM civicrm_activity ca \n                WHERE ca.source_record_id IS NOT NULL  AND \n                      ca.activity_type_id = %1         AND \n                      ca.id <> {$dao->aid}             AND \n                      ca.source_record_id = {$dao->sid}";
             $deleteParams = array(1 => array($bulkEmailID, 'Integer'));
             CRM_Core_DAO::executeQuery($deleteQuery, $deleteParams);
         }
     }
     //CRM-4453
     //lets insert column in civicrm_aprticipant table
     $query = "\n        ALTER TABLE `civicrm_participant` \n            ADD `fee_currency` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL COMMENT '3 character string, value derived from config setting.' AFTER `discount_id`";
     CRM_Core_DAO::executeQuery($query);
     //get currency from contribution table if exists/default
     //insert currency when fee_amount != NULL or event is paid.
     $query = "\n        SELECT  civicrm_participant.id \n        FROM    civicrm_participant\n            LEFT JOIN  civicrm_event \n                   ON ( civicrm_participant.event_id = civicrm_event.id )\n        WHERE  civicrm_participant.fee_amount IS NOT NULL OR \n               civicrm_event.is_monetary = 1";
     $participant = CRM_Core_DAO::executeQuery($query);
     while ($participant->fetch()) {
         $query = "\n            SELECT civicrm_contribution.currency \n            FROM   civicrm_contribution, \n                   civicrm_participant_payment\n            WHERE  civicrm_contribution.id = civicrm_participant_payment.contribution_id AND  \n                   civicrm_participant_payment.participant_id = {$participant->id}";
         $currencyID = CRM_Core_DAO::singleValueQuery($query);
         if (!$currencyID) {
             $config =& CRM_Core_Config::singleton();
             $currencyID = $config->defaultCurrency;
         }
         //finally update participant record.
         CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participant->id, 'fee_currency', $currencyID);
     }
     //CRM-4575
     //check whether {contact.name} is set in mailing labels
     require_once 'CRM/Core/BAO/Preferences.php';
     $mailingFormat = CRM_Core_BAO_Preferences::value('mailing_format');
     $addNewAddressee = true;
     if (strpos($mailingFormat, '{contact.contact_name}') === false) {
         $addNewAddressee = false;
     } else {
         //else compare individual name format with default individual addressee.
         $individualNameFormat = CRM_Core_BAO_Preferences::value('individual_name_format');
         $defaultAddressee = CRM_Core_OptionGroup::values('addressee', false, false, false, " AND v.filter = 1 AND v.is_default =  1", 'label');
         if (array_search($individualNameFormat, $defaultAddressee) !== false) {
             $addNewAddressee = false;
         }
     }
     require_once 'CRM/Utils/System.php';
     $docURL = CRM_Utils_System::docURL2('Update Greetings and Address Data for Contacts', false, null, null, 'color: white; text-decoration: underline;');
     if ($addNewAddressee) {
         //otherwise insert new token in addressee and set as a default
         $addresseeGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'addressee', 'id', 'name');
         $optionValueParams = array('label' => $individualNameFormat, 'is_active' => 1, 'contactOptions' => 1, 'filter' => 1, 'is_default' => 1, 'reset_default_for' => array('filter' => "0, 1"));
         $action = CRM_Core_Action::ADD;
         $addresseeGroupParams = array('name' => 'addressee');
         $fieldValues = array('option_group_id' => $addresseeGroupId);
         $weight = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
         $optionValueParams['weight'] = $weight;
         $addresseeToken = CRM_Core_OptionValue::addOptionValue($optionValueParams, $addresseeGroupParams, $action, $optionId = null);
         $afterUpgradeMessage = ts("During this upgrade, Postal Addressee values have been stored for each contact record using the system default format - %2.You will need to run the included command-line script to update your Individual contact records to use the \"Individual Name Format\" previously specified for your site %1", array(1 => $docURL, 2 => array_pop($defaultAddressee)));
     } else {
         $afterUpgradeMessage = ts("Email Greeting, Postal Greeting and Postal Addressee values have been stored for all contact records based on the system default formats. If you want to use a different format for any of these contact fields - you can run the provided command line script to update contacts to a different format %1 ", array(1 => $docURL));
     }
     //replace contact.contact_name with contact.addressee in civicrm_preference.mailing_format
     $updateQuery = "\n        UPDATE civicrm_preferences \n               SET `mailing_format` = \n                    replace(`mailing_format`, '{contact.contact_name}','{contact.addressee}')";
     CRM_Core_DAO::executeQuery($updateQuery);
     //drop column individual_name_format
     $alterQuery = "\n        ALTER TABLE `civicrm_preferences`\n              DROP `individual_name_format`";
     CRM_Core_DAO::executeQuery($alterQuery);
     //set status message for default greetings
     $template =& CRM_Core_Smarty::singleton();
     $template->assign('afterUpgradeMessage', $afterUpgradeMessage);
 }
Example #12
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);
 }
Example #13
0
 static function optionExists($value, $options)
 {
     return CRM_Core_OptionValue::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array::value(3, $options, 'name'));
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Core_BAO_OptionValue::del($this->_id)) {
             CRM_Core_Session::setStatus(ts('Selected %1 Report has been deleted.', array(1 => $this->_GName)));
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/report/options/report_template', "reset=1"));
         } else {
             CRM_Core_Session::setStatus(ts('Selected %1 type has not been deleted.', array(1 => $this->_GName)));
             CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $fieldValues);
         }
     } else {
         // get the submitted form values.
         $params = $this->controller->exportValues($this->_name);
         $ids = array();
         $groupParams = array('name' => 'report_template');
         $optionValue = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $this->_action, $this->_id);
         CRM_Core_Session::setStatus(ts('The %1 \'%2\' has been saved.', array(1 => 'Report Template', 2 => $optionValue->label)));
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/report/options/report_template', "reset=1"));
     }
 }
Example #15
0
 /**
  * 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.
  *
  * @return array|bool|int
  *   'main_loc_block' => Stores all location blocks associated with the 'main' contact
  */
 public static function getRowsElementsAndInfo($mainId, $otherId)
 {
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     // Fetch contacts
     foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
         $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
         $result = civicrm_api('contact', 'get', $params);
         if (empty($result['values'][$cid]['contact_type'])) {
             return FALSE;
         }
         ${$moniker} = $result['values'][$cid];
     }
     $fields = CRM_Contact_DAO_Contact::fields();
     // FIXME: there must be a better way
     foreach (array('main', 'other') 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, 'communication_style_id' => $value);
         if (!empty($contact['preferred_communication_method'])) {
             // 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);
         if (!empty($contact['communication_style'])) {
             $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
         }
     }
     static $optionValueFields = array();
     if (empty($optionValueFields)) {
         $optionValueFields = CRM_Core_OptionValue::getFields();
     }
     foreach ($optionValueFields as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     $compareFields = self::retrieveFields($main, $other);
     $rows = $elements = $relTableElements = $migrationInfo = array();
     foreach ($compareFields['contact'] as $field) {
         if ($field == 'contact_sub_type') {
             // CRM-15681 don't display sub-types in UI
             continue;
         }
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             if (isset($specialValues[$moniker][$field]) && is_string($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}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif (!empty($fields[$field]['type']) && $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('individual_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('individual_suffix', $contact);
                 $value = CRM_Utils_Array::value('suffix_id', $contact);
                 $field = 'suffix_id';
             } elseif ($field == 'gender_id' && !empty($value)) {
                 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
                 $label = $genderOptions['values'][$value];
             } elseif ($field == 'current_employer_id' && !empty($value)) {
                 $label = "{$value} (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 //CRM-14334
                 if ($value === NULL || $value == '') {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $qfZeroBug;
                 }
                 if (is_array($value) && empty($value[1])) {
                     $value[1] = NULL;
                 }
                 // Display a checkbox to migrate, only if the values are different
                 if ($value != $main[$field]) {
                     $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value);
                 }
                 $migrationInfo["move_{$field}"] = $value;
             }
         }
         $rows["move_{$field}"]['title'] = $fields[$field]['title'];
     }
     // Handle location blocks.
     // @todo OpenID not in API yet, so is not supported here.
     // Set up useful information about the location blocks
     $locationBlocks = self::getLocationBlockInfo();
     $locations = array('main' => array(), 'other' => array());
     $mainLocBlock = array();
     // @todo This could probably be defined and used earlier
     $mergeTargets = array('main' => $mainId, 'other' => $otherId);
     foreach ($locationBlocks as $blockName => $blockInfo) {
         // Collect existing fields from both 'main' and 'other' contacts first
         // This allows us to match up location/types when building the table rows
         foreach ($mergeTargets as $moniker => $cid) {
             $cnt = 1;
             $searchParams = array('version' => 3, 'contact_id' => $cid, 'options' => array('sort' => $blockInfo['sortString']));
             $values = civicrm_api($blockName, 'get', $searchParams);
             if ($values['count']) {
                 $cnt = 0;
                 foreach ($values['values'] as $index => $value) {
                     $locations[$moniker][$blockName][$cnt] = $value;
                     // Fix address display
                     $display = '';
                     if ($blockName == 'address') {
                         CRM_Core_BAO_Address::fixAddress($value);
                         $display = CRM_Utils_Address::format($value);
                         $locations[$moniker][$blockName][$cnt]['display'] = $display;
                     }
                     // Add any 'main' contact block values to an array for the JS
                     // @todo The JS should just access the main_details to find this info?
                     if ($moniker == 'main') {
                         if ($blockInfo['hasType']) {
                             // Handle websites, no location type ID
                             // @todo Remove the need for this specific 'if'
                             if ($blockName == 'website') {
                                 $value['location_type_id'] = 0;
                             }
                             $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['display'] = $value[$blockInfo['displayField']];
                             $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['id'] = $value['id'];
                         } else {
                             // Get the correct display value for addresses
                             // @todo Remove the need for this if...
                             if ($blockName == 'address') {
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $display;
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id'];
                             } else {
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $value[$blockInfo['displayField']];
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id'];
                             }
                         }
                     }
                     $cnt++;
                 }
             }
         }
         // Now, build the table rows appropriately, based off the information on
         // the 'other' contact
         if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
             foreach ($locations['other'][$blockName] as $count => $value) {
                 $displayValue = $value[$blockInfo['displayField']];
                 // Add this value to the table rows
                 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
                 // CRM-17556 Only display 'main' contact value if it's the same location + type
                 // Look it up from main values...
                 $lookupLocation = FALSE;
                 if ($blockInfo['hasLocation']) {
                     $lookupLocation = $value['location_type_id'];
                 }
                 $lookupType = FALSE;
                 if ($blockInfo['hasType']) {
                     $lookupType = $value[$blockInfo['hasType']];
                 }
                 // Hold ID of main contact's matching block
                 $mainContactBlockId = 0;
                 if (!empty($locations['main'][$blockName])) {
                     foreach ($locations['main'][$blockName] as $mainValueCheck) {
                         // No location/type, or matching location and type
                         if ((empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id']) && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])) {
                             // Set this value as the default against the 'other' contact value
                             $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
                             $mainContactBlockId = $mainValueCheck['id'];
                             break;
                         }
                     }
                 }
                 // Add checkbox to migrate data from 'other' to 'main'
                 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
                 // Flag up this field to skipMerge function (@todo: do we need to?)
                 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
                 // Add a hidden field to store the ID of the target main contact block
                 $elements[] = array('hidden', "location[{$blockName}][{$count}][mainContactBlockId]", $mainContactBlockId);
                 // Setup variables
                 $thisTypeId = FALSE;
                 $thisLocId = FALSE;
                 // Provide a select drop-down for the location's location type
                 // eg: Home, Work...
                 $js = NULL;
                 if ($blockInfo['hasLocation']) {
                     // Load the location options for this entity
                     $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
                     // JS lookup 'main' contact's location (if there are any)
                     if (!empty($locations['main'][$blockName])) {
                         $js = array('onChange' => "mergeBlock('{$blockName}', this, {$count}, 'locTypeId' );");
                     }
                     $thisLocId = $value['location_type_id'];
                     // Put this field's location type at the top of the list
                     $tmpIdList = $locationOptions['values'];
                     $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
                     unset($tmpIdList[$thisLocId]);
                     // Add the element
                     $elements[] = array('select', "location[{$blockName}][{$count}][locTypeId]", NULL, $defaultLocId + $tmpIdList, $js);
                     // Add the relevant information to the $migrationInfo
                     // Keep location-type-id same as that of other-contact
                     // @todo Check this logic out
                     $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
                     if ($blockName != 'address') {
                         $elements[] = array('advcheckbox', "location[{$blockName}][{$count}][operation]", NULL, ts('add new'));
                         // always use add operation
                         $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
                     }
                 }
                 // Provide a select drop-down for the location's type/provider
                 // eg websites: Google+, Facebook...
                 $js = NULL;
                 if ($blockInfo['hasType']) {
                     // Load the type options for this entity
                     $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
                     // CRM-17556 Set up JS lookup of 'main' contact's value by type
                     if (!empty($locations['main'][$blockName])) {
                         $js = array('onChange' => "mergeBlock('{$blockName}', this, {$count}, 'typeTypeId' );");
                     }
                     $thisTypeId = $value[$blockInfo['hasType']];
                     // Put this field's location type at the top of the list
                     $tmpIdList = $typeOptions['values'];
                     $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
                     unset($tmpIdList[$thisTypeId]);
                     // Add the element
                     $elements[] = array('select', "location[{$blockName}][{$count}][typeTypeId]", NULL, $defaultTypeId + $tmpIdList, $js);
                     // Add the information to the migrationInfo (@todo Why?)
                     $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
                 }
                 // Set the label for this row
                 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
                 if (!empty($thisLocId)) {
                     $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
                 }
                 if (!empty($thisTypeId)) {
                     $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
                 }
                 $rows["move_location_{$blockName}_{$count}"]['title'] = $rowTitle;
             }
             // End loop through 'other' locations of this type
         }
         // End if 'other' location for this type exists
     }
     // End loop through each location block entity
     // 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();
     foreach ($otherTree as $gid => $group) {
         $foundField = FALSE;
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             if (in_array($fid, $compareFields['custom'])) {
                 if (!$foundField) {
                     $rows["custom_group_{$gid}"]['title'] = $group['title'];
                     $foundField = TRUE;
                 }
                 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
                     }
                 }
                 $value = "null";
                 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
                         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']['location_blocks'] = $locations['main'];
     $result['other_details']['location_blocks'] = $locations['other'];
     return $result;
 }
Example #16
0
 /**
  * Process the form when submitted
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     require_once 'CRM/Core/BAO/Domain.php';
     $params = array();
     $params = $this->exportValues();
     $params['entity_id'] = $this->_id;
     $params['entity_table'] = CRM_Core_BAO_Domain::getTableName();
     $domain = CRM_Core_BAO_Domain::edit($params, $this->_id);
     require_once 'CRM/Core/BAO/LocationType.php';
     $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault();
     $location = array();
     $params['address'][1]['location_type_id'] = $defaultLocationType->id;
     $params['phone'][1]['location_type_id'] = $defaultLocationType->id;
     $params['email'][1]['location_type_id'] = $defaultLocationType->id;
     $location = CRM_Core_BAO_Location::create($params, true, 'domain');
     $params['loc_block_id'] = $location['id'];
     require_once 'CRM/Core/BAO/Domain.php';
     CRM_Core_BAO_Domain::edit($params, $this->_id);
     //set domain from email address, CRM-3552
     $emailName = '"' . $params['email_name'] . '"<' . $params['email_address'] . '>';
     $emailParams = array('label' => $emailName, 'description' => $params['description'], 'is_active' => 1, 'is_default' => 1);
     $groupParams = array('name' => 'from_email_address');
     //get the option value wt.
     if ($this->_fromEmailId) {
         $action = $this->_action;
         $emailParams['weight'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_fromEmailId, 'weight');
     } else {
         //add from email address.
         $action = CRM_Core_Action::ADD;
         require_once 'CRM/Utils/Weight.php';
         $grpId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'from_email_address', 'id', 'name');
         $fieldValues = array('option_group_id' => $grpId);
         $emailParams['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
     }
     require_once 'CRM/Core/OptionValue.php';
     //reset default within domain.
     $emailParams['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
     CRM_Core_OptionValue::addOptionValue($emailParams, $groupParams, $action, $this->_fromEmailId);
     CRM_Core_Session::setStatus(ts('Domain information for \'%1\' has been saved.', array(1 => $domain->name)));
     $session =& CRM_Core_Session::singleton();
     $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
 }
Example #17
0
 /**
  * This function preserve the civicrm_domain.email_name and civicrm_domain.email_address
  * as a default option value into "from_email_address" option group
  * and drop these columns from civicrm_domain table.
  * @access public
  *
  * @return void
  */
 function upgradeDomainFromEmail()
 {
     $query = "\nSELECT id\n  FROM civicrm_option_group\n WHERE name = 'from_Email_address'";
     $fmaGroup = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     $fmaGroupId = NULL;
     if ($fmaGroup->fetch()) {
         $fmaGroupId = $fmaGroup->id;
     } else {
         //insert 'from_mailing_address' option group.
         $query = "\nINSERT INTO civicrm_option_group ( name, description, is_reserved, is_active )\nVALUES ('from_email_address', 'From Email Address', 0, 1)";
         CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
         //get the group id.
         $query = "\nSELECT id\n  FROM civicrm_option_group\n WHERE name = 'from_email_address'";
         $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
         if ($dao->fetch()) {
             $fmaGroupId = $dao->id;
         }
     }
     if ($fmaGroupId) {
         //get domain from email address and name as default value.
         $domain = CRM_Core_BAO_Domain::getDomain();
         $domain->selectAdd();
         $domain->selectAdd('email_name', 'email_address');
         $domain->find(TRUE);
         $formEmailAddress = '"' . $domain->email_name . '"<' . $domain->email_address . '>';
         //first check given domain email address exist in option
         //value, if yes make it as domain email address by making
         //it as default from email address..
         //get the existing from email address.
         $optionValues = array();
         $grpParams['name'] = 'from_email_address';
         CRM_Core_OptionValue::getValues($grpParams, $optionValues);
         $maxVal = $maxWt = 1;
         $insertEmailAddress = TRUE;
         if (!empty($optionValues)) {
             //make existing is_default = 0
             $query = "\nUPDATE  civicrm_option_value\n   SET  is_default = 0\n WHERE  option_group_id = %1";
             $params = array(1 => array($fmaGroupId, 'Integer'));
             CRM_Core_DAO::executeQuery($query, $params);
             //if domain from name and email exist as name or label in option value
             //table need to preserve that name and label  and take care that label
             //and name both remain unique in db.
             $labelValues = $nameValues = array();
             foreach ($optionValues as $id => $value) {
                 if ($value['label'] == $formEmailAddress) {
                     $labelValues = $value;
                 } elseif ($value['name'] == $formEmailAddress) {
                     $nameValues = $value;
                 }
             }
             //as we consider label so label should preserve.
             $updateValues = array();
             if (!empty($labelValues)) {
                 $updateValues = $labelValues;
             }
             //if matching name found need to preserve it.
             if (!empty($nameValues)) {
                 //copy domain from email address as label.
                 if (empty($updateValues)) {
                     $updateValues = $nameValues;
                     $updateValues['label'] = $formEmailAddress;
                 } else {
                     //since name is also imp so preserve it
                     //as name for domain email address record.
                     $updateValues['name'] = $nameValues['name'];
                     //name is unique so drop name value record.
                     //since we transfer this name to found label record.
                     CRM_Core_BAO_OptionValue::del($nameValues['id']);
                 }
             }
             if (!empty($updateValues)) {
                 $insertEmailAddress = FALSE;
                 //update label/name found record w/ manupulated values.
                 $updateValues['is_active'] = $updateValues['is_default'] = 1;
                 $optionValue = new CRM_Core_DAO_OptionValue();
                 $optionValue->copyValues($updateValues);
                 $optionValue->save();
             }
             //get the max value and wt.
             if ($insertEmailAddress) {
                 $query = "\nSELECT   max(ROUND(civicrm_option_value.value)) as maxVal,\n         max(civicrm_option_value.weight) as maxWt\n    FROM civicrm_option_value, civicrm_option_group\n   WHERE civicrm_option_group.name = 'from_Email_address'\n     AND civicrm_option_value.option_group_id = civicrm_option_group.id\nGROUP BY civicrm_option_group.id";
                 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
                 if ($dao->fetch()) {
                     $maxWt += $dao->maxWt;
                     $maxVal += $dao->maxVal;
                 }
             }
         }
         if ($insertEmailAddress) {
             //insert domain from email address and name.
             $query = "\nINSERT INTO  `civicrm_option_value`\n             (`option_group_id`, `label`, `value`, `name` , `grouping`, `filter`, `is_default`,\n              `weight`, `description`, `is_optgroup`, `is_reserved`, `is_active`, `component_id`)\n     VALUES  ( %1, %2, %3, %2, NULL, 0, 1, %4, 'Default domain email address and from name.', 0, 0, 1, NULL)";
             $params = array(1 => array($fmaGroupId, 'Integer'), 2 => array($formEmailAddress, 'String'), 3 => array($maxVal, 'Integer'), 4 => array($maxWt, 'Integer'));
             CRM_Core_DAO::executeQuery($query, $params);
         }
         //drop civicrm_domain.email_name and
         //civicrm_domain.email_address.
         $query = "\nALTER TABLE `civicrm_domain`\n       DROP `email_name`,\n       DROP `email_address`";
         CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     }
 }
Example #18
0
 /**
  * Browse all options
  *  
  * 
  * @return void
  * @access public
  * @static
  */
 function browse()
 {
     require_once 'CRM/Core/OptionValue.php';
     $groupParams = array('name' => self::$_gName);
     $optionValue = CRM_Core_OptionValue::getRows($groupParams, $this->links(), 'component_id,weight');
     $gName = self::$_gName;
     $returnURL = CRM_Utils_System::url("civicrm/admin/options/{$gName}", "reset=1&group={$gName}");
     $filter = "option_group_id = " . self::$_gId;
     require_once 'CRM/Utils/Weight.php';
     CRM_Utils_Weight::addOrder($optionValue, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
     $this->assign('rows', $optionValue);
 }
Example #19
0
 /**
  * Given a list of conditions in params and a list of desired
  * return Properties generate the required select and from
  * clauses. Note that since the where clause introduces new
  * tables, the initial attempt also retrieves all variables used
  * in the params list
  */
 public function selectClause()
 {
     $this->addSpecialFields();
     foreach ($this->_fields as $name => $field) {
         // skip component fields
         // there are done by the alter query below
         // and need not be done on every field
         if (substr($name, 0, 12) == 'participant_' || substr($name, 0, 7) == 'pledge_' || substr($name, 0, 5) == 'case_' || substr($name, 0, 13) == 'contribution_' && (strpos($name, 'source') !== FALSE && strpos($name, 'recur') !== FALSE) || substr($name, 0, 8) == 'payment_') {
             continue;
         }
         // redirect to activity select clause
         if (substr($name, 0, 9) == 'activity_' || $name == 'parent_id') {
             CRM_Activity_BAO_Query::select($this);
             continue;
         }
         // if this is a hierarchical name, we ignore it
         $names = explode('-', $name);
         if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
             continue;
         }
         // make an exception for special cases, to add the field in select clause
         $makeException = FALSE;
         //special handling for groups/tags
         if (in_array($name, array('groups', 'tags', 'notes')) && isset($this->_returnProperties[substr($name, 0, -1)])) {
             $makeException = TRUE;
         }
         // since note has 3 different options we need special handling
         // note / note_subject / note_body
         if ($name == 'notes') {
             foreach (array('note', 'note_subject', 'note_body') as $noteField) {
                 if (isset($this->_returnProperties[$noteField])) {
                     $makeException = TRUE;
                     break;
                 }
             }
         }
         if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) {
             if (CRM_Utils_Array::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties)) {
                 $makeException = TRUE;
             }
         }
         $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
         if (!empty($this->_paramLookup[$name]) || !empty($this->_returnProperties[$name]) || $makeException) {
             if ($cfID) {
                 // add to cfIDs array if not present
                 if (!array_key_exists($cfID, $this->_cfIDs)) {
                     $this->_cfIDs[$cfID] = array();
                 }
             } elseif (isset($field['where'])) {
                 list($tableName, $fieldName) = explode('.', $field['where'], 2);
                 if (isset($tableName)) {
                     if (CRM_Utils_Array::value($tableName, self::$_dependencies)) {
                         $this->_tables['civicrm_address'] = 1;
                         $this->_select['address_id'] = 'civicrm_address.id as address_id';
                         $this->_element['address_id'] = 1;
                     }
                     if ($tableName == 'im_provider' || $tableName == 'email_greeting' || $tableName == 'postal_greeting' || $tableName == 'addressee') {
                         if ($tableName == 'im_provider') {
                             CRM_Core_OptionValue::select($this);
                         }
                         if (in_array($tableName, array('email_greeting', 'postal_greeting', 'addressee'))) {
                             $this->_element["{$name}_id"] = 1;
                             $this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
                             $this->_pseudoConstantsSelect[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
                             $this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as {$name}";
                             $this->_pseudoConstantsSelect[$name]['element'] = $name;
                             if ($tableName == 'email_greeting') {
                                 $this->_pseudoConstantsSelect[$name]['join'] = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
                                 $this->_pseudoConstantsSelect[$name]['join'] .= " LEFT JOIN civicrm_option_value email_greeting ON (contact_a.email_greeting_id = email_greeting.value AND option_group_email_greeting.id = email_greeting.option_group_id ) ";
                             } elseif ($tableName == 'postal_greeting') {
                                 $this->_pseudoConstantsSelect[$name]['join'] = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
                                 $this->_pseudoConstantsSelect[$name]['join'] .= " LEFT JOIN civicrm_option_value postal_greeting ON (contact_a.postal_greeting_id = postal_greeting.value AND option_group_postal_greeting.id = postal_greeting.option_group_id ) ";
                             } elseif ($tableName == 'addressee') {
                                 $this->_pseudoConstantsSelect[$name]['join'] = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
                                 $this->_pseudoConstantsSelect[$name]['join'] .= " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
                             }
                             $this->_pseudoConstantsSelect[$name]['table'] = $tableName;
                             //get display
                             $greetField = "{$name}_display";
                             $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
                             $this->_element[$greetField] = 1;
                             //get custom
                             $greetField = "{$name}_custom";
                             $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
                             $this->_element[$greetField] = 1;
                         }
                     } else {
                         if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
                             $this->_tables[$tableName] = 1;
                         }
                         // also get the id of the tableName
                         $tName = substr($tableName, 8);
                         if (in_array($tName, array('country', 'state_province', 'county'))) {
                             if ($tName == 'state_province') {
                                 $this->_pseudoConstantsSelect['state_province_name'] = array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address', 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
                                 $this->_pseudoConstantsSelect[$tName] = array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id", 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
                             } else {
                                 $this->_pseudoConstantsSelect[$name] = array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address', 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
                             }
                             $this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
                             $this->_element["{$tName}_id"] = 1;
                         } elseif ($tName != 'contact') {
                             $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
                             $this->_element["{$tName}_id"] = 1;
                         }
                         //special case for phone
                         if ($name == 'phone') {
                             $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
                             $this->_element['phone_type_id'] = 1;
                         }
                         // if IM then select provider_id also
                         // to get "IM Service Provider" in a file to be exported, CRM-3140
                         if ($name == 'im') {
                             $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id";
                             $this->_element['provider_id'] = 1;
                         }
                         if ($tName == 'contact') {
                             // special case, when current employer is set for Individual contact
                             if ($fieldName == 'organization_name') {
                                 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
                             } elseif ($fieldName != 'id') {
                                 if ($fieldName == 'prefix_id') {
                                     $this->_pseudoConstantsSelect['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
                                 }
                                 if ($fieldName == 'suffix_id') {
                                     $this->_pseudoConstantsSelect['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
                                 }
                                 if ($fieldName == 'gender_id') {
                                     $this->_pseudoConstantsSelect['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
                                 }
                                 if ($name == 'communication_style_id') {
                                     $this->_pseudoConstantsSelect['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
                                 }
                                 $this->_select[$name] = "contact_a.{$fieldName}  as `{$name}`";
                             }
                         } elseif (in_array($tName, array('country', 'county'))) {
                             $this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `{$name}`";
                             $this->_pseudoConstantsSelect[$name]['element'] = $name;
                         } elseif ($tName == 'state_province') {
                             $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `{$name}`";
                             $this->_pseudoConstantsSelect[$tName]['element'] = $name;
                         } else {
                             $this->_select[$name] = "{$field['where']} as `{$name}`";
                         }
                         if (!in_array($tName, array('state_province', 'country', 'county'))) {
                             $this->_element[$name] = 1;
                         }
                     }
                 }
             } elseif ($name === 'tags') {
                 $this->_useGroupBy = TRUE;
                 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
                 $this->_element[$name] = 1;
                 $this->_tables['civicrm_tag'] = 1;
                 $this->_tables['civicrm_entity_tag'] = 1;
             } elseif ($name === 'groups') {
                 $this->_useGroupBy = TRUE;
                 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
                 $this->_element[$name] = 1;
                 $this->_tables['civicrm_group'] = 1;
             } elseif ($name === 'notes') {
                 // if note field is subject then return subject else body of the note
                 $noteColumn = 'note';
                 if (isset($noteField) && $noteField == 'note_subject') {
                     $noteColumn = 'subject';
                 }
                 $this->_useGroupBy = TRUE;
                 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.{$noteColumn})) as notes";
                 $this->_element[$name] = 1;
                 $this->_tables['civicrm_note'] = 1;
             } elseif ($name === 'current_employer') {
                 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
                 $this->_element[$name] = 1;
             }
         }
         if ($cfID && !empty($field['is_search_range'])) {
             // this is a custom field with range search enabled, so we better check for two/from values
             if (!empty($this->_paramLookup[$name . '_from'])) {
                 if (!array_key_exists($cfID, $this->_cfIDs)) {
                     $this->_cfIDs[$cfID] = array();
                 }
                 foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) {
                     // search in the cdID array for the same grouping
                     $fnd = FALSE;
                     foreach ($this->_cfIDs[$cfID] as $cID => $c) {
                         if ($c[3] == $p[3]) {
                             $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2];
                             $fnd = TRUE;
                         }
                     }
                     if (!$fnd) {
                         $p[2] = array('from' => $p[2]);
                         $this->_cfIDs[$cfID][] = $p;
                     }
                 }
             }
             if (!empty($this->_paramLookup[$name . '_to'])) {
                 if (!array_key_exists($cfID, $this->_cfIDs)) {
                     $this->_cfIDs[$cfID] = array();
                 }
                 foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) {
                     // search in the cdID array for the same grouping
                     $fnd = FALSE;
                     foreach ($this->_cfIDs[$cfID] as $cID => $c) {
                         if ($c[4] == $p[4]) {
                             $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2];
                             $fnd = TRUE;
                         }
                     }
                     if (!$fnd) {
                         $p[2] = array('to' => $p[2]);
                         $this->_cfIDs[$cfID][] = $p;
                     }
                 }
             }
         }
     }
     // add location as hierarchical elements
     $this->addHierarchicalElements();
     // add multiple field like website
     $this->addMultipleElements();
     //fix for CRM-951
     CRM_Core_Component::alterQuery($this, 'select');
     CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'select');
     if (!empty($this->_cfIDs)) {
         // @todo This function is the select function but instead of running 'select' it
         // is running the whole query.
         $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields);
         $this->_customQuery->query();
         $this->_select = array_merge($this->_select, $this->_customQuery->_select);
         $this->_element = array_merge($this->_element, $this->_customQuery->_element);
         $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
         $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables);
         $this->_options = $this->_customQuery->_options;
     }
 }
Example #20
0
 /**
  * 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.
  *
  * @return array|bool|int
  */
 public static function getRowsElementsAndInfo($mainId, $otherId)
 {
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     // Fetch contacts
     foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
         $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
         $result = civicrm_api('contact', 'get', $params);
         if (empty($result['values'][$cid]['contact_type'])) {
             return FALSE;
         }
         ${$moniker} = $result['values'][$cid];
     }
     static $fields = array();
     if (empty($fields)) {
         $fields = CRM_Contact_DAO_Contact::fields();
         CRM_Core_DAO::freeResult();
     }
     // FIXME: there must be a better way
     foreach (array('main', 'other') 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, 'communication_style_id' => $value);
         if (!empty($contact['preferred_communication_method'])) {
             // 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);
         if (!empty($contact['communication_style'])) {
             $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
         }
     }
     static $optionValueFields = array();
     if (empty($optionValueFields)) {
         $optionValueFields = CRM_Core_OptionValue::getFields();
     }
     foreach ($optionValueFields as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     $diffs = self::findDifferences($main, $other);
     $rows = $elements = $relTableElements = $migrationInfo = array();
     $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
     foreach ($diffs['contact'] as $field) {
         if ($field == 'contact_sub_type') {
             // CRM-15681 don't display sub-types in UI
             continue;
         }
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             if (isset($specialValues[$moniker][$field]) && is_string($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}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif (!empty($fields[$field]['type']) && $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('individual_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('individual_suffix', $contact);
                 $value = CRM_Utils_Array::value('suffix_id', $contact);
                 $field = 'suffix_id';
             } elseif ($field == 'gender_id' && !empty($value)) {
                 $label = $genders[$value];
             } elseif ($field == 'current_employer_id' && !empty($value)) {
                 $label = "{$value} (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 //CRM-14334
                 if ($value === NULL || $value == '') {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $qfZeroBug;
                 }
                 if (is_array($value) && empty($value[1])) {
                     $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');
     $locations = array();
     foreach ($locationBlocks as $block) {
         foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
             $cnt = 1;
             $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
             $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[$moniker][$block][$cnt] = $value;
                             $locations[$moniker][$block][$cnt]['display'] = $display;
                         } else {
                             $locations[$moniker][$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[$moniker][$block][$cnt] = $values['values'][$id];
                         $locations[$moniker][$block][$cnt]['display'] = $display;
                     } else {
                         $locations[$moniker][$block][$cnt] = $values['values'][$id];
                     }
                 }
             }
         }
     }
     $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $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) {
             $locIndex = CRM_Utils_Array::value($moniker, $locations);
             $blockValue = CRM_Utils_Array::value($name, $locIndex, 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();
     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 (!empty($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, TRUE);
                     }
                 }
                 $value = "null";
                 if (!empty($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, 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'];
     return $result;
 }
Example #21
0
 /**
  * Browse all options.
  */
 public function browse()
 {
     $groupParams = array('name' => self::$_gName);
     $optionValue = CRM_Core_OptionValue::getRows($groupParams, $this->links(), 'weight');
     $gName = self::$_gName;
     $returnURL = CRM_Utils_System::url("civicrm/admin/report/options/{$gName}", "reset=1");
     $filter = "option_group_id = " . self::$_gId;
     $session = new CRM_Core_Session();
     $session->replaceUserContext($returnURL);
     CRM_Utils_Weight::addOrder($optionValue, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
     $this->assign('rows', $optionValue);
 }
 /**
  * @param $entityTable
  */
 public static function preProcess($entityTable)
 {
     self::$_entityId = (int) CRM_Utils_Request::retrieve('id', 'Positive');
     self::$_entityTable = $entityTable;
     if (self::$_entityId && $entityTable) {
         $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor(self::$_entityId, $entityTable);
         if ($checkParentExistsForThisId) {
             self::$_hasParent = TRUE;
             self::$_parentEntityId = $checkParentExistsForThisId;
             self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $entityTable);
         } else {
             self::$_parentEntityId = self::$_entityId;
             self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId(self::$_entityId, $entityTable);
         }
         if (property_exists(self::$_scheduleReminderDetails, 'id')) {
             self::$_scheduleReminderID = self::$_scheduleReminderDetails->id;
         }
     }
     CRM_Core_OptionValue::getValues(array('name' => $entityTable . '_repeat_exclude_dates_' . self::$_parentEntityId), $optionValue);
     $excludeOptionValues = array();
     if (!empty($optionValue)) {
         foreach ($optionValue as $key => $val) {
             $excludeOptionValues[$val['value']] = substr(CRM_Utils_Date::mysqlToIso($val['value']), 0, 10);
         }
         self::$_excludeDateInfo = $excludeOptionValues;
     }
     // Assign variables
     $entityType = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable));
     $tpl = CRM_Core_Smarty::singleton();
     $tpl->assign('recurringEntityType', ts($entityType));
     $tpl->assign('currentEntityId', self::$_entityId);
     $tpl->assign('entityTable', self::$_entityTable);
     $tpl->assign('scheduleReminderId', self::$_scheduleReminderID);
     $tpl->assign('hasParent', self::$_hasParent);
 }
 /**
  * Given a list of conditions in params and a list of desired
  * return Properties generate the required select and from
  * clauses. Note that since the where clause introduces new
  * tables, the initial attempt also retrieves all variables used
  * in the params list
  *
  * @return void
  * @access public
  */
 function selectClause()
 {
     $properties = array();
     $this->addSpecialFields();
     // CRM_Core_Error::debug( 'f', $this->_fields );
     // CRM_Core_Error::debug( 'p', $this->_params );
     // CRM_Core_Error::debug( 'p', $this->_paramLookup );
     foreach ($this->_fields as $name => $field) {
         // skip component fields
         // there are done by the alter query below
         // and need not be done on every field
         if (substr($name, 0, 12) == 'participant_' || substr($name, 0, 7) == 'pledge_' || substr($name, 0, 5) == 'case_') {
             continue;
         }
         // redirect to activity select clause
         if (substr($name, 0, 9) == 'activity_') {
             CRM_Activity_BAO_Query::select($this);
             continue;
         }
         // if this is a hierarchical name, we ignore it
         $names = explode('-', $name);
         if (count($names > 1) && isset($names[1]) && is_numeric($names[1])) {
             continue;
         }
         $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
         if (CRM_Utils_Array::value($name, $this->_paramLookup) || CRM_Utils_Array::value($name, $this->_returnProperties)) {
             if ($cfID) {
                 // add to cfIDs array if not present
                 if (!array_key_exists($cfID, $this->_cfIDs)) {
                     $this->_cfIDs[$cfID] = array();
                 }
             } elseif (isset($field['where'])) {
                 list($tableName, $fieldName) = explode('.', $field['where'], 2);
                 if (isset($tableName)) {
                     if (substr($tableName, 0, 6) == 'quest_') {
                         $this->_select['ethnicity_id_1'] = 'ethnicity_id_1';
                         $this->_select['gpa_weighted_calc'] = 'gpa_weighted_calc';
                         $this->_select['SAT_composite'] = 'SAT_composite';
                         $this->_select['household_income_total'] = 'household_income_total';
                     }
                     if (CRM_Utils_Array::value($tableName, self::$_dependencies)) {
                         $this->_tables['civicrm_address'] = 1;
                         $this->_select['address_id'] = 'civicrm_address.id as address_id';
                         $this->_element['address_id'] = 1;
                     }
                     if ($tableName == 'gender' || $tableName == 'individual_prefix' || $tableName == 'individual_suffix' || $tableName == 'im_provider' || $tableName == 'email_greeting' || $tableName == 'postal_greeting' || $tableName == 'addressee') {
                         CRM_Core_OptionValue::select($this);
                         if (in_array($tableName, array('email_greeting', 'postal_greeting', 'addressee'))) {
                             //get display
                             $greetField = "{$name}_display";
                             $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
                             $this->_element[$greetField] = 1;
                             //get custom
                             $greetField = "{$name}_custom";
                             $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
                             $this->_element[$greetField] = 1;
                         }
                     } else {
                         $this->_tables[$tableName] = 1;
                         // also get the id of the tableName
                         $tName = substr($tableName, 8);
                         if ($tName != 'contact') {
                             $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
                             $this->_element["{$tName}_id"] = 1;
                         }
                         //special case for phone
                         if ($name == 'phone') {
                             $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
                             $this->_element['phone_type_id'] = 1;
                         }
                         // if IM then select provider_id also
                         // to get "IM Service Provider" in a file to be exported, CRM-3140
                         if ($name == 'im') {
                             $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id";
                             $this->_element['provider_id'] = 1;
                         }
                         if ($name == 'state_province') {
                             $this->_select[$name] = "civicrm_state_province.abbreviation as `{$name}`, civicrm_state_province.name as state_province_name";
                             $this->_element['state_province_name'] = 1;
                         } elseif ($tName == 'contact') {
                             // special case, when current employer is set for Individual contact
                             if ($fieldName == 'organization_name') {
                                 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
                             } elseif ($fieldName != 'id') {
                                 $this->_select[$name] = "contact_a.{$fieldName}  as `{$name}`";
                             }
                         } else {
                             $this->_select[$name] = "{$field['where']} as `{$name}`";
                         }
                         $this->_element[$name] = 1;
                     }
                 }
             } elseif ($name === 'tags') {
                 $this->_useGroupBy = TRUE;
                 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
                 $this->_element[$name] = 1;
                 $this->_tables['civicrm_tag'] = 1;
                 $this->_tables['civicrm_entity_tag'] = 1;
             } elseif ($name === 'groups') {
                 $this->_useGroupBy = TRUE;
                 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
                 $this->_element[$name] = 1;
                 $this->_tables['civicrm_group'] = 1;
             } elseif ($name === 'notes') {
                 $this->_useGroupBy = TRUE;
                 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.note)) as notes";
                 $this->_element[$name] = 1;
                 $this->_tables['civicrm_note'] = 1;
             } elseif ($name === 'current_employer') {
                 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
                 $this->_element[$name] = 1;
             }
         }
         if ($cfID && CRM_Utils_Array::value('is_search_range', $field)) {
             // this is a custom field with range search enabled, so we better check for two/from values
             if (CRM_Utils_Array::value($name . '_from', $this->_paramLookup)) {
                 if (!array_key_exists($cfID, $this->_cfIDs)) {
                     $this->_cfIDs[$cfID] = array();
                 }
                 foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) {
                     // search in the cdID array for the same grouping
                     $fnd = FALSE;
                     foreach ($this->_cfIDs[$cfID] as $cID => $c) {
                         if ($c[3] == $p[3]) {
                             $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2];
                             $fnd = TRUE;
                         }
                     }
                     if (!$fnd) {
                         $p[2] = array('from' => $p[2]);
                         $this->_cfIDs[$cfID][] = $p;
                     }
                 }
             }
             if (CRM_Utils_Array::value($name . '_to', $this->_paramLookup)) {
                 if (!array_key_exists($cfID, $this->_cfIDs)) {
                     $this->_cfIDs[$cfID] = array();
                 }
                 foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) {
                     // search in the cdID array for the same grouping
                     $fnd = FALSE;
                     foreach ($this->_cfIDs[$cfID] as $cID => $c) {
                         if ($c[4] == $p[4]) {
                             $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2];
                             $fnd = TRUE;
                         }
                     }
                     if (!$fnd) {
                         $p[2] = array('to' => $p[2]);
                         $this->_cfIDs[$cfID][] = $p;
                     }
                 }
             }
         }
     }
     // add location as hierarchical elements
     $this->addHierarchicalElements();
     // add multiple field like website
     $this->addMultipleElements();
     //fix for CRM-951
     CRM_Core_Component::alterQuery($this, 'select');
     if (!empty($this->_cfIDs)) {
         $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE);
         $this->_customQuery->query();
         $this->_select = array_merge($this->_select, $this->_customQuery->_select);
         $this->_element = array_merge($this->_element, $this->_customQuery->_element);
         $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
         $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables);
         $this->_options = $this->_customQuery->_options;
     }
 }
 /**
  * Will store the donor's account data
  *
  * @todo move to post processors
  */
 function storeAccountWithContact($btx, $contact_id)
 {
     // find all reference types
     $reference_type_group = array('name' => 'civicrm_banking.reference_types');
     $reference_types = array();
     CRM_Core_OptionValue::getValues($reference_type_group, $reference_types);
     // gather the information
     $data = $btx->getDataParsed();
     $references = array();
     foreach ($reference_types as $reference_type) {
         $field_name = '_party_' . $reference_type['name'];
         if (!empty($data[$field_name])) {
             $references[$reference_type['id']] = $data[$field_name];
         }
     }
     // if we don't have references, there's nothing we can do...
     if (empty($references)) {
         return;
     }
     // gather account info
     $account_info = array();
     if (!empty($data['_party_BIC'])) {
         $account_info['BIC'] = $data['_party_BIC'];
     }
     if (!empty($data['_party_IBAN'])) {
         $account_info['country'] = substr($data['_party_IBAN'], 0, 2);
     }
     // copy all entries that start with _party_ba_ into the account info
     foreach ($data as $key => $value) {
         if ('_party_ba_' == substr($key, 0, 10)) {
             if (!empty($value)) {
                 $new_key = substr($key, 10);
                 $account_info[$new_key] = $value;
             }
         }
     }
     // find all referenced bank accounts
     $bank_accounts = array();
     $contact_bank_account_id = NULL;
     $contact_bank_account_created = false;
     $reference2instances = array();
     foreach ($references as $reference_type => $reference) {
         $reference2instances[$reference] = array();
         $query = array('version' => 3, 'reference' => $reference, 'reference_type_id' => $reference_type);
         $existing = civicrm_api('BankingAccountReference', 'get', $query);
         if (empty($existing['is_error'])) {
             foreach ($existing['values'] as $account_reference) {
                 array_push($reference2instances[$reference], $account_reference);
                 if (!isset($bank_accounts[$account_reference['ba_id']])) {
                     // load the bank account
                     $ba_bao = new CRM_Banking_BAO_BankAccount();
                     $ba_bao->get('id', $account_reference['ba_id']);
                     $bank_accounts[$account_reference['ba_id']] = $ba_bao;
                 }
                 // consider this bank account to be ours if the contact id matches
                 if (!$contact_bank_account_id && $ba_bao->contact_id == $contact_id) {
                     $contact_bank_account_id = $ba_bao->id;
                 }
             }
         }
     }
     // create new account if it does not yet exist
     if (!$contact_bank_account_id) {
         $ba_bao = new CRM_Banking_BAO_BankAccount();
         $ba_bao->contact_id = $contact_id;
         $ba_bao->description = ts("created by CiviBanking");
         $ba_bao->created_date = date('YmdHis');
         $ba_bao->modified_date = date('YmdHis');
         $ba_bao->data_raw = NULL;
         $ba_bao->data_parsed = "{}";
         $ba_bao->save();
         $contact_bank_account_id = $ba_bao->id;
         $bank_accounts[$contact_bank_account_id] = $ba_bao;
         $contact_bank_account_created = true;
     }
     // update bank account data
     $ba_bao = $bank_accounts[$contact_bank_account_id];
     $ba_data = $ba_bao->getDataParsed();
     foreach ($account_info as $key => $value) {
         $ba_data[$key] = $value;
     }
     $ba_bao->setDataParsed($ba_data);
     $ba_bao->save();
     // create references (warn if exists for another contact)
     foreach ($references as $reference_type => $reference) {
         // check the existing
         $reference_already_there = false;
         foreach ($reference2instances[$reference] as $reference_instance) {
             if ($reference_instance['ba_id'] == $contact_bank_account_id) {
                 // there is already a reference for 'our' bank account
                 $reference_already_there = true;
                 break;
             }
         }
         if (!$reference_already_there) {
             // there was no reference to 'our' bank account -> create!
             $query = array('version' => 3, 'reference' => $reference, 'reference_type_id' => $reference_type, 'ba_id' => $contact_bank_account_id);
             $result = civicrm_api('BankingAccountReference', 'create', $query);
             if (!empty($result['is_error'])) {
                 CRM_Core_Session::setStatus(ts("Couldn't create reference. Error was: '%1'", array(1 => $result['error_message'])), ts('Error'), 'alert');
             }
         }
     }
     // finally, create some feedback
     if ($contact_bank_account_created) {
         if (count($bank_accounts) > 1) {
             // there are mutiple acccounts referenced by this
             $message = ts("The account information of this contact was saved, but it is also used by the following contacts:<br/><ul>%s</ul>");
             $contacts = "";
             foreach ($bank_accounts as $ba_id => $ba_bao) {
                 if ($ba_id == $contact_bank_account_id) {
                     continue;
                 }
                 $contact = civicrm_api('Contact', 'getsingle', array('version' => 3, 'id' => $ba_bao->contact_id));
                 if (empty($contact['is_error'])) {
                     $url = CRM_Utils_System::url('civicrm/contact/view', 'cid=' . $ba_bao->contact_id);
                     $contacts .= "<li><a href='{$url}'>" . $contact['display_name'] . "</a></li>";
                 }
             }
             CRM_Core_Session::setStatus(sprintf($message, $contacts), ts('Warning'), 'warn');
         } else {
             CRM_Core_Session::setStatus(ts("The account information of this contact was saved."), ts('Account saved'), 'info');
         }
     }
 }
 /**
  * Browse all options
  *
  *
  * @return void
  * @access public
  * @static
  */
 function browse()
 {
     $campaingCompId = CRM_Core_Component::getComponentID('CiviCampaign');
     $groupParams = array('name' => $this->_gName);
     $optionValues = CRM_Core_OptionValue::getRows($groupParams, $this->links(), 'component_id,weight');
     foreach ($optionValues as $key => $optionValue) {
         if (CRM_Utils_Array::value('component_id', $optionValue) != $campaingCompId) {
             unset($optionValues[$key]);
         }
     }
     $returnURL = CRM_Utils_System::url("civicrm/admin/campaign/surveyType", "reset=1");
     $filter = "option_group_id = " . $this->_gid;
     CRM_Utils_Weight::addOrder($optionValues, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
     $this->assign('rows', $optionValues);
 }
Example #26
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $fieldValues = array('option_group_id' => $this->_gid);
         $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
         if (CRM_Core_BAO_OptionValue::del($this->_id)) {
             if ($this->_gName == 'phone_type') {
                 CRM_Core_BAO_Phone::setOptionToNull(CRM_Utils_Array::value('value', $this->_defaultValues));
             }
             CRM_Core_Session::setStatus(ts('Selected %1 type has been deleted.', array(1 => $this->_gLabel)), ts('Record Deleted'), 'success');
         } else {
             CRM_Core_Session::setStatus(ts('Selected %1 type has not been deleted.', array(1 => $this->_gLabel)), ts('Sorry'), 'error');
             CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $fieldValues);
         }
     } else {
         $params = $ids = array();
         $params = $this->exportValues();
         // allow multiple defaults within group.
         $allowMultiDefaults = array('email_greeting', 'postal_greeting', 'addressee', 'from_email_address');
         if (in_array($this->_gName, $allowMultiDefaults)) {
             if ($this->_gName == 'from_email_address') {
                 $params['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
             } elseif ($filter = CRM_Utils_Array::value('contactOptions', $params)) {
                 $params['filter'] = $filter;
                 $params['reset_default_for'] = array('filter' => "0, " . $params['filter']);
             }
             //make sure we should has to have space, CRM-6977
             if ($this->_gName == 'from_email_address') {
                 $params['label'] = str_replace('"<', '" <', $params['label']);
             }
         }
         // set value of filter if not present in params
         if ($this->_id && !array_key_exists('filter', $params)) {
             if ($this->_gName == 'participant_role') {
                 $params['filter'] = 0;
             } else {
                 $params['filter'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'filter', 'id');
             }
         }
         $groupParams = array('name' => $this->_gName);
         $optionValue = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $this->_action, $this->_id);
         // CRM-11516
         if (!empty($params['financial_account_id'])) {
             $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
             $params = array('entity_table' => 'civicrm_option_value', 'entity_id' => $optionValue->id, 'account_relationship' => $relationTypeId, 'financial_account_id' => $params['financial_account_id']);
             CRM_Financial_BAO_FinancialTypeAccount::add($params);
         }
         CRM_Core_Session::setStatus(ts('The %1 \'%2\' has been saved.', array(1 => $this->_gLabel, 2 => $optionValue->label)), ts('Saved'), 'success');
     }
 }
Example #27
0
 static function loadOptionGroupDetails()
 {
     $id = CRM_Utils_Array::value('option_group_id', $_POST);
     $status = 'fail';
     $opValues = array();
     if ($id) {
         $groupParams['id'] = $id;
         CRM_Core_OptionValue::getValues($groupParams, $opValues);
     }
     $surveyId = CRM_Utils_Array::value('survey_id', $_POST);
     if ($surveyId) {
         $survey = new CRM_Campaign_DAO_Survey();
         $survey->id = $surveyId;
         $survey->result_id = $id;
         if ($survey->find(TRUE)) {
             if ($survey->recontact_interval) {
                 $recontactInterval = unserialize($survey->recontact_interval);
                 foreach ($opValues as $opValId => $opVal) {
                     if (is_numeric($recontactInterval[$opVal['label']])) {
                         $opValues[$opValId]['interval'] = $recontactInterval[$opVal['label']];
                     }
                 }
             }
         }
     }
     if (!empty($opValues)) {
         $status = 'success';
     }
     $result = array('status' => $status, 'result' => $opValues);
     echo json_encode($result);
     CRM_Utils_System::civiExit();
 }
 /**
  * Get the list of types for objects that a custom group extends to.
  *
  * @param array $types
  *   Var which should have the list appended.
  *
  * @return array
  *   Array of types.
  */
 public static function getExtendedObjectTypes(&$types = array())
 {
     static $flag = FALSE, $objTypes = array();
     if (!$flag) {
         $extendObjs = array();
         CRM_Core_OptionValue::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
         foreach ($extendObjs as $ovId => $ovValues) {
             if ($ovValues['description']) {
                 // description is expected to be a callback func to subtypes
                 list($callback, $args) = explode(';', trim($ovValues['description']));
                 if (empty($args)) {
                     $args = array();
                 }
                 if (!is_array($args)) {
                     CRM_Core_Error::fatal('Arg is not of type array');
                 }
                 list($className) = explode('::', $callback);
                 require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
                 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
             }
         }
         $flag = TRUE;
     }
     $types = array_merge($types, $objTypes);
     return $objTypes;
 }
Example #29
0
 public static function loadOptionGroupDetails()
 {
     $id = CRM_Utils_Request::retrieve('option_group_id', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST');
     $status = 'fail';
     $opValues = array();
     if ($id) {
         $groupParams['id'] = $id;
         CRM_Core_OptionValue::getValues($groupParams, $opValues);
     }
     $surveyId = CRM_Utils_Request::retrieve('survey_id', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST');
     if ($surveyId) {
         $survey = new CRM_Campaign_DAO_Survey();
         $survey->id = $surveyId;
         $survey->result_id = $id;
         if ($survey->find(TRUE)) {
             if ($survey->recontact_interval) {
                 $recontactInterval = unserialize($survey->recontact_interval);
                 foreach ($opValues as $opValId => $opVal) {
                     if (is_numeric($recontactInterval[$opVal['label']])) {
                         $opValues[$opValId]['interval'] = $recontactInterval[$opVal['label']];
                     }
                 }
             }
         }
     }
     if (!empty($opValues)) {
         $status = 'success';
     }
     $result = array('status' => $status, 'result' => $opValues);
     CRM_Utils_JSON::output($result);
 }
Example #30
0
 /**
  * Process the form when submitted.
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $params['entity_id'] = $this->_id;
     $params['entity_table'] = CRM_Core_BAO_Domain::getTableName();
     $domain = CRM_Core_BAO_Domain::edit($params, $this->_id);
     $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
     if (isset($this->_locationDefaults['address'][1]['location_type_id'])) {
         $params['address'][1]['location_type_id'] = $this->_locationDefaults['address'][1]['location_type_id'];
     } else {
         $params['address'][1]['location_type_id'] = $defaultLocationType->id;
     }
     if (isset($this->_locationDefaults['phone'][1]['location_type_id'])) {
         $params['phone'][1]['location_type_id'] = $this->_locationDefaults['phone'][1]['location_type_id'];
     } else {
         $params['phone'][1]['location_type_id'] = $defaultLocationType->id;
     }
     if (isset($this->_locationDefaults['email'][1]['location_type_id'])) {
         $params['email'][1]['location_type_id'] = $this->_locationDefaults['email'][1]['location_type_id'];
     } else {
         $params['email'][1]['location_type_id'] = $defaultLocationType->id;
     }
     $params += array('contact_id' => $this->_contactId);
     $contactParams = array('sort_name' => $domain->name, 'display_name' => $domain->name, 'legal_name' => $domain->name, 'organization_name' => $domain->name, 'contact_id' => $this->_contactId, 'contact_type' => 'Organization');
     if ($this->_contactId) {
         $contactParams['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($this->_contactId);
     }
     CRM_Contact_BAO_Contact::add($contactParams);
     CRM_Core_BAO_Location::create($params, TRUE);
     CRM_Core_BAO_Domain::edit($params, $this->_id);
     //set domain from email address, CRM-3552
     $emailName = '"' . $params['email_name'] . '" <' . $params['email_address'] . '>';
     $emailParams = array('label' => $emailName, 'description' => $params['description'], 'is_active' => 1, 'is_default' => 1);
     $groupParams = array('name' => 'from_email_address');
     //get the option value wt.
     if ($this->_fromEmailId) {
         $action = $this->_action;
         $emailParams['weight'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_fromEmailId, 'weight');
     } else {
         //add from email address.
         $action = CRM_Core_Action::ADD;
         $grpId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'from_email_address', 'id', 'name');
         $fieldValues = array('option_group_id' => $grpId);
         $emailParams['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
     }
     //reset default within domain.
     $emailParams['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
     CRM_Core_OptionValue::addOptionValue($emailParams, $groupParams, $action, $this->_fromEmailId);
     CRM_Core_Session::setStatus(ts("Domain information for '%1' has been saved.", array(1 => $domain->name)), ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
 }