function testFindByContactIdNoSyncSettings()
 {
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     $contact = CRM_Contact_BAO_Contact::create($params);
     $mailchimp_sync_settings = CRM_CiviMailchimp_BAO_SyncSettings::findByContactId($contact->id);
     $this->assertEmpty($mailchimp_sync_settings);
 }
Exemplo n.º 2
0
 /**
  * Helper function to create
  * a contact of type Organisation
  *
  * @param null $params
  * @return mixed $contactID id of created Organisation
  */
 static function createOrganisation($params = NULL)
 {
     //compose the params, when not passed
     if (!$params) {
         $organization_name = "My Organization";
         $params = array('organization_name' => $organization_name, 'contact_type' => 'Organization');
     }
     require_once "CRM/Contact/BAO/Contact.php";
     $organization = CRM_Contact_BAO_Contact::create($params);
     return $organization->id;
 }
Exemplo n.º 3
0
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // Process / save contact info
     $params['contact_type'] = $this->_contactType;
     $params['contact_id'] = $this->_contactId;
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     CRM_Contact_BAO_Contact::create($params);
     $this->response();
 }
 function testForceCiviToMailchimpSyncNullEmail()
 {
     $mailchimp_sync_setting = CRM_CiviMailchimp_BAO_SyncSettingsTest::createTestGroupAndSyncSettings('Test Group testForceCiviToMailchimpSyncNullEmail');
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     unset($params['email']);
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contact_ids = array($contact->id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $mailchimp_sync_setting->civicrm_group_id);
     $contacts = CRM_CiviMailchimp_Form_Sync::forceCiviToMailchimpSync($mailchimp_sync_setting);
     $mailchimp_api_subscribe = civimailchimp_static('mailchimp_api_subscribe');
     $this->assertCount(0, $contacts);
     $this->assertNull($mailchimp_api_subscribe);
 }
Exemplo n.º 5
0
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // Process / save contact info
     $params['contact_type'] = $this->_contactType;
     $params['contact_id'] = $this->_contactId;
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     CRM_Contact_BAO_Contact::create($params);
     // Saving current employer affects relationship tab
     $this->ajaxResponse['updateTabs'] = array('#tab_rel' => CRM_Contact_BAO_Contact::getCountComponent('rel', $this->_contactId));
     $this->response();
 }
Exemplo n.º 6
0
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // Process / save demographics
     if (empty($params['is_deceased'])) {
         $params['is_deceased'] = FALSE;
         $params['deceased_date'] = NULL;
     }
     $params['contact_type'] = 'Individual';
     $params['contact_id'] = $this->_contactId;
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     CRM_Contact_BAO_Contact::create($params);
     $this->response();
 }
Exemplo n.º 7
0
 /**
  * Process the form.
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // Process / save contact info
     $params['contact_type'] = $this->_contactType;
     $params['contact_id'] = $this->_contactId;
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     CRM_Contact_BAO_Contact::create($params);
     // Saving current employer affects relationship tab, and possibly related memberships and contributions
     $this->ajaxResponse['updateTabs'] = array('#tab_rel' => CRM_Contact_BAO_Contact::getCountComponent('rel', $this->_contactId));
     if (CRM_Core_Permission::access('CiviContribute')) {
         $this->ajaxResponse['updateTabs']['#tab_contribute'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
     }
     if (CRM_Core_Permission::access('CiviMember')) {
         $this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId);
     }
     $this->response();
 }
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // need to process / save demographics
     if (!CRM_Utils_Array::value('is_deceased', $params)) {
         $params['is_deceased'] = FALSE;
         $params['deceased_date'] = NULL;
     }
     $params['contact_type'] = 'Individual';
     $params['contact_id'] = $this->_contactId;
     CRM_Contact_BAO_Contact::create($params);
     $response = array('status' => 'save');
     $this->postProcessHook();
     echo json_encode($response);
     CRM_Utils_System::civiExit();
 }
Exemplo n.º 9
0
 /**
  * Use SQL to INSERT a contact and assert success. Perform
  * work within a transaction.
  *
  * @param string $nesting
  *   'reuse-tx'|'nest-tx' how to construct transaction.
  * @param string $insert
  *   'sql-insert'|'bao-create' how to add the example record.
  * @param string $outcome
  *   'rollback'|'implicit-commit'|'explicit-commit' how to finish transaction.
  * @return int
  *   cid
  */
 public function createContactWithTransaction($nesting, $insert, $outcome)
 {
     if ($nesting != 'reuse-tx' && $nesting != 'nest-tx') {
         throw new RuntimeException('Bad test data: reuse=' . $nesting);
     }
     if ($insert != 'sql-insert' && $insert != 'bao-create') {
         throw new RuntimeException('Bad test data: insert=' . $insert);
     }
     if ($outcome != 'rollback' && $outcome != 'implicit-commit' && $outcome != 'explicit-commit') {
         throw new RuntimeException('Bad test data: outcome=' . $outcome);
     }
     $tx = new CRM_Core_Transaction($nesting === 'nest-tx');
     if ($insert == 'sql-insert') {
         $r = CRM_Core_DAO::executeQuery("INSERT INTO civicrm_contact(first_name,last_name) VALUES ('ff', 'll')");
         $cid = mysql_insert_id();
     } elseif ($insert == 'bao-create') {
         $params = array('contact_type' => 'Individual', 'first_name' => 'FF', 'last_name' => 'LL');
         $r = CRM_Contact_BAO_Contact::create($params);
         $cid = $r->id;
     }
     $this->cids[] = $cid;
     $this->assertContactsExist(array($cid), TRUE);
     if ($outcome == 'rollback') {
         $tx->rollback();
     } elseif ($outcome == 'explicit-commit') {
         $tx->commit();
     }
     // else: implicit-commit
     return $cid;
 }
