/**
  * Check method create()
  */
 public function testCreate()
 {
     $firstName = 'Shane';
     $lastName = 'Whatson';
     $params = array('first_name' => $firstName, 'last_name' => $lastName, 'contact_type' => 'Individual');
     $contact = CRM_Contact_BAO_Contact::add($params);
     $price = 100.0;
     $cParams = array('contact_id' => $contact->id, 'total_amount' => $price, 'financial_type_id' => 1, 'is_active' => 1, 'skipLineItem' => 1);
     $defaults = array();
     $contribution = CRM_Contribute_BAO_Contribution::add($cParams, $defaults);
     $lParams = array('entity_id' => $contribution->id, 'entity_table' => 'civicrm_contribution', 'price_field_id' => 1, 'qty' => 1, 'label' => 'Contribution Amount', 'unit_price' => $price, 'line_total' => $price, 'price_field_value_id' => 1, 'financial_type_id' => 1);
     $lineItem = CRM_Price_BAO_LineItem::create($lParams);
     $fParams = array('contact_id' => $contact->id, 'description' => 'Contribution Amount', 'amount' => $price, 'financial_account_id' => 1, 'status_id' => 1, 'transaction_date' => date('YmdHis'), 'entity_id' => $lineItem->id, 'entity_table' => 'civicrm_line_item');
     CRM_Financial_BAO_FinancialItem::create($fParams);
     $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
     $entityTrxn->entity_table = 'civicrm_contribution';
     $entityTrxn->entity_id = $contribution->id;
     $entityTrxn->amount = $price;
     if ($entityTrxn->find(TRUE)) {
         $entityId = $entityTrxn->entity_id;
     }
     $result = $this->assertDBNotNull('CRM_Financial_DAO_FinancialItem', $lineItem->id, 'amount', 'entity_id', 'Database check on added financial item record.');
     $this->assertEquals($result, $price, 'Verify Amount for Financial Item');
     $entityResult = $this->assertDBNotNull('CRM_Financial_DAO_EntityFinancialTrxn', $entityId, 'amount', 'entity_id', 'Database check on added entity financial trxn record.');
     $this->assertEquals($entityResult, $price, 'Verify Amount for Financial Item');
 }
Example #2
0
 function testFindReferences()
 {
     $params = array('first_name' => 'Testy', 'last_name' => 'McScallion', 'contact_type' => 'Individual');
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertNotNull($contact->id);
     $params = array('email' => '*****@*****.**', 'contact_id' => $contact->id, 'is_primary' => 0, 'location_type_id' => 1);
     $email = CRM_Core_BAO_Email::add($params);
     $refs = $contact->findReferences();
     $refsByTable = array();
     foreach ($refs as $refObj) {
         $refsByTable[$refObj->__table] = $refObj;
     }
     $this->assertTrue(array_key_exists('civicrm_email', $refsByTable));
     $refDao = $refsByTable['civicrm_email'];
     $refDao->find(TRUE);
     $this->assertEquals($contact->id, $refDao->contact_id);
 }
 /**
  * Method processAction to execute the action
  *
  * @param CRM_Civirules_EventData_EventData $eventData
  * @access public
  *
  */
 public function processAction(CRM_Civirules_EventData_EventData $eventData)
 {
     $contactId = $eventData->getContactId();
     $subTypes = CRM_Contact_BAO_Contact::getContactSubType($contactId);
     $contactType = CRM_Contact_BAO_Contact::getContactType($contactId);
     $changed = false;
     $action_params = $this->getActionParameters();
     foreach ($action_params['sub_type'] as $sub_type) {
         if (CRM_Contact_BAO_ContactType::isExtendsContactType($sub_type, $contactType)) {
             $subTypes[] = $sub_type;
             $changed = true;
         }
     }
     if ($changed) {
         $params['id'] = $contactId;
         $params['contact_id'] = $contactId;
         $params['contact_type'] = $contactType;
         $params['contact_sub_type'] = $subTypes;
         CRM_Contact_BAO_Contact::add($params);
     }
 }
Example #4
0
 /**
  * Ensure that created_date and modified_date are set.
  */
 public function testTimestampContact()
 {
     $test = $this;
     $this->_testTimestamps(array('UPDATE' => function ($contactId) use($test) {
         $params = array('first_name' => 'Testing', 'contact_type' => 'Individual', 'contact_id' => $contactId);
         $contact = CRM_Contact_BAO_Contact::add($params);
         $test->assertInstanceOf('CRM_Contact_DAO_Contact', $contact, 'Check for created object');
     }));
 }
 /**
  * Display sort name during.
  * Update multiple contributions
  * sortName();
  */
 public function testsortName()
 {
     $params = array('first_name' => 'Shane', 'last_name' => 'Whatson', 'contact_type' => 'Individual');
     $contact = CRM_Contact_BAO_Contact::add($params);
     //Now check $contact is object of contact DAO..
     $this->assertInstanceOf('CRM_Contact_DAO_Contact', $contact, 'Check for created object');
     $contactId = $contact->id;
     $ids = array('contribution' => NULL);
     $param = array('contact_id' => $contactId, 'currency' => 'USD', 'financial_type_id' => 1, 'contribution_status_id' => 1, 'payment_instrument_id' => 1, 'source' => 'STUDENT', 'receive_date' => '20080522000000', 'receipt_date' => '20080522000000', 'id' => NULL, 'non_deductible_amount' => 0.0, 'total_amount' => 300.0, 'fee_amount' => 5, 'net_amount' => 295, 'trxn_id' => '22ereerwww323', 'invoice_id' => '22ed39c9e9ee621ce0eafe6da70', 'thankyou_date' => '20080522');
     $contribution = CRM_Contribute_BAO_Contribution::create($param, $ids);
     $this->assertEquals($param['trxn_id'], $contribution->trxn_id, 'Check for transcation id creation.');
     $this->assertEquals($contactId, $contribution->contact_id, 'Check for contact id  creation.');
     //display sort name during Update multiple contributions
     $sortName = CRM_Contribute_BAO_Contribution::sortName($contribution->id);
     $this->assertEquals('Whatson, Shane', $sortName, 'Check for sort name.');
     //Delete Contribution
     $this->contributionDelete($contribution->id);
     //Delete Contact
     Contact::delete($contactId);
 }
 function testDetermineMailchimpEmailForContact()
 {
     $params = array('first_name' => 'MCFirst', 'last_name' => 'MCLast', 'contact_type' => 'Individual', 'do_not_email' => TRUE);
     $initial_contact = CRM_Contact_BAO_Contact::add($params);
     $primary_email = new CRM_Core_BAO_Email();
     $primary_email->contact_id = $initial_contact->id;
     $primary_email->email = '*****@*****.**';
     $primary_email->is_primary = TRUE;
     $primary_email->save();
     $bulk_email = new CRM_Core_BAO_Email();
     $bulk_email->contact_id = $initial_contact->id;
     $bulk_email->email = '*****@*****.**';
     $bulk_email->is_bulkmail = TRUE;
     $bulk_email->save();
     $contact = CRM_CiviMailchimp_Utils::getContactById($initial_contact->id);
     // Test that a contact with do_not_mail does not return an email address.
     $mailchimp_email = CRM_CiviMailchimp_Utils::determineMailchimpEmailForContact($contact);
     $this->assertNull($mailchimp_email);
     // Test that a contact with is_opt_out does not return an email address.
     $contact->do_not_email = FALSE;
     $contact->is_opt_out = TRUE;
     $contact->save();
     $mailchimp_email = CRM_CiviMailchimp_Utils::determineMailchimpEmailForContact($contact);
     $this->assertNull($mailchimp_email);
     // Test that a is_bulkmail email is returned rather than an is_primary one.
     $contact->is_opt_out = FALSE;
     $contact->save();
     $mailchimp_email = CRM_CiviMailchimp_Utils::determineMailchimpEmailForContact($contact);
     $this->assertEquals($bulk_email->email, $mailchimp_email);
     // Test that is_primary email is returned if no is_bulkmail email exists.
     $bulk_email->is_bulkmail = FALSE;
     $bulk_email->save();
     $contact = CRM_CiviMailchimp_Utils::getContactById($initial_contact->id);
     $mailchimp_email = CRM_CiviMailchimp_Utils::determineMailchimpEmailForContact($contact);
     $this->assertEquals($primary_email->email, $mailchimp_email);
     // Test that is_primary email marked on_hold with no is_bulkmail email
     // does not return an email address.
     $primary_email->on_hold = TRUE;
     $primary_email->save();
     $contact = CRM_CiviMailchimp_Utils::getContactById($initial_contact->id);
     $mailchimp_email = CRM_CiviMailchimp_Utils::determineMailchimpEmailForContact($contact);
     $this->assertNull($mailchimp_email);
 }
    /**
     * @return array
     */
    public function createDomainContacts()
    {
        $domainParams = $context = array();
        $query = "\nALTER TABLE civicrm_domain ADD contact_id INT( 10 ) UNSIGNED NULL DEFAULT NULL COMMENT 'FK to Contact ID. This is specifically not an FK to avoid circular constraints',\n ADD CONSTRAINT FK_civicrm_domain_contact_id FOREIGN KEY (contact_id) REFERENCES civicrm_contact(id);";
        CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
        $query = '
SELECT cd.id, cd.name, ce.email FROM civicrm_domain cd
LEFT JOIN civicrm_loc_block clb ON clb.id = cd. loc_block_id
LEFT JOIN civicrm_email ce ON ce.id = clb.email_id ;
';
        $dao = CRM_Core_DAO::executeQuery($query);
        while ($dao->fetch()) {
            $query = "\nSELECT    cc.id FROM civicrm_contact cc\nLEFT JOIN civicrm_email ce ON ce.contact_id = cc.id\nWHERE     cc.contact_type = 'Organization' AND cc.organization_name = %1\n";
            $params = array(1 => array($dao->name, 'String'));
            if ($dao->email) {
                $query .= " AND ce.email = %2 ";
                $params[2] = array($dao->email, 'String');
            }
            $contactID = CRM_Core_DAO::singleValueQuery($query, $params);
            $context[1] = $dao->name;
            if (empty($contactID)) {
                $params = array('sort_name' => $dao->name, 'display_name' => $dao->name, 'legal_name' => $dao->name, 'organization_name' => $dao->name, 'contact_type' => 'Organization');
                $contact = CRM_Contact_BAO_Contact::add($params);
                $contactID = $contact->id;
                $context[0] = 'added';
            } else {
                $context[0] = 'merged';
            }
            $domainParams['contact_id'] = $contactID;
            CRM_Core_BAO_Domain::edit($domainParams, $dao->id);
        }
        return $context;
    }