Exemplo n.º 10
0
 /**
  * Form submission of new/edit contact is processed.
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $locType = CRM_Core_BAO_LocationType::getDefault();
     foreach (array('phone', 'email', 'address') as $locFld) {
         if (!empty($this->_defaults[$locFld]) && $this->_defaults[$locFld][1]['location_type_id']) {
             $params[$locFld][1]['is_primary'] = $this->_defaults[$locFld][1]['is_primary'];
             $params[$locFld][1]['location_type_id'] = $this->_defaults[$locFld][1]['location_type_id'];
         } else {
             $params[$locFld][1]['is_primary'] = 1;
             $params[$locFld][1]['location_type_id'] = $locType->id;
         }
     }
     $params['contact_type'] = $this->_contactType;
     $params['contact_id'] = $this->_contactId;
     $contact = CRM_Contact_BAO_Contact::create($params, TRUE);
     // set status message.
     if ($this->_contactId) {
         $message = ts('%1 has been updated.', array(1 => $contact->display_name));
     } else {
         $message = ts('%1 has been created.', array(1 => $contact->display_name));
     }
     CRM_Core_Session::setStatus($message, ts('Contact Saved'), 'success');
 }
 function test_civicrm_api3_civi_mailchimp_sync()
 {
     $action = 'subscribeContactToMailchimpList';
     $mailchimp_list_id = 'MailchimpListsTestListA';
     $mailchimp_interest_groups = array('MailchimpTestInterestGroupingA_MailchimpTestInterestGroupA', 'MailchimpTestInterestGroupingA_MailchimpTestInterestGroupC');
     $mailchimp_sync_setting = CRM_CiviMailchimp_BAO_SyncSettingsTest::createTestGroupAndSyncSettings('Test Group test_civicrm_api3_civi_mailchimp_sync', $mailchimp_list_id, $mailchimp_interest_groups);
     $merge_fields = CRM_CiviMailchimp_Utils::getMailchimpMergeFields();
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     $contact = CRM_Contact_BAO_Contact::create($params);
     $merge_vars = CRM_CiviMailchimp_Utils::formatMailchimpMergeVars($merge_fields, $contact);
     CRM_CiviMailchimp_Utils::addMailchimpSyncQueueItem($action, $mailchimp_list_id, $params['email'][0]['email'], $merge_vars);
     $action = 'unsubscribeContactFromMailchimpList';
     CRM_CiviMailchimp_Utils::addMailchimpSyncQueueItem($action, $mailchimp_list_id, $params['email'][0]['email'], $merge_vars);
     $job_params['records_to_process_per_run'] = 100;
     civicrm_api3_civi_mailchimp_sync($job_params);
     $queue = CRM_Queue_Service::singleton()->create(array('type' => 'Sql', 'name' => 'mailchimp-sync', 'reset' => FALSE));
     $this->assertEquals(0, $queue->numberOfItems());
 }
 function testClearQueueItem()
 {
     $mailchimp_list_id = 'MailchimpListsTestListA';
     $mailchimp_sync_setting = CRM_CiviMailchimp_BAO_SyncSettingsTest::createTestGroupAndSyncSettings('Test Group testClearQueueItem', $mailchimp_list_id);
     $group = CRM_CiviMailchimp_Utils::getGroupById($mailchimp_sync_setting->civicrm_group_id);
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     $contact = CRM_Contact_BAO_Contact::create($params);
     $queue = CRM_Queue_Service::singleton()->create(array('type' => 'Sql', 'name' => 'mailchimp-sync', 'reset' => TRUE));
     civimailchimp_civicrm_contact_removed_from_group($group, $contact);
     $item = $queue->claimItem($lease_time = 0);
     $existing_mailchimp_sync_log = self::createTestLogMessage('This is a test error message', $details = NULL, $direction = 'civicrm_to_mailchimp', $type = 'error', $item->id);
     CRM_CiviMailchimp_BAO_SyncLog::clearQueueItem($item->id);
     $query = "\n      SELECT\n        *\n      FROM\n        civicrm_queue_item\n      WHERE\n        queue_name = 'mailchimp-sync'\n      AND\n        id = %1\n      LIMIT 1\n      ";
     $params = array(1 => array($item->id, 'Integer'));
     $new_item = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Queue_DAO_QueueItem');
     $mailchimp_sync_log = CRM_CiviMailchimp_BAO_SyncLog::findById($existing_mailchimp_sync_log->id);
     $this->assertFalse($new_item->fetch());
     $this->assertNull($mailchimp_sync_log->civicrm_queue_item_id);
 }
Exemplo n.º 13
0
 /**
  * Test case for getDisplayAndImage( ).
  */
 public function testGetDisplayAndImage()
 {
     //get the contact params
     $params = $this->contactParams();
     //create contact
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contactId = $contact->id;
     //get DisplayAndImage.
     list($displayName, $image) = CRM_Contact_BAO_Contact::getDisplayAndImage($contactId);
     $checkImage = CRM_Contact_BAO_Contact_Utils::getImage($params['contact_type'], FALSE, $contactId);
     $prefix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
     $suffix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id');
     //build display name
     $paramsDisplayName = $prefix[$params['prefix_id']] . ' ' . $params['first_name'] . ' ' . $params['last_name'] . ' ' . $suffix[$params['suffix_id']];
     $this->assertEquals($displayName, $paramsDisplayName, 'Check For Display Name');
     $this->assertEquals($image, $checkImage, 'Check For Image');
     //cleanup DB by deleting the contact
     $this->contactDelete($contactId);
 }