Example #8
0
 /**
  * Create Current employer relationship for a individual
  *
  * @param int    $contactID        contact id of the individual
  * @param string $organization     it can be name or id of organization
  * 
  * @access public
  * @static
  */
 static function createCurrentEmployerRelationship($contactID, $organization)
 {
     require_once 'CRM/Contact/BAO/Relationship.php';
     $organizationId = null;
     // if organization id is passed.
     if (is_numeric($organization)) {
         $organizationId = $organization;
     } else {
         $orgName = explode('::', $organization);
         trim($orgName[0]);
         $organizationParams = array();
         $organizationParams['organization_name'] = $orgName[0];
         require_once 'CRM/Dedupe/Finder.php';
         $dedupeParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
         $dedupeParams['check_permission'] = false;
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Fuzzy');
         if (is_array($dupeIDs) && !empty($dupeIDs)) {
             // we should create relationship only w/ first org CRM-4193
             foreach ($dupeIDs as $orgId) {
                 $organizationId = $orgId;
                 break;
             }
         } else {
             //create new organization
             $newOrg = array('contact_type' => 'Organization', 'organization_name' => trim($orgName[0]));
             $org = CRM_Contact_BAO_Contact::add($newOrg);
             $organizationId = $org->id;
         }
     }
     if ($organizationId) {
         $cid = array('contact' => $contactID);
         // get the relationship type id of "Employee of"
         $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
         if (!$relTypeId) {
             CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
         }
         // create employee of relationship
         $relationshipParams = array('is_active' => true, 'relationship_type_id' => $relTypeId . '_a_b', 'contact_check' => array($organizationId => true));
         list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationshipParams, $cid);
         // In case we change employer, clean prveovious employer related records.
         $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
         if ($previousEmployerID && $previousEmployerID != $organizationId) {
             self::clearCurrentEmployer($contactID, $previousEmployerID);
         }
         // set current employer
         self::setCurrentEmployer(array($contactID => $organizationId));
         // handle related meberships. CRM-3792
         self::currentEmployerRelatedMembership($contactID, $organizationId, $relationshipParams, $duplicate);
     }
 }
Example #9
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'));
 }
Example #10
0
 /**
  * Update the contact with subtype to another valid subtype.
  * success expected
  */
 public function testUpdateContactSubtype()
 {
     $params = array('first_name' => 'Anne', 'last_name' => 'Grant', 'contact_type' => 'Individual', 'contact_sub_type' => $this->student);
     try {
         $contact = CRM_Contact_BAO_Contact::add($params);
     } catch (Exception $expected) {
     }
     $updateParams = array('contact_sub_type' => $this->parent, 'contact_type' => 'Individual', 'contact_id' => $contact->id);
     try {
         $updatedContact = CRM_Contact_BAO_Contact::add($updateParams);
     } catch (Exception $expected) {
     }
     $this->assertEquals($updatedContact->id, $contact->id);
     $this->assertEquals($updatedContact->contact_type, 'Individual');
     $this->assertEquals(str_replace(CRM_Core_DAO::VALUE_SEPARATOR, '', $updatedContact->contact_sub_type), $this->parent);
     CRM_Contact_BAO_Contact::deleteContact($contact->id);
     $params = array('organization_name' => 'Compumentor', 'contact_type' => 'Organization', 'contact_sub_type' => $this->sponsor);
     try {
         $contact = CRM_Contact_BAO_Contact::add($params);
     } catch (Exception $expected) {
     }
     $updateParams = array('contact_sub_type' => $this->team, 'contact_type' => 'Organization', 'contact_id' => $contact->id);
     try {
         $updatedContact = CRM_Contact_BAO_Contact::add($updateParams);
     } catch (Exception $expected) {
     }
     $this->assertEquals($updatedContact->id, $contact->id);
     $this->assertEquals($updatedContact->contact_type, 'Organization');
     $this->assertEquals(str_replace(CRM_Core_DAO::VALUE_SEPARATOR, '', $updatedContact->contact_sub_type), $this->team);
     CRM_Contact_BAO_Contact::deleteContact($contact->id);
     $params = array('first_name' => 'Anne', 'last_name' => 'Grant', 'contact_type' => 'Individual', 'contact_sub_type' => $this->student);
     try {
         $contact = CRM_Contact_BAO_Contact::add($params);
     } catch (Exception $expected) {
     }
     $updateParams = array('contact_sub_type' => NULL, 'contact_type' => 'Individual', 'contact_id' => $contact->id);
     try {
         $updatedContact = CRM_Contact_BAO_Contact::add($updateParams);
     } catch (Exception $expected) {
     }
     $this->assertEquals($updatedContact->id, $contact->id);
     $this->assertEquals($updatedContact->contact_type, 'Individual');
     $this->assertEquals($updatedContact->contact_sub_type, 'null');
     CRM_Contact_BAO_Contact::deleteContact($contact->id);
 }
Example #11
0
 public function testFindById()
 {
     $params = $this->sampleContact('Individual', 4);
     $existing_contact = CRM_Contact_BAO_Contact::add($params);
     $contact = CRM_Contact_BAO_Contact::findById($existing_contact->id);
     $this->assertEquals($existing_contact->id, $contact->id);
     $deleted_contact_id = $existing_contact->id;
     CRM_Contact_BAO_Contact::deleteContact($contact->id, FALSE, TRUE);
     $exception_thrown = FALSE;
     try {
         $deleted_contact = CRM_Contact_BAO_Contact::findById($deleted_contact_id);
     } catch (Exception $e) {
         $exception_thrown = TRUE;
     }
     $this->assertTrue($exception_thrown);
 }