Exemplo n.º 14
0
 static function processAPIContribution($params)
 {
     if (empty($params) || array_key_exists('error', $params)) {
         return false;
     }
     // add contact using dedupe rule
     require_once 'CRM/Dedupe/Finder.php';
     $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
     $dedupeParams['check_permission'] = false;
     $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
     // if we find more than one contact, use the first one
     if (CRM_Utils_Array::value(0, $dupeIds)) {
         $params['contact_id'] = $dupeIds[0];
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact = CRM_Contact_BAO_Contact::create($params);
     if (!$contact->id) {
         return false;
     }
     // only pass transaction params to contribution::create, if available
     if (array_key_exists('transaction', $params)) {
         $params = $params['transaction'];
         $params['contact_id'] = $contact->id;
     }
     // handle contribution custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Contribution', false, false, CRM_Utils_Array::value('contribution_type_id', $params));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, CRM_Utils_Array::value('id', $params, null), 'Contribution');
     // create contribution
     // if this is a recurring contribution then process it first
     if ($params['trxn_type'] == 'subscrpayment') {
         // see if a recurring record already exists
         require_once 'CRM/Contribute/BAO/ContributionRecur.php';
         $recurring = new CRM_Contribute_BAO_ContributionRecur();
         $recurring->processor_id = $params['processor_id'];
         if (!$recurring->find(true)) {
             $recurring = new CRM_Contribute_BAO_ContributionRecur();
             $recurring->invoice_id = $params['invoice_id'];
             $recurring->find(true);
         }
         // This is the same thing the CiviCRM IPN handler does to handle
         // subsequent recurring payments to avoid duplicate contribution
         // errors due to invoice ID. See:
         // ./CRM/Core/Payment/PayPalIPN.php:200
         if ($recurring->id) {
             $params['invoice_id'] = md5(uniqid(rand(), true));
         }
         $recurring->copyValues($params);
         $recurring->save();
         if (is_a($recurring, 'CRM_Core_Error')) {
             return false;
         } else {
             $params['contribution_recur_id'] = $recurring->id;
         }
     }
     require_once 'CRM/Contribute/BAO/Contribution.php';
     $contribution =& CRM_Contribute_BAO_Contribution::create($params, CRM_Core_DAO::$_nullArray);
     if (!$contribution->id) {
         return false;
     }
     return true;
 }
Exemplo n.º 15
0
 /**
  * Form submission of new/edit contact is processed.
  */
 public function postProcess()
 {
     // check if dedupe button, if so return.
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->_dedupeButtonName) {
         return;
     }
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $group = CRM_Utils_Array::value('group', $params);
     if (!empty($group) && is_array($group)) {
         unset($params['group']);
         foreach ($group as $key => $value) {
             $params['group'][$value] = 1;
         }
     }
     CRM_Contact_BAO_Contact_Optimizer::edit($params, $this->_preEditValues);
     if (!empty($params['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($params);
     }
     if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
         $params['current_employer'] = $params['current_employer_id'];
     }
     // don't carry current_employer_id field,
     // since we don't want to directly update DAO object without
     // handling related business logic ( eg related membership )
     if (isset($params['current_employer_id'])) {
         unset($params['current_employer_id']);
     }
     $params['contact_type'] = $this->_contactType;
     if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
         $params['contact_sub_type'] = array($this->_contactSubType);
     }
     if ($this->_contactId) {
         $params['contact_id'] = $this->_contactId;
     }
     //make deceased date null when is_deceased = false
     if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) {
         $params['is_deceased'] = FALSE;
         $params['deceased_date'] = NULL;
     }
     if (isset($params['contact_id'])) {
         // process membership status for deceased contact
         $deceasedParams = array('contact_id' => CRM_Utils_Array::value('contact_id', $params), 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE), 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL));
         $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
     }
     // action is taken depending upon the mode
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE);
     //CRM-5143
     //if subtype is set, send subtype as extend to validate subtype customfield
     $customFieldExtends = CRM_Utils_Array::value('contact_sub_type', $params) ? $params['contact_sub_type'] : $params['contact_type'];
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_contactId, $customFieldExtends, TRUE);
     if ($this->_contactId && !empty($this->_oldSubtypes)) {
         CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId, $params['contact_type'], $this->_oldSubtypes, $params['contact_sub_type']);
     }
     if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
         // this is a chekbox, so mark false if we dont get a POST value
         $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
     }
     // process shared contact address.
     CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
     if (!array_key_exists('TagsAndGroups', $this->_editOptions) && !empty($params['group'])) {
         unset($params['group']);
     }
     if (!empty($params['contact_id']) && $this->_action & CRM_Core_Action::UPDATE && !empty($params['group'])) {
         // figure out which all groups are intended to be removed
         $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
         if (is_array($contactGroupList)) {
             foreach ($contactGroupList as $key) {
                 if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
                     $params['group'][$key['group_id']] = -1;
                 }
             }
         }
     }
     // parse street address, CRM-5450
     $parseStatusMsg = NULL;
     if ($this->_parseStreetAddress) {
         $parseResult = self::parseAddress($params);
         $parseStatusMsg = self::parseAddressStatusMsg($parseResult);
     }
     // Allow un-setting of location info, CRM-5969
     $params['updateBlankLocInfo'] = TRUE;
     $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE);
     // status message
     if ($this->_contactId) {
         $message = ts('%1 has been updated.', array(1 => $contact->display_name));
     } else {
         $message = ts('%1 has been created.', array(1 => $contact->display_name));
     }
     // set the contact ID
     $this->_contactId = $contact->id;
     if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
         //add contact to tags
         CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']);
         //save free tags
         if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
             CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
         }
     }
     if (!empty($parseStatusMsg)) {
         $message .= "<br />{$parseStatusMsg}";
     }
     if (!empty($updateMembershipMsg)) {
         $message .= "<br />{$updateMembershipMsg}";
     }
     $session = CRM_Core_Session::singleton();
     $session->setStatus($message, ts('Contact Saved'), 'success');
     // add the recently viewed contact
     $recentOther = array();
     if ($session->get('userID') == $contact->id || CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id);
     }
     if ($session->get('userID') != $this->_contactId && CRM_Core_Permission::check('delete contacts')) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id);
     }
     CRM_Utils_Recent::add($contact->display_name, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $contact->display_name, $recentOther);
     // here we replace the user context with the url to view this contact
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->getButtonName('upload', 'new')) {
         $contactSubTypes = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_contactSubType));
         $resetStr = "reset=1&ct={$contact->contact_type}";
         $resetStr .= count($contactSubTypes) == 1 ? "&cst=" . array_pop($contactSubTypes) : '';
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
     } else {
         $context = CRM_Utils_Request::retrieve('context', 'String', $this);
         $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
         //validate the qfKey
         $urlParams = 'reset=1&cid=' . $contact->id;
         if ($context) {
             $urlParams .= "&context={$context}";
         }
         if (CRM_Utils_Rule::qfKey($qfKey)) {
             $urlParams .= "&key={$qfKey}";
         }
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
     }
     // now invoke the post hook
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
     } else {
         CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
     }
 }
Exemplo n.º 16
0
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // Process / save communication preferences
     // this is a chekbox, so mark false if we dont get a POST value
     $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
     $params['contact_type'] = $this->_contactType;
     $params['contact_id'] = $this->_contactId;
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     CRM_Contact_BAO_Contact::create($params);
     $this->response();
 }