Example #12
0
 /**
  * test case for add( )
  * test with All contact types.
  */
 function testAddWithAllContactTypes()
 {
     $firstName = 'Bill';
     $lastName = 'Adams';
     $params = array('first_name' => $firstName, 'last_name' => $lastName, 'contact_type' => 'Individual');
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertEquals($firstName, $contact->first_name, 'Check for first name creation.');
     $this->assertEquals($lastName, $contact->last_name, 'Check for last name creation.');
     $contactId = $contact->id;
     //update and change first name and last name, using create()
     $firstName = 'Joan';
     $params = array('first_name' => $firstName, 'contact_type' => 'Individual', 'contact_id' => $contactId);
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertEquals($firstName, $contact->first_name, 'Check for updated first name.');
     $contactId = $contact->id;
     Contact::delete($contactId);
     $householdName = 'Adams house';
     $params = array('household_name' => $householdName, 'contact_type' => 'Household');
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertEquals($householdName, $contact->sort_name, 'Check for created household.');
     $contactId = $contact->id;
     //update and change name of household, using create
     $householdName = 'Joans home';
     $params = array('household_name' => $householdName, 'contact_type' => 'Household', 'contact_id' => $contactId);
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertEquals($householdName, $contact->sort_name, 'Check for updated household.');
     Contact::delete($contactId);
     $organizationName = 'My Organization';
     $params = array('organization_name' => $organizationName, 'contact_type' => 'Organization');
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertEquals($organizationName, $contact->sort_name, 'Check for created organization.');
     $contactId = $contact->id;
     //update and change name of organization, using create
     $organizationName = 'Your Changed Organization';
     $params = array('organization_name' => $organizationName, 'contact_type' => 'Organization', 'contact_id' => $contactId);
     $contact = CRM_Contact_BAO_Contact::add($params);
     $this->assertEquals($organizationName, $contact->sort_name, 'Check for updated organization.');
     Contact::delete($contactId);
 }
Example #13
0
 /**
  * Unit test to ensure that removing any subtype from CustomGroup's
  * extend_for setting, won't delete any custom data of contact
  *
  * Success expected
  */
 public function testCRM19133()
 {
     $customGroupName = md5(microtime());
     $subtypesToPreserve = array($this->student, $this->parent);
     // Create custom group that extends student and parent subtype
     $apiParams = array('title' => $customGroupName, 'extends' => array('Individual', $subtypesToPreserve), 'is_active' => TRUE);
     $result = civicrm_api3('customGroup', 'create', $apiParams);
     $customGroupId = $result['id'];
     // Create desired custom field
     $apiParams = array('debug' => 1, 'custom_group_id' => $result['id'], 'label' => $customGroupName, 'html_type' => 'Text', 'data_type' => 'String', 'is_active' => TRUE);
     $result = civicrm_api3('custom_field', 'create', $apiParams);
     $customFieldId = $result['id'];
     // Create contact of subtype parent and student
     $params = array('first_name' => 'Anne', 'last_name' => 'Grant', 'contact_type' => 'Individual', 'contact_sub_type' => array($this->student, $this->parent));
     $contact = CRM_Contact_BAO_Contact::add($params);
     // Record custom value for desired customGroup
     $this->callAPISuccess('CustomValue', 'create', array('entity_id' => $contact->id, 'custom_' . $customFieldId => 'value 1'));
     // Subtype to be removed from customGroup setting
     $subtypesToBeRemoved = array($this->student);
     CRM_Contact_BAO_ContactType::deleteCustomRowsOfSubtype($customGroupId, $subtypesToBeRemoved, $subtypesToPreserve);
     // Check with correct value to assert that custom data is not deleted
     $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customFieldId => 'value 1'));
     $this->assertEquals(1, $result['count']);
     $this->assertEquals($contact->id, $result['id']);
     //Check with incorrect custom value that our previous assertion was correct
     $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customFieldId => 'wrong value'));
     $this->assertEquals(0, $result['count']);
 }
 static function processNormalization($fromContactId, $toContactId)
 {
     $processInfo = array('name' => 0, 'phone' => 0, 'address' => 0);
     if (empty($fromContactId) || empty($toContactId)) {
         return $processInfo;
     }
     $contactIds = range($fromContactId, $toContactId);
     $normalization = CRM_Utils_Normalize::singleton();
     $formattedContactIds = $formattedPhoneIds = $formattedAddressIds = array();
     foreach ($contactIds as $contactId) {
         $contact = new CRM_Contact_DAO_Contact();
         $contact->id = $contactId;
         if ($contact->find()) {
             $params = array('id' => $contactId, 'contact_id' => $contactId);
             $orgContactValues = array();
             CRM_Contact_BAO_Contact::retrieve($params, $orgContactValues);
             //update contacts name fields.
             $formatNameValues = array();
             foreach ($normalization->getNameFields() as $field) {
                 $nameValue = CRM_Utils_Array::value($field, $orgContactValues);
                 if (empty($nameValue)) {
                     continue;
                 }
                 $formatNameValues[$field] = $nameValue;
             }
             if (!empty($formatNameValues)) {
                 $formatNameValues['contact_type'] = $orgContactValues['contact_type'];
                 $formattedNameValues = $formatNameValues;
                 //format name values
                 $normalization->normalize_contact($formattedNameValues);
                 //check formatted diff, only update if there is difference.
                 $formatDiff = array_diff($formatNameValues, $formattedNameValues);
                 if (!empty($formatDiff)) {
                     $formattedNameValues['id'] = $formattedNameValues['contact_id'] = $orgContactValues['id'];
                     $formattedNameValues['contact_type'] = $orgContactValues['contact_type'];
                     $contactUpdated = CRM_Contact_BAO_Contact::add($formattedNameValues);
                     if ($contactUpdated->id) {
                         $formattedContactIds[$contactUpdated->id] = $contactUpdated->id;
                     }
                     $contactUpdated->free();
                 }
             }
             //update phone fields.
             if (isset($orgContactValues['phone']) && is_array($orgContactValues['phone'])) {
                 foreach ($orgContactValues['phone'] as $cnt => $orgPhoneValues) {
                     if (!isset($orgPhoneValues['id']) || empty($orgPhoneValues['id']) || empty($orgPhoneValues['phone'])) {
                         continue;
                     }
                     $formattedPhoneValues = $orgPhoneValues;
                     //format phone fields
                     $normalization->normalize_phone($formattedPhoneValues);
                     //do check for formatted difference, than only update.
                     $formattedDiff = array_diff_assoc($orgPhoneValues, $formattedPhoneValues);
                     if (!empty($formattedDiff)) {
                         $phoneUpdated = CRM_Core_BAO_Phone::add($formattedPhoneValues);
                         if ($phoneUpdated->id) {
                             $formattedPhoneIds[$phoneUpdated->id] = $phoneUpdated->id;
                         }
                         $phoneUpdated->free();
                     }
                 }
             }
             //update address.
             if (isset($orgContactValues['address']) && is_array($orgContactValues['address'])) {
                 foreach ($orgContactValues['address'] as $cnt => $orgAddressValues) {
                     if (!isset($orgAddressValues['id']) || empty($orgAddressValues['id'])) {
                         continue;
                     }
                     $formattedAddressValues = $orgAddressValues;
                     //format addrees fields
                     $normalization->normalize_address($formattedAddressValues);
                     //do check for formatted difference, than only update.
                     $formattedDiff = array_diff($orgAddressValues, $formattedAddressValues);
                     if (!empty($formattedDiff)) {
                         $addressUpdated = CRM_Core_BAO_Address::add($formattedAddressValues, FALSE);
                         if ($addressUpdated->id) {
                             $formattedAddressIds[$addressUpdated->id] = $addressUpdated->id;
                         }
                         $addressUpdated->free();
                     }
                 }
             }
         }
         $contact->free();
     }
     $processInfo = array('name' => $formattedContactIds, 'phone' => $formattedPhoneIds, 'address' => $formattedAddressIds);
     return $processInfo;
 }