Exemplo n.º 17
0
function &crm_create_contact_formatted(&$params, $onDuplicate)
{
    _crm_initialize();
    // return error if we have no params
    if (empty($params)) {
        return _crm_error('Input Parameters empty');
    }
    $error = _crm_required_formatted_contact($params);
    if (is_a($error, 'CRM_Core_Error')) {
        return $error;
    }
    $error = _crm_validate_formatted_contact($params);
    if (is_a($error, 'CRM_Core_Error')) {
        return $error;
    }
    require_once 'CRM/Import/Parser.php';
    if ($onDuplicate != CRM_IMPORT_PARSER_DUPLICATE_NOCHECK) {
        $error = _crm_duplicate_formatted_contact($params);
        if (is_a($error, 'CRM_Core_Error')) {
            return $error;
        }
    }
    $ids = array();
    CRM_Contact_BAO_Contact::resolveDefaults($params, true);
    $contact = CRM_Contact_BAO_Contact::create($params, $ids, count($params['location']));
    return $contact;
}
Exemplo n.º 18
0
 /**
  * Function to add on behalf of organization and it's location  
  *
  * @param $behalfOrganization array  array of organization info
  * @param $values             array  form values array
  * @param $contactID          int    individual contact id. One
  * who is doing the process of signup / contribution. 
  *
  * @return void
  * @access public
  */
 static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params)
 {
     $isCurrentEmployer = false;
     if ($behalfOrganization['organization_id'] && $behalfOrganization['org_option']) {
         $orgID = $behalfOrganization['organization_id'];
         unset($behalfOrganization['organization_id']);
         $isCurrentEmployer = true;
     }
     // formalities for creating / editing organization.
     require_once "CRM/Core/BAO/LocationType.php";
     $locType = CRM_Core_BAO_LocationType::getDefault();
     $behalfOrganization['contact_type'] = 'Organization';
     foreach (array('phone', 'email', 'address') as $locFld) {
         $behalfOrganization[$locFld][1]['is_primary'] = 1;
         $behalfOrganization[$locFld][1]['location_type_id'] = $locType->id;
     }
     // get the relationship type id
     require_once "CRM/Contact/DAO/RelationshipType.php";
     $relType =& new CRM_Contact_DAO_RelationshipType();
     $relType->name_a_b = "Employee of";
     $relType->find(true);
     $relTypeId = $relType->id;
     // keep relationship params ready
     $relParams['relationship_type_id'] = $relTypeId . '_a_b';
     $relParams['is_permission_a_b'] = 1;
     $relParams['is_active'] = 1;
     if (!$orgID) {
         // check if matching organization contact exists
         require_once 'CRM/Dedupe/Finder.php';
         $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Strict');
         if (count($dupeIDs) == 1) {
             $behalfOrganization['contact_id'] = $dupeIDs[0];
             // don't allow name edit
             unset($behalfOrganization['organization_name']);
         }
     } else {
         // if found permissioned related organization, allow location edit
         $behalfOrganization['contact_id'] = $orgID;
         // don't allow name edit
         unset($behalfOrganization['organization_name']);
     }
     // create organization, add location
     $org = CRM_Contact_BAO_Contact::create($behalfOrganization);
     // create relationship
     $relParams['contact_check'][$org->id] = 1;
     $cid = array('contact' => $contactID);
     $relationship = CRM_Contact_BAO_Relationship::create($relParams, $cid);
     // take a note of new/updated organiation contact-id.
     $orgID = $org->id;
     // if multiple match - send a duplicate alert
     if ($dupeIDs && count($dupeIDs) > 1) {
         $values['onbehalf_dupe_alert'] = 1;
         // required for IPN
         $params['onbehalf_dupe_alert'] = 1;
     }
     // make sure organization-contact-id is considered for recording
     // contribution/membership etc..
     if ($contactID != $orgID) {
         // take a note of contact-id, so we can send the
         // receipt to individual contact as well.
         // required for mailing/template display ..etc
         $values['related_contact'] = $contactID;
         // required for IPN
         $params['related_contact'] = $contactID;
         //make this employee of relationship as current
         //employer / employee relationship,  CRM-3532
         if ($isCurrentEmployer && $orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id')) {
             $isCurrentEmployer = false;
         }
         if (!$isCurrentEmployer && $orgID) {
             //build current employer params
             $currentEmpParams[$contactID] = $orgID;
             require_once 'CRM/Contact/BAO/Contact/Utils.php';
             CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
         }
         // contribution / signup will be done using this
         // organization id.
         $contactID = $orgID;
     }
 }
Exemplo n.º 19
0
 /**
  * Function to create a new shared household (used if create-new-household options is checked).
  *
  * @param array $params  the input form values
  *
  * @return void
  * @access public
  * @static
  */
 static function createSharedHousehold(&$params)
 {
     $houseHoldId = null;
     // if household id is passed.
     if (is_numeric($params['shared_household'])) {
         $houseHoldId = $params['shared_household'];
     } else {
         $householdParams = array();
         $householdParams['address']['1'] = $params['address']['1'];
         $householdParams['household_name'] = $params['shared_household'];
         require_once 'CRM/Dedupe/Finder.php';
         $dedupeParams = CRM_Dedupe_Finder::formatParams($householdParams, 'Household');
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Household', 'Fuzzy');
         if (empty($dupeIDs)) {
             //create new Household
             $newHousehold = array('contact_type' => 'Household', 'household_name' => $params['shared_household'], 'address' => $householdParams['address']);
             $houseHold = CRM_Contact_BAO_Contact::create($newHousehold);
             $houseHoldId = $houseHold->id;
         } else {
             $houseHoldId = $dupeIDs[0];
         }
     }
     if ($houseHoldId) {
         $params['mail_to_household_id'] = $houseHoldId;
         return true;
     }
     return false;
 }
 /**
  * Test in which an outer function ($transactionalFunction_outermost) makes multiple calls
  * to inner functions ($transactionalFunction_inner) but then rollsback the entire set.
  */
 function testRollback_BaoCreate_2xInner()
 {
     $cids = array();
     $test = $this;
     $transactionalFunction_inner = function () use(&$cids, $test) {
         $tx = new CRM_Core_Transaction();
         $params = array('contact_type' => 'Individual', 'first_name' => 'F', 'last_name' => 'L');
         $r = CRM_Contact_BAO_Contact::create($params);
         $cid = $r->id;
         $cids[] = $cid;
         $test->assertContactsExist($cids, TRUE);
         // end of inner $tx; neither COMMIT nor ROLLBACK b/c it's inner
     };
     $transactionalFunction_outermost = function () use(&$cids, $test, $transactionalFunction_inner) {
         $tx = new CRM_Core_Transaction();
         $transactionalFunction_inner();
         $transactionalFunction_inner();
         $tx->rollback();
         // Mark ROLLBACK, but don't execute yet
         $test->assertContactsExist($cids, TRUE);
         // not yet rolled back
         // End of outermost $tx; ROLLBACK will execute ASAP
     };
     $transactionalFunction_outermost();
     // No outstanding $tx -- ROLLBACK should be done
     $test->assertContactsExist($cids, FALSE);
 }