Example #15
0
 /** 
  * takes an associative array and creates a contact object and all the associated 
  * derived objects (i.e. individual, location, email, phone etc) 
  * 
  * This function is invoked from within the web form layer and also from the api layer
  * primarily from the profile / contribute forms where we dont have a nice hierarchy
  * and are too lazy to create one. This function should be obsoleted at some time
  * 
  * @param array $params (reference ) an assoc array of name/value pairs 
  * @param array $ids    the array that holds all the db ids 
  * 
  * @return object CRM_Contact_BAO_Contact object  
  * @access public 
  * @static 
  */
 function &createFlat(&$params, &$ids)
 {
     require_once 'CRM/Utils/Hook.php';
     if (CRM_Utils_Array::value('contact', $ids)) {
         CRM_Utils_Hook::pre('edit', 'Individual', $ids['contact'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Individual', null, $params);
     }
     CRM_Core_DAO::transaction('BEGIN');
     $params['contact_type'] = 'Individual';
     $contact = CRM_Contact_BAO_Contact::add($params, $ids);
     $params['contact_id'] = $contact->id;
     require_once 'CRM/Contact/BAO/Individual.php';
     CRM_Contact_BAO_Individual::add($params, $ids);
     require_once 'CRM/Core/BAO/LocationType.php';
     $locationType =& CRM_Core_BAO_LocationType::getDefault();
     $locationTypeId = $locationType->id;
     $locationIds = CRM_Utils_Array::value('location', $ids);
     // extract the first location id
     if ($locationIds) {
         foreach ($locationIds as $dontCare => $locationId) {
             $locationIds = $locationId;
             break;
         }
     }
     $location =& new CRM_Core_DAO_Location();
     $location->location_type_id = $locationTypeId;
     $location->entity_table = 'civicrm_contact';
     $location->entity_id = $contact->id;
     $location->id = CRM_Utils_Array::value('id', $locationIds);
     if ($location->find(true)) {
         if (!$location->is_primary) {
             $location->is_primary = true;
         }
     } else {
         $location->is_primary = true;
     }
     $location->save();
     $address =& new CRM_Core_BAO_Address();
     CRM_Core_BAO_Address::fixAddress($params);
     if (!$address->copyValues($params)) {
         $address->id = CRM_Utils_Array::value('address', $locationIds);
         $address->location_id = $location->id;
         $address->save();
     }
     $phone =& new CRM_Core_BAO_Phone();
     if (!$phone->copyValues($params)) {
         $blockIds = CRM_Utils_Array::value('phone', $locationIds);
         $phone->id = CRM_Utils_Array::value(1, $blockIds);
         $phone->location_id = $location->id;
         $phone->is_primary = true;
         $phone->save();
     }
     $email =& new CRM_Core_BAO_Email();
     if (!$email->copyValues($params)) {
         $blockIds = CRM_Utils_Array::value('email', $locationIds);
         $email->id = CRM_Utils_Array::value(1, $blockIds);
         $email->location_id = $location->id;
         $email->is_primary = true;
         $email->save();
     }
     /* Process custom field values and other values */
     foreach ($params as $key => $value) {
         if ($key == 'group') {
             CRM_Contact_BAO_GroupContact::create($params['group'], $contact->id);
         } else {
             if ($key == 'tag') {
                 require_once 'CRM/Core/BAO/EntityTag.php';
                 CRM_Core_BAO_EntityTag::create($params['tag'], $contact->id);
             } else {
                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                     $custom_field_id = $cfID;
                     $cf =& new CRM_Core_BAO_CustomField();
                     $cf->id = $custom_field_id;
                     if ($cf->find(true)) {
                         switch ($cf->html_type) {
                             case 'Select Date':
                                 $date = CRM_Utils_Date::format($value);
                                 if (!$date) {
                                     $date = '';
                                 }
                                 $customValue = $date;
                                 break;
                             case 'CheckBox':
                                 $customValue = implode(CRM_CORE_BAO_CUSTOMOPTION_VALUE_SEPERATOR, array_keys($value));
                                 break;
                                 //added a case for Multi-Select
                             //added a case for Multi-Select
                             case 'Multi-Select':
                                 $customValue = implode(CRM_CORE_BAO_CUSTOMOPTION_VALUE_SEPERATOR, array_keys($value));
                                 break;
                             default:
                                 $customValue = $value;
                         }
                     }
                     CRM_Core_BAO_CustomValue::updateValue($contact->id, $custom_field_id, $customValue);
                 }
             }
         }
     }
     CRM_Core_DAO::transaction('COMMIT');
     if (CRM_Utils_Array::value('contact', $ids)) {
         CRM_Utils_Hook::post('edit', 'Individual', $contact->id, $contact);
     } else {
         CRM_Utils_Hook::post('create', 'Individual', $contact->id, $contact);
     }
     return $contact;
 }