Exemplo n.º 21
0
 /**
  * Form submission of new/edit contact is processed.
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     require_once "CRM/Core/BAO/LocationType.php";
     $locType = CRM_Core_BAO_LocationType::getDefault();
     foreach (array('phone', 'email', 'address') as $locFld) {
         if (!empty($this->_defaults[$locFld]) && $this->_defaults[$locFld][1]['location_type_id']) {
             $params[$locFld][1]['is_primary'] = $this->_defaults[$locFld][1]['is_primary'];
             $params[$locFld][1]['location_type_id'] = $this->_defaults[$locFld][1]['location_type_id'];
         } else {
             $params[$locFld][1]['is_primary'] = 1;
             $params[$locFld][1]['location_type_id'] = $locType->id;
         }
     }
     $params['contact_type'] = $this->_contactType;
     $params['contact_id'] = $this->_contactId;
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact =& CRM_Contact_BAO_Contact::create($params, true, false);
     if ($this->_contactType == 'Household' && $this->_action & CRM_Core_Action::UPDATE) {
         require_once 'CRM/Contact/Form/Household.php';
         CRM_Contact_Form_Household::synchronizeIndividualAddresses($contact->id);
     }
     // set status message.
     CRM_Core_Session::setStatus(ts('Your %1 contact record has been saved.', array(1 => $contact->contact_type_display)));
 }
Exemplo n.º 22
0
 /**
  * Form rule to send out a test mailing.
  *
  * @param aray $testParams
  * @param array $files
  *   Any files posted to the form.
  * @param array $self
  *   An current this object.
  *
  * @return bool
  *   true on successful SMTP handoff
  */
 public static function testMail($testParams, $files, $self)
 {
     $error = NULL;
     $urlString = 'civicrm/mailing/send';
     $urlParams = "_qf_Test_display=true&qfKey={$testParams['qfKey']}";
     $ssID = $self->get('ssID');
     if ($ssID && $self->_searchBasedMailing) {
         if ($self->_action == CRM_Core_Action::BASIC) {
             $fragment = 'search';
         } elseif ($self->_action == CRM_Core_Action::PROFILE) {
             $fragment = 'search/builder';
         } elseif ($self->_action == CRM_Core_Action::ADVANCED) {
             $fragment = 'search/advanced';
         } else {
             $fragment = 'search/custom';
         }
         $urlString = 'civicrm/contact/' . $fragment;
     }
     $emails = NULL;
     if (!empty($testParams['sendtest'])) {
         if (!($testParams['test_group'] || $testParams['test_email'])) {
             CRM_Core_Session::setStatus(ts('You did not provide an email address or select a group.'), ts('Test not sent.'), 'error');
             $error = TRUE;
         }
         if ($testParams['test_email']) {
             $emailAdd = explode(',', $testParams['test_email']);
             foreach ($emailAdd as $key => $value) {
                 $email = trim($value);
                 $testParams['emails'][] = $email;
                 $emails .= ($emails ? ',' : '') . "'" . CRM_Core_DAO::escapeString($email) . "'";
                 if (!CRM_Utils_Rule::email($email)) {
                     CRM_Core_Session::setStatus(ts('Please enter a valid email address.'), ts('Test not sent.'), 'error');
                     $error = TRUE;
                 }
             }
         }
         if ($error) {
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
             return $error;
         }
     }
     if (!empty($testParams['_qf_Test_submit'])) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         if ($ssID && $self->_searchBasedMailing) {
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("You can continue later by clicking the 'Continue' action to resume working on it.<br />From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             //replace user context to search.
             $context = $self->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}&qfKey={$testParams['qfKey']}";
             $url = CRM_Utils_System::url($urlString, $urlParams);
         } else {
             $status = ts("Click the 'Continue' action to resume working on it.");
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
         }
         CRM_Core_Session::setStatus($status, ts('Mailing Saved'), 'success');
         CRM_Utils_System::redirect($url);
     }
     if (CRM_Mailing_Info::workflowEnabled()) {
         if (!CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings')) {
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (!empty($testParams['_qf_Test_next']) && $self->get('count') <= 0) {
         return array('_qf_default' => ts("You can not schedule or send this mailing because there are currently no recipients selected. Click 'Previous' to return to the Select Recipients step, OR click 'Save & Continue Later'."));
     }
     if (!empty($_POST['_qf_Import_refresh']) || !empty($testParams['_qf_Test_next']) || empty($testParams['sendtest'])) {
         $error = TRUE;
         return $error;
     }
     $job = new CRM_Mailing_BAO_MailingJob();
     $job->mailing_id = $self->get('mailing_id');
     $job->is_test = TRUE;
     $job->save();
     $newEmails = NULL;
     $session = CRM_Core_Session::singleton();
     if (!empty($testParams['emails'])) {
         $query = "\nSELECT     e.id, e.contact_id, e.email\nFROM       civicrm_email e\nINNER JOIN civicrm_contact c ON e.contact_id = c.id\nWHERE      e.email IN ({$emails})\nAND        e.on_hold = 0\nAND        c.is_opt_out = 0\nAND        c.do_not_email = 0\nAND        c.is_deleted = 0\nAND        c.is_deceased = 0\nGROUP BY   e.id\nORDER BY   e.is_bulkmail DESC, e.is_primary DESC\n";
         $dao = CRM_Core_DAO::executeQuery($query);
         $emailDetail = array();
         // fetch contact_id and email id for all existing emails
         while ($dao->fetch()) {
             $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
         }
         $dao->free();
         foreach ($testParams['emails'] as $key => $email) {
             // Email addresses are forced to lower case when saved, so ensure
             // we have the same case when comparing.
             $email = trim(strtolower($email));
             $contactId = $emailId = NULL;
             if (array_key_exists($email, $emailDetail)) {
                 $emailId = $emailDetail[$email]['email_id'];
                 $contactId = $emailDetail[$email]['contact_id'];
             }
             if (!$contactId) {
                 //create new contact.
                 $params = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
                 $contact = CRM_Contact_BAO_Contact::create($params);
                 $emailId = $contact->email[0]->id;
                 $contactId = $contact->id;
                 $contact->free();
             }
             $params = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
             CRM_Mailing_Event_BAO_Queue::create($params);
         }
     }
     $testParams['job_id'] = $job->id;
     $isComplete = FALSE;
     while (!$isComplete) {
         $isComplete = CRM_Mailing_BAO_MailingJob::runJobs($testParams);
     }
     if (!empty($testParams['sendtest'])) {
         $status = NULL;
         if (CRM_Mailing_Info::workflowEnabled()) {
             if (CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings') || CRM_Core_Permission::check('access CiviMail')) {
                 $status = ts("Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
             }
         } else {
             $status = ts("Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
         }
         if ($status) {
             CRM_Core_Session::setStatus($status, ts('Test message sent'), 'success');
         }
         $url = CRM_Utils_System::url($urlString, $urlParams);
         CRM_Utils_System::redirect($url);
     }
     $error = TRUE;
     return $error;
 }
Exemplo n.º 23
0
 /**
  * Create Current employer relationship for a individual.
  *
  * @param int $contactID
  *   Contact id of the individual.
  * @param $organization
  *   (id or name).
  * @param int $previousEmployerID
  * @param bool $newContact
  *
  */
 public static function createCurrentEmployerRelationship($contactID, $organization, $previousEmployerID = NULL, $newContact = FALSE)
 {
     //if organization name is passed. CRM-15368,CRM-15547
     if ($organization && !is_numeric($organization)) {
         $organizationParams['organization_name'] = $organization;
         $dedupeParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
         $dedupeParams['check_permission'] = FALSE;
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
         if (is_array($dupeIDs) && !empty($dupeIDs)) {
             // we should create relationship only w/ first org CRM-4193
             foreach ($dupeIDs as $orgId) {
                 $organization = $orgId;
                 break;
             }
         } else {
             //create new organization
             $newOrg = array('contact_type' => 'Organization', 'organization_name' => $organization);
             $org = CRM_Contact_BAO_Contact::create($newOrg);
             $organization = $org->id;
         }
     }
     if ($organization && is_numeric($organization)) {
         $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($organization => TRUE));
         list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::legacyCreateMultiple($relationshipParams, $cid);
         // In case we change employer, clean previous employer related records.
         if (!$previousEmployerID && !$newContact) {
             $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
         }
         if ($previousEmployerID && $previousEmployerID != $organization) {
             self::clearCurrentEmployer($contactID, $previousEmployerID);
         }
         // set current employer
         self::setCurrentEmployer(array($contactID => $organization));
         $relationshipParams['relationship_ids'] = $relationshipIds;
         // Handle related memberships. CRM-3792
         self::currentEmployerRelatedMembership($contactID, $organization, $relationshipParams, $duplicate, $previousEmployerID);
     }
 }
Exemplo n.º 24
0
 /**
  * Form rule to send out a test mailing.
  *
  * @param array $params     Array of the form values
  * @param array $files      Any files posted to the form
  * @param array $self       an current this object
  *
  * @return boolean          true on succesful SMTP handoff
  * @access public
  */
 static function &testMail($testParams, $files, $self)
 {
     $error = NULL;
     $urlString = 'civicrm/mailing/send';
     $urlParams = "_qf_Test_display=true&qfKey={$testParams['qfKey']}";
     $ssID = $self->get('ssID');
     if ($ssID && $self->_searchBasedMailing) {
         if ($self->_action == CRM_Core_Action::BASIC) {
             $fragment = 'search';
         } elseif ($self->_action == CRM_Core_Action::PROFILE) {
             $fragment = 'search/builder';
         } elseif ($self->_action == CRM_Core_Action::ADVANCED) {
             $fragment = 'search/advanced';
         } else {
             $fragment = 'search/custom';
         }
         $urlString = 'civicrm/contact/' . $fragment;
     }
     $emails = NULL;
     if (CRM_Utils_Array::value('sendtest', $testParams)) {
         if (!($testParams['test_group'] || $testParams['test_email'])) {
             CRM_Core_Session::setStatus(ts('Your did not provided any email address or selected any group. No test mail is sent.'));
             $error = TRUE;
         }
         if ($testParams['test_email']) {
             $emailAdd = explode(',', $testParams['test_email']);
             foreach ($emailAdd as $key => $value) {
                 $email = trim($value);
                 $testParams['emails'][] = $email;
                 $emails .= $emails ? ",'{$email}'" : "'{$email}'";
                 if (!CRM_Utils_Rule::email($email)) {
                     CRM_Core_Session::setStatus(ts('Please enter valid email addresses only.'));
                     $error = TRUE;
                 }
             }
         }
         if ($error) {
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
             return $error;
         }
     }
     if (CRM_Utils_Array::value('_qf_Test_submit', $testParams)) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         if ($ssID && $self->_searchBasedMailing) {
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("Your mailing has been saved. You can continue later by clicking the 'Continue' action to resume working on it.<br /> From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             CRM_Core_Session::setStatus($status);
             //replace user context to search.
             $context = $self->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}&qfKey={$testParams['qfKey']}";
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
         } else {
             $status = ts("Your mailing has been saved. Click the 'Continue' action to resume working on it.");
             CRM_Core_Session::setStatus($status);
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (CRM_Mailing_Info::workflowEnabled()) {
         if (!CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings')) {
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (CRM_Utils_Array::value('_qf_Import_refresh', $_POST) || CRM_Utils_Array::value('_qf_Test_next', $testParams) || !CRM_Utils_Array::value('sendtest', $testParams)) {
         $error = TRUE;
         return $error;
     }
     $job = new CRM_Mailing_BAO_Job();
     $job->mailing_id = $self->get('mailing_id');
     $job->is_test = TRUE;
     $job->save();
     $newEmails = NULL;
     $session = CRM_Core_Session::singleton();
     if (!empty($testParams['emails'])) {
         $query = "\n                      SELECT id, contact_id, email  \n                      FROM civicrm_email  \n                      WHERE civicrm_email.email IN ({$emails})";
         $dao = CRM_Core_DAO::executeQuery($query);
         $emailDetail = array();
         // fetch contact_id and email id for all existing emails
         while ($dao->fetch()) {
             $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
         }
         $dao->free();
         foreach ($testParams['emails'] as $key => $email) {
             $email = trim($email);
             $contactId = $emailId = NULL;
             if (array_key_exists($email, $emailDetail)) {
                 $emailId = $emailDetail[$email]['email_id'];
                 $contactId = $emailDetail[$email]['contact_id'];
             }
             if (!$contactId) {
                 //create new contact.
                 $params = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
                 $contact = CRM_Contact_BAO_Contact::create($params);
                 $emailId = $contact->email[0]->id;
                 $contactId = $contact->id;
                 $contact->free();
             }
             $params = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
             CRM_Mailing_Event_BAO_Queue::create($params);
         }
     }
     $testParams['job_id'] = $job->id;
     $isComplete = FALSE;
     while (!$isComplete) {
         $isComplete = CRM_Mailing_BAO_Job::runJobs($testParams);
     }
     if (CRM_Utils_Array::value('sendtest', $testParams)) {
         $status = ts('Your test message has been sent.');
         if (CRM_Mailing_Info::workflowEnabled()) {
             if (CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings') || CRM_Core_Permission::check('access CiviMail')) {
                 $status .= ts(" Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
             }
         } else {
             $status .= ts(" Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
         }
         CRM_Core_Session::setStatus($status);
         $url = CRM_Utils_System::url($urlString, $urlParams);
         CRM_Utils_System::redirect($url);
     }
     $error = TRUE;
     return $error;
 }
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // need to process / save communication preferences
     // this is a chekbox, so mark false if we dont get a POST value
     $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
     $params['contact_type'] = $this->_contactType;
     $params['contact_id'] = $this->_contactId;
     CRM_Contact_BAO_Contact::create($params);
     $response = array('status' => 'save');
     $this->postProcessHook();
     echo json_encode($response);
     CRM_Utils_System::civiExit();
 }
Exemplo n.º 26
0
/**
 * Helper function for Contact create.
 *
 * @param array $params
 *   (reference ) an assoc array of name/value pairs.
 * @param int $contactID
 *   If present the contact with that ID is updated.
 *
 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
 */
function _civicrm_api3_contact_update($params, $contactID = NULL)
{
    //@todo - doesn't contact create support 'id' which is already set- check & remove
    if ($contactID) {
        $params['contact_id'] = $contactID;
    }
    return CRM_Contact_BAO_Contact::create($params);
}
Exemplo n.º 27
0
 /**
  * Form submission of new/edit contact is processed.
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     // check if dedupe button, if so return.
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->_dedupeButtonName) {
         return;
     }
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     //get the related id for shared / current employer
     if (CRM_Utils_Array::value('shared_household_id', $params)) {
         $params['shared_household'] = $params['shared_household_id'];
     }
     if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && CRM_Utils_Array::value('current_employer', $params)) {
         $params['current_employer'] = $params['current_employer_id'];
     }
     // don't carry current_employer_id field,
     // since we don't want to directly update DAO object without
     // handling related business logic ( eg related membership )
     if (isset($params['current_employer_id'])) {
         unset($params['current_employer_id']);
     }
     $params['contact_type'] = $this->_contactType;
     if ($this->_contactId) {
         $params['contact_id'] = $this->_contactId;
     }
     //make deceased date null when is_deceased = false
     if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('Demographics', $this->_editOptions) && !CRM_Utils_Array::value('is_deceased', $params)) {
         $params['is_deceased'] = false;
         $params['deceased_date'] = null;
     }
     if ($this->_contactSubType && $this->_action & CRM_Core_Action::ADD) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     // action is taken depending upon the mode
     require_once 'CRM/Utils/Hook.php';
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', $params['contact_type'], null, $params);
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], false, true);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_contactId, $params['contact_type'], true);
     if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
         // this is a chekbox, so mark false if we dont get a POST value
         $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, false);
     }
     // copy household address, if use_household_address option (for individual form) is checked
     if ($this->_contactType == 'Individual') {
         if (CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('shared_household', $params)) {
             if (is_numeric($params['shared_household'])) {
                 CRM_Contact_Form_Edit_Individual::copyHouseholdAddress($params);
             }
             CRM_Contact_Form_Edit_Individual::createSharedHousehold($params);
         } else {
             $params['mail_to_household_id'] = 'null';
         }
     } else {
         $params['mail_to_household_id'] = 'null';
     }
     if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
         unset($params['group']);
     }
     if (CRM_Utils_Array::value('contact_id', $params) && $this->_action & CRM_Core_Action::UPDATE) {
         // cleanup unwanted location blocks
         require_once 'CRM/Core/BAO/Location.php';
         CRM_Core_BAO_Location::cleanupContactLocations($params);
         // figure out which all groups are intended to be removed
         if (!empty($params['group'])) {
             $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
             if (is_array($contactGroupList)) {
                 foreach ($contactGroupList as $key) {
                     if ($params['group'][$key['group_id']] != 1) {
                         $params['group'][$key['group_id']] = -1;
                     }
                 }
             }
         }
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact =& CRM_Contact_BAO_Contact::create($params, true, false);
     if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('mail_to_household_id', $params)) {
         // add/edit/delete the relation of individual with household, if use-household-address option is checked/unchecked.
         CRM_Contact_Form_Edit_Individual::handleSharedRelation($contact->id, $params);
     }
     if ($this->_contactType == 'Household' && $this->_action & CRM_Core_Action::UPDATE) {
         //TO DO: commented because of schema changes
         require_once 'CRM/Contact/Form/Edit/Household.php';
         CRM_Contact_Form_Edit_Household::synchronizeIndividualAddresses($contact->id);
     }
     if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
         //add contact to tags
         require_once 'CRM/Core/BAO/EntityTag.php';
         CRM_Core_BAO_EntityTag::create($params['tag'], $params['contact_id']);
     }
     // here we replace the user context with the url to view this contact
     $session =& CRM_Core_Session::singleton();
     CRM_Core_Session::setStatus(ts('Your %1 contact record has been saved.', array(1 => $contact->contact_type_display)));
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->getButtonName('next', 'new') || $buttonName == $this->getButtonName('upload', 'new')) {
         require_once 'CRM/Utils/Recent.php';
         // add the recently viewed contact
         $displayName = CRM_Contact_BAO_Contact::displayName($contact->id);
         CRM_Utils_Recent::add($displayName, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $displayName);
         $resetStr = "reset=1&ct={$contact->contact_type}";
         $resetStr .= $this->_contactSubType ? "&cst={$this->_contactSubType}" : '';
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
     } else {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id));
     }
     // now invoke the post hook
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
     } else {
         CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
     }
 }
 /**
  * @param $mailingId
  * @param $emails
  *
  * @return CRM_Mailing_BAO_MailingJob
  */
 protected static function sendTestEmailToIndividuals($mailingId, $emails)
 {
     $job = static::createTestMailingJob($mailingId);
     $emailArr = explode(',', $emails);
     array_walk($emailArr, function (&$email) {
         $email = trim($email);
     });
     $emailStr = implode(', ', array_map(function ($email) {
         return '\'' . $email . '\'';
     }, $emailArr));
     $query = "\n      SELECT e.id, e.contact_id, e.email\n      FROM civicrm_email e\n\n      INNER JOIN civicrm_contact c ON e.contact_id = c.id\n\n      WHERE e.email IN ({$emailStr})\n        AND e.on_hold = 0\n        AND c.is_opt_out = 0\n        AND c.do_not_email = 0\n        AND c.is_deceased = 0\n\n      GROUP BY e.id\n      ORDER BY e.is_bulkmail DESC, e.is_primary DESC\n    ";
     $dao = CRM_Core_DAO::executeQuery($query);
     $emailDetail = array();
     // fetch contact_id and email id for all existing emails
     while ($dao->fetch()) {
         $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
     }
     $dao->free();
     foreach ($emailArr as $email) {
         $email = trim($email);
         $contactId = $emailId = NULL;
         if (array_key_exists($email, $emailDetail)) {
             $emailId = $emailDetail[$email]['email_id'];
             $contactId = $emailDetail[$email]['contact_id'];
         }
         if (!$contactId) {
             //create new contact.
             $createParams = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
             $contact = CRM_Contact_BAO_Contact::create($createParams);
             $emailId = $contact->email[0]->id;
             $contactId = $contact->id;
             $contact->free();
         }
         $queueParams = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
         CRM_Mailing_Event_BAO_Queue::create($queueParams);
     }
     static::runTestEmailJobs($job);
     return $job;
 }
Exemplo n.º 29
0
 /**
  * @param $from
  * @param $body
  * @param null $to
  * @param int $trackID
  *
  * @return self|null|object
  * @throws CRM_Core_Exception
  */
 public function processInbound($from, $body, $to = NULL, $trackID = NULL)
 {
     $formatFrom = $this->formatPhone($this->stripPhone($from), $like, "like");
     $escapedFrom = CRM_Utils_Type::escape($formatFrom, 'String');
     $fromContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $escapedFrom . '"');
     if (!$fromContactID) {
         // unknown mobile sender -- create new contact
         // use fake @mobile.sms email address for new contact since civi
         // requires email or name for all contacts
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
         $phoneloc = array_search('Home', $locationTypes);
         $phonetype = array_search('Mobile', $phoneTypes);
         $stripFrom = $this->stripPhone($from);
         $contactparams = array('contact_type' => 'Individual', 'email' => array(1 => array('location_type_id' => $phoneloc, 'email' => $stripFrom . '@mobile.sms')), 'phone' => array(1 => array('phone_type_id' => $phonetype, 'location_type_id' => $phoneloc, 'phone' => $stripFrom)));
         $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
         $fromContactID = $fromContact->id;
     }
     if ($to) {
         $to = CRM_Utils_Type::escape($to, 'String');
         $toContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $to . '"');
     } else {
         $toContactID = $fromContactID;
     }
     if ($fromContactID) {
         $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status'));
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Inbound SMS', 'name');
         // note: lets not pass status here, assuming status will be updated by callback
         $activityParams = array('source_contact_id' => $toContactID, 'target_contact_id' => $fromContactID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'status_id' => $actStatusIDs['Completed'], 'details' => $body, 'phone_number' => $from);
         if ($trackID) {
             $trackID = CRM_Utils_Type::escape($trackID, 'String');
             $activityParams['result'] = $trackID;
         }
         $result = CRM_Activity_BAO_Activity::create($activityParams);
         CRM_Core_Error::debug_log_message("Inbound SMS recorded for cid={$fromContactID}.");
         return $result;
     }
 }
Exemplo n.º 30
0
/**
 * @todo Move this to ContactFormat.php
 * @deprecated
 */
function civicrm_contact_format_create(&$params)
{
    _civicrm_initialize();
    CRM_Core_DAO::freeResult();
    // return error if we have no params
    if (empty($params)) {
        return civicrm_create_error('Input Parameters empty');
    }
    $error = _civicrm_required_formatted_contact($params);
    if (civicrm_error($error)) {
        return $error;
    }
    $error = _civicrm_validate_formatted_contact($params);
    if (civicrm_error($error)) {
        return $error;
    }
    //get the prefix id etc if exists
    require_once 'CRM/Contact/BAO/Contact.php';
    CRM_Contact_BAO_Contact::resolveDefaults($params, TRUE);
    require_once 'CRM/Import/Parser.php';
    if (CRM_Utils_Array::value('onDuplicate', $params) != CRM_Import_Parser::DUPLICATE_NOCHECK) {
        CRM_Core_Error::reset();
        $error = _civicrm_duplicate_formatted_contact($params);
        if (civicrm_error($error)) {
            return $error;
        }
    }
    $contact = CRM_Contact_BAO_Contact::create($params, CRM_Utils_Array::value('fixAddress', $params));
    _civicrm_object_to_array($contact, $contactArray);
    return $contactArray;
}