/**
 * Get CiviCRM domain details
 * {@getfields domain_create}
 * @example DomainGet.php
 */
function civicrm_api3_domain_get($params)
{
    $params['version'] = CRM_Utils_array::value('domain_version', $params);
    unset($params['version']);
    $bao = new CRM_Core_BAO_Domain();
    if (CRM_Utils_Array::value('current_domain', $params)) {
        $domainBAO = CRM_Core_Config::domainID();
        $params['id'] = $domainBAO;
    }
    _civicrm_api3_dao_set_filter($bao, $params, true, 'domain');
    $domains = _civicrm_api3_dao_to_array($bao, $params, true, 'domain');
    foreach ($domains as $domain) {
        $values = array();
        $locparams = array('entity_id' => $domain['id'], 'entity_table' => 'civicrm_domain');
        require_once 'CRM/Core/BAO/Location.php';
        $values['location'] = CRM_Core_BAO_Location::getValues($locparams, TRUE);
        $address_array = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'state_province_id', 'postal_code', 'country_id', 'geo_code_1', 'geo_code_2');
        require_once 'CRM/Core/OptionGroup.php';
        if (!empty($values['location']['email'])) {
            $domain['domain_email'] = CRM_Utils_Array::value('email', $values['location']['email'][1]);
        }
        if (!empty($values['location']['phone'])) {
            $domain['domain_phone'] = array('phone_type' => CRM_Core_OptionGroup::getLabel('phone_type', CRM_Utils_Array::value('phone_type_id', $values['location']['phone'][1])), 'phone' => CRM_Utils_Array::value('phone', $values['location']['phone'][1]));
        }
        if (!empty($values['location']['address'])) {
            foreach ($address_array as $value) {
                $domain['domain_address'][$value] = CRM_Utils_Array::value($value, $values['location']['address'][1]);
            }
        }
        list($domain['from_name'], $domain['from_email']) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
        $domains[$domain['id']] = array_merge($domains[$domain['id']], $domain);
    }
    return civicrm_api3_create_success($domains, $params, 'domain', 'get', $bao);
}
 /**
  * Function to process the activities
  *
  * @param object $form         form object
  * @param array  $params       associated array of the submitted values
  * @param array  $ids          array of ids
  * @param string $activityType activity Type
  * @param boolean $record   true if it is Record Activity 
  * @access public
  * @return
  */
 public function create(&$params)
 {
     // check required params
     if (!self::dataExists($params)) {
         CRM_Core_Error::fatal('Not enough data to create activity object,');
     }
     $activity = new CRM_Activity_DAO_Activity();
     if (!CRM_Utils_Array::value('status_id', $params)) {
         if (isset($params['activity_date_time']) && strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)) {
             $params['status_id'] = 2;
         } else {
             $params['status_id'] = 1;
         }
     }
     //set priority to Normal for Auto-populated activities (for Cases)
     if (!CRM_Utils_Array::value('priority_id', $params)) {
         require_once 'CRM/Core/PseudoConstant.php';
         $priority = CRM_Core_PseudoConstant::priority();
         $params['priority_id'] = array_search('Normal', $priority);
     }
     if (empty($params['id'])) {
         unset($params['id']);
     }
     if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
         $params['target_contact_id'] = array_unique($params['target_contact_id']);
     }
     if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
     }
     $activity->copyValues($params);
     // start transaction
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $result = $activity->save();
     if (is_a($result, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $result;
     }
     $activityId = $activity->id;
     // check and attach and files as needed
     require_once 'CRM/Core/BAO/File.php';
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
     // attempt to save activity assignment
     $resultAssignment = null;
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         require_once 'CRM/Activity/BAO/ActivityAssignment.php';
         $assignmentParams = array('activity_id' => $activityId);
         if (is_array($params['assignee_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityAssignment', $params, true)) {
                 // first delete existing assignments if any
                 self::deleteActivityAssignment($activityId);
             }
             foreach ($params['assignee_contact_id'] as $acID) {
                 if ($acID) {
                     $assignmentParams['assignee_contact_id'] = $acID;
                     $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
                     if (is_a($resultAssignment, 'CRM_Core_Error')) {
                         $transaction->rollback();
                         return $resultAssignment;
                     }
                 }
             }
         } else {
             $assignmentParams['assignee_contact_id'] = $params['assignee_contact_id'];
             if (CRM_Utils_Array::value('id', $params)) {
                 $assignment = new CRM_Activity_BAO_ActivityAssignment();
                 $assignment->activity_id = $activityId;
                 $assignment->find(true);
                 if ($assignment->assignee_contact_id != $params['assignee_contact_id']) {
                     $assignmentParams['id'] = $assignment->id;
                     $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
                 }
             } else {
                 $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityAssignment', $params, true)) {
             self::deleteActivityAssignment($activityId);
         }
     }
     if (is_a($resultAssignment, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $resultAssignment;
     }
     // attempt to save activity targets
     $resultTarget = null;
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         $targetParams = array('activity_id' => $activityId);
         $resultTarget = array();
         if (is_array($params['target_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityTarget', $params, true)) {
                 // first delete existing targets if any
                 self::deleteActivityTarget($activityId);
             }
             foreach ($params['target_contact_id'] as $tid) {
                 if ($tid) {
                     $targetParams['target_contact_id'] = $tid;
                     $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
                     if (is_a($resultTarget, 'CRM_Core_Error')) {
                         $transaction->rollback();
                         return $resultTarget;
                     }
                 }
             }
         } else {
             $targetParams['target_contact_id'] = $params['target_contact_id'];
             if (CRM_Utils_Array::value('id', $params)) {
                 $target = new CRM_Activity_BAO_ActivityTarget();
                 $target->activity_id = $activityId;
                 $target->find(true);
                 if ($target->target_contact_id != $params['target_contact_id']) {
                     $targetParams['id'] = $target->id;
                     $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
                 }
             } else {
                 $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityTarget', $params, true)) {
             self::deleteActivityTarget($activityId);
         }
     }
     // write to changelog before transation is committed/rolled
     // back (and prepare status to display)
     if (CRM_Utils_Array::value('id', $params)) {
         $logMsg = "Activity (id: {$result->id} ) updated with ";
     } else {
         $logMsg = "Activity created for ";
     }
     $msgs = array();
     if (isset($params['source_contact_id'])) {
         $msgs[] = "source={$params['source_contact_id']}";
     }
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         if (is_array($params['target_contact_id']) && !CRM_Utils_array::crmIsEmptyArray($params['target_contact_id'])) {
             $msgs[] = "target=" . implode(',', $params['target_contact_id']);
             // take only first target
             // will be used for recently viewed display
             $t = array_slice($params['target_contact_id'], 0, 1);
             $recentContactId = $t[0];
         } else {
             if (isset($params['target_contact_id'])) {
                 $msgs[] = "target={$params['target_contact_id']}";
                 // will be used for recently viewed display
                 $recentContactId = $params['target_contact_id'];
             }
         }
     } else {
         // at worst, take source for recently viewed display
         $recentContactId = $params['source_contact_id'];
     }
     if (isset($params['assignee_contact_id'])) {
         if (is_array($params['assignee_contact_id'])) {
             $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
         } else {
             $msgs[] = "assignee={$params['assignee_contact_id']}";
         }
     }
     $logMsg .= implode(', ', $msgs);
     self::logActivityAction($result, $logMsg);
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
     }
     $transaction->commit();
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         $recentOther = array();
         require_once 'CRM/Utils/Recent.php';
         if (CRM_Utils_Array::value('case_id', $params)) {
             $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
             $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home");
         } else {
             $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home";
             if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
                 $url = CRM_Utils_System::url('civicrm/contact/view/activity', $q);
                 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/activity', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home");
                 require_once 'CRM/Core/Permission.php';
                 if (CRM_Core_Permission::check("delete activities")) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home");
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/activity', $q);
                 if (CRM_Core_Permission::check("delete activities")) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home");
                 }
             }
         }
         if (!isset($activity->parent_id)) {
             require_once 'CRM/Contact/BAO/Contact.php';
             $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
             // add the recently created Activity
             $activityTypes = CRM_Core_Pseudoconstant::activityType(true, true);
             $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
             $title = "";
             if (isset($activitySubject)) {
                 $title = $activitySubject . ' - ';
             }
             $title = $title . $recentContactDisplay . ' (' . $activityTypes[$activity->activity_type_id] . ')';
             CRM_Utils_Recent::add($title, $url, $activity->id, 'Activity', $recentContactId, $recentContactDisplay, $recentOther);
         }
     }
     // reset the group contact cache since smart groups might be affected due to this
     require_once 'CRM/Contact/BAO/GroupContactCache.php';
     CRM_Contact_BAO_GroupContactCache::remove();
     if (CRM_Utils_Array::value('id', $params)) {
         CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
     } else {
         CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
     }
     // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
     $matches = array();
     if (preg_match('/\\[case #([0-9a-h]{7})\\]/', $params['subject'], $matches)) {
         $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
         $hash = $matches[1];
         $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('{$key}', id)), 1, 7) = '{$hash}'";
         $caseParams = array('activity_id' => $activity->id, 'case_id' => CRM_Core_DAO::singleValueQuery($query));
         if ($caseParams['case_id']) {
             require_once 'CRM/Case/BAO/Case.php';
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
         } else {
             self::logActivityAction($activity, "unknown case hash encountered: {$hash}");
         }
     }
     return $result;
 }
Exemple #3
0
 /**
  * assign the minimal set of variables to the template
  *
  * @return void
  * @access public
  */
 function assignToTemplate()
 {
     $name = CRM_Utils_Array::value('billing_first_name', $this->_params);
     if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
         $name .= " {$this->_params['billing_middle_name']}";
     }
     $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
     $name = trim($name);
     $this->assign('billingName', $name);
     $this->set('name', $name);
     $this->assign('paymentProcessor', $this->_paymentProcessor);
     $vars = array('amount', 'currencyID', 'credit_card_type', 'trxn_id', 'amount_level');
     $config = CRM_Core_Config::singleton();
     if (isset($this->_values['is_recur']) && CRM_Utils_Array::value('is_recur', $this->_paymentProcessor)) {
         $this->assign('is_recur_enabled', 1);
         $vars = array_merge($vars, array('is_recur', 'frequency_interval', 'frequency_unit', 'installments'));
     }
     if (in_array('CiviPledge', $config->enableComponents) && CRM_Utils_Array::value('is_pledge', $this->_params) == 1) {
         $this->assign('pledge_enabled', 1);
         $vars = array_merge($vars, array('is_pledge', 'pledge_frequency_interval', 'pledge_frequency_unit', 'pledge_installments'));
     }
     if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
         $this->_params['amount_level'] = '';
     }
     foreach ($vars as $v) {
         if (isset($this->_params[$v])) {
             if ($v == 'frequency_unit' || $v == 'pledge_frequency_unit') {
                 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
                 if (array_key_exists($this->_params[$v], $frequencyUnits)) {
                     $this->_params[$v] = $frequencyUnits[$this->_params[$v]];
                 }
             }
             if ($v == "amount" && $this->_params[$v] === 0) {
                 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
             }
             $this->assign($v, $this->_params[$v]);
         }
     }
     // assign the address formatted up for display
     $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
     $addressFields = array();
     foreach ($addressParts as $part) {
         list($n, $id) = explode('-', $part);
         $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $this->_params);
     }
     $this->assign('address', CRM_Utils_Address::format($addressFields));
     if (CRM_Utils_Array::value('hidden_onbehalf_profile', $this->_params)) {
         $this->assign('onBehalfName', $this->_params['organization_name']);
         $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
         $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
     }
     //fix for CRM-3767
     $assignCCInfo = FALSE;
     if ($this->_amount > 0.0) {
         $assignCCInfo = TRUE;
     } elseif (CRM_Utils_array::value('selectMembership', $this->_params)) {
         $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
         if ($memFee > 0.0) {
             $assignCCInfo = TRUE;
         }
     }
     if ($this->_contributeMode == 'direct' && $assignCCInfo) {
         if ($this->_paymentProcessor && $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) {
             $this->assign('payment_type', $this->_paymentProcessor['payment_type']);
             $this->assign('account_holder', $this->_params['account_holder']);
             $this->assign('bank_identification_number', $this->_params['bank_identification_number']);
             $this->assign('bank_name', $this->_params['bank_name']);
             $this->assign('bank_account_number', $this->_params['bank_account_number']);
         } else {
             $date = CRM_Utils_Date::format(CRM_Utils_array::value('credit_card_exp_date', $this->_params));
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard(CRM_Utils_array::value('credit_card_number', $this->_params)));
         }
     }
     $this->assign('email', $this->controller->exportValue('Main', "email-{$this->_bltID}"));
     // also assign the receipt_text
     if (isset($this->_values['receipt_text'])) {
         $this->assign('receipt_text', $this->_values['receipt_text']);
     }
 }
Exemple #4
0
 /**
  * @return array|NULL
  *   NULL if execution should proceed; array if the response is already known
  */
 public function loadCMSBootstrap()
 {
     $requestParams = CRM_Utils_Request::exportValues();
     $q = CRM_Utils_array::value('q', $requestParams);
     $args = explode('/', $q);
     // Proceed with bootstrap for "?entity=X&action=Y"
     // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
     if (!empty($q)) {
         if (count($args) == 2 && $args[1] == 'ping') {
             return NULL;
             // this is pretty wonky but maybe there's some reason I can't see
         }
         if (count($args) != 3) {
             return self::error('ERROR: Malformed REST path');
         }
         if ($args[0] != 'civicrm') {
             return self::error('ERROR: Malformed REST path');
         }
         // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
     }
     if (!CRM_Utils_System::authenticateKey(FALSE)) {
         // FIXME: At time of writing, this doesn't actually do anything because
         // authenticateKey abends, but that's a bad behavior which sends a
         // malformed response.
         return self::error('Failed to authenticate key');
     }
     $uid = NULL;
     if (!$uid) {
         $store = NULL;
         $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
         if (empty($api_key)) {
             return self::error("FATAL: mandatory param 'api_key' (user key) missing");
         }
         $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
         if ($contact_id) {
             $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
         }
     }
     if ($uid) {
         CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
         return NULL;
     } else {
         return self::error('ERROR: No CMS user associated with given api-key');
     }
 }
Exemple #5
0
 /**
  * Add fields to $profileAddressFields as appropriate.
  * profileAddressFields is assigned to the template to tell it
  * what fields are in the profile address
  * that potentially should be copied to the Billing fields
  * we want to give precedence to
  *   1) Billing &
  *   2) then Primary designated as 'Primary
  *   3) location_type is primary
  *   4) if none of these apply then it just uses the first one
  *
  *   as this will be used to
  * transfer profile address data to billing fields
  * http://issues.civicrm.org/jira/browse/CRM-5869
  *
  * @param string $key
  *   Field key - e.g. street_address-Primary, first_name.
  * @param array $profileAddressFields
  *   Array of profile fields that relate to address fields.
  * @param array $profileFilter
  *   Filter to apply to profile fields - expected usage is to only fill based on.
  *   the bottom profile per CRM-13726
  *
  * @return bool
  *   Can the address block be hidden safe in the knowledge all fields are elsewhere collected (see CRM-15118)
  */
 public static function assignAddressField($key, &$profileAddressFields, $profileFilter)
 {
     $billing_id = CRM_Core_BAO_LocationType::getBilling();
     list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
     $profileFields = civicrm_api3('uf_field', 'get', array_merge($profileFilter, array('is_active' => 1, 'return' => 'field_name, is_required', 'options' => array('limit' => 0))));
     //check for valid fields ( fields that are present in billing block )
     $validBillingFields = array('first_name', 'middle_name', 'last_name', 'street_address', 'supplemental_address_1', 'city', 'state_province', 'postal_code', 'country');
     $requiredBillingFields = array_diff($validBillingFields, array('middle_name', 'supplemental_address_1'));
     $validProfileFields = array();
     $requiredProfileFields = array();
     foreach ($profileFields['values'] as $field) {
         if (in_array($field['field_name'], $validBillingFields)) {
             $validProfileFields[] = $field['field_name'];
         }
         if ($field['is_required']) {
             $requiredProfileFields[] = $field['field_name'];
         }
     }
     if (!in_array($prefixName, $validProfileFields)) {
         return FALSE;
     }
     if (!empty($index) && (!CRM_Utils_array::value($prefixName, $profileAddressFields) || $index == $billing_id || $index == 'Primary' && $profileAddressFields[$prefixName] != $billing_id || $index == CRM_Core_BAO_LocationType::getDefault()->id && $profileAddressFields[$prefixName] != $billing_id && $profileAddressFields[$prefixName] != 'Primary')) {
         $profileAddressFields[$prefixName] = $index;
     }
     $potentiallyMissingRequiredFields = array_diff($requiredBillingFields, $requiredProfileFields);
     CRM_Core_Resources::singleton()->addSetting(array('billing' => array('billingProfileIsHideable' => empty($potentiallyMissingRequiredFields))));
 }
 /**
  * Process the form submission.
  *
  *
  * @param array $params
  *
  * @return void
  */
 public function postProcess($params = NULL)
 {
     $transaction = new CRM_Core_Transaction();
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = NULL;
         //block deleting activities which affects
         //case attributes.CRM-4543
         $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
         $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
         if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
             $params = array('id' => $this->_activityId);
             $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, TRUE);
             if ($activityDelete) {
                 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
             }
         } else {
             $statusMsg = ts("Selected Activity cannot be deleted.");
         }
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = NULL;
         $params = array('id' => $this->_activityId);
         $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
         if ($activityRestore) {
             $statusMsg = ts('The selected activity has been restored.<br />');
         }
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     //set parent id if its edit mode
     if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
         $params['parent_id'] = $parentId;
     }
     // store the dates with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     $params['activity_type_id'] = $this->_activityTypeId;
     // format with contact (target contact) values
     if (isset($params['target_contact_id'])) {
         $params['target_contact_id'] = explode(',', $params['target_contact_id']);
     } else {
         $params['target_contact_id'] = array();
     }
     // format activity custom data
     if (!empty($params['hidden_custom'])) {
         if ($this->_activityId) {
             // unset custom fields-id from params since we want custom
             // fields to be saved for new activity.
             foreach ($params as $key => $value) {
                 $match = array();
                 if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) {
                     $params[$match[1] . '-1'] = $params[$key];
                     // for autocomplete transfer hidden value instead of label
                     if ($params[$key] && isset($params[$key . '_id'])) {
                         $params[$match[1] . '-1_id'] = $params[$key . '_id'];
                         unset($params[$key . '_id']);
                     }
                     unset($params[$key]);
                 }
             }
         }
         // build custom data getFields array
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_activityId, 'Activity');
     }
     // assigning formatted value
     if (!empty($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = array();
     }
     if (isset($this->_activityId)) {
         // activity which hasn't been modified by a user yet
         if ($this->_defaults['is_auto'] == 1) {
             $params['is_auto'] = 0;
         }
         // always create a revision of an case activity. CRM-4533
         $newActParams = $params;
         // add target contact values in update mode
         if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
             $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
         }
     }
     if (!isset($newActParams)) {
         // add more attachments if needed for old activity
         CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($params);
         foreach ($this->_caseId as $key => $val) {
             $params['case_id'] = $val;
             // activity create/update
             $activity = CRM_Activity_BAO_Activity::create($params);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($params, $activity);
         }
     } else {
         // since the params we need to set are very few, and we don't want rest of the
         // work done by bao create method , lets use dao object to make the changes
         $params = array('id' => $this->_activityId);
         $params['is_current_revision'] = 0;
         $activity = new CRM_Activity_DAO_Activity();
         $activity->copyValues($params);
         $activity->save();
     }
     // create a new version of activity if activity was found to
     // have been modified/created by user
     if (isset($newActParams)) {
         // set proper original_id
         if (!empty($this->_defaults['original_id'])) {
             $newActParams['original_id'] = $this->_defaults['original_id'];
         } else {
             $newActParams['original_id'] = $activity->id;
         }
         //is_current_revision will be set to 1 by default.
         // add attachments if any
         CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($newActParams);
         foreach ($this->_caseId as $key => $val) {
             $newActParams['case_id'] = $val;
             $activity = CRM_Activity_BAO_Activity::create($newActParams);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($newActParams, $activity);
         }
         // copy files attached to old activity if any, to new one,
         // as long as users have not selected the 'delete attachment' option.
         if (empty($newActParams['is_delete_attachment'])) {
             CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id);
         }
         // copy back params to original var
         $params = $newActParams;
     }
     foreach ($vvalue as $vkey => $vval) {
         if ($vval['actId']) {
             // add tags if exists
             $tagParams = array();
             if (!empty($params['tag'])) {
                 foreach ($params['tag'] as $tag) {
                     $tagParams[$tag] = 1;
                 }
             }
             //save static tags
             CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $vval['actId']);
             //save free tags
             if (isset($params['taglist']) && !empty($params['taglist'])) {
                 CRM_Core_Form_Tag::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
             }
         }
         // update existing case record if needed
         $caseParams = $params;
         $caseParams['id'] = $vval['case_id'];
         if (!empty($caseParams['case_status_id'])) {
             $caseParams['status_id'] = $caseParams['case_status_id'];
         }
         // unset params intended for activities only
         unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']);
         $case = CRM_Case_BAO_Case::create($caseParams);
         // create case activity record
         $caseParams = array('activity_id' => $vval['actId'], 'case_id' => $vval['case_id']);
         CRM_Case_BAO_Case::processCaseActivity($caseParams);
     }
     // Insert civicrm_log record for the activity (e.g. store the
     // created / edited by contact id and date for the activity)
     // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
     // send copy to selected contacts.
     $mailStatus = '';
     $mailToContacts = array();
     //CRM-5695
     //check for notification settings for assignee contacts
     $selectedContacts = array('contact_check');
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
         $selectedContacts[] = 'assignee_contact_id';
     }
     foreach ($vvalue as $vkey => $vval) {
         foreach ($selectedContacts as $dnt => $val) {
             if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) {
                 if ($val == 'contact_check') {
                     $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
                 } else {
                     $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
                     $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
                 }
                 //build an associative array with unique email addresses.
                 foreach ($params[$val] as $key => $value) {
                     if ($val == 'contact_check') {
                         $id = $key;
                     } else {
                         $id = $value;
                     }
                     if (isset($id) && array_key_exists($id, $this->_relatedContacts) && isset($this->_relatedContacts[$id]['email'])) {
                         //if email already exists in array then append with ', ' another role only otherwise add it to array.
                         if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
                             $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
                             $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
                         } else {
                             $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
                         }
                     }
                 }
             }
         }
         $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId);
         $result = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts, $extraParams);
         if (empty($result)) {
             $mailStatus = '';
         }
         // create follow up activity if needed
         $followupStatus = '';
         if (!empty($params['followup_activity_type_id'])) {
             $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($vval['actId'], $params);
             if ($followupActivity) {
                 $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $vval['case_id']);
                 CRM_Case_BAO_Case::processCaseActivity($caseParams);
                 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
             }
         }
         $title = ts("%1 Saved", array(1 => $this->_activityTypeName));
         CRM_Core_Session::setStatus($followupStatus . $mailStatus, $title, 'success');
     }
 }
 /**
  * Based on the provided two contact_ids and a set of tables, move the belongings of the
  * other contact to the main one - be it Location / CustomFields or Contact .. related info.
  * A superset of moveContactBelongings() function.
  *
  * @param int $mainId
  *   Main contact with whom merge has to happen.
  * @param int $otherId
  *   Duplicate contact which would be deleted after merge operation.
  *
  * @param $migrationInfo
  *
  * @return bool
  */
 public static function moveAllBelongings($mainId, $otherId, $migrationInfo)
 {
     if (empty($migrationInfo)) {
         return FALSE;
     }
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     $relTables = CRM_Dedupe_Merger::relTables();
     $moveTables = $locBlocks = $tableOperations = array();
     foreach ($migrationInfo as $key => $value) {
         if ($value == $qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) || substr($key, 0, 12) == 'move_custom_') && $value != NULL) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
             $locField = explode('_', $key);
             $fieldName = $locField[2];
             $fieldCount = $locField[3];
             $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
             // default operation is overwrite.
             if (!$operation) {
                 $operation = 2;
             }
             $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
             $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
             if (array_key_exists('operation', $migrationInfo)) {
                 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
                     if (array_key_exists($key, $migrationInfo['operation'])) {
                         $tableOperations[$table] = $migrationInfo['operation'][$key];
                     }
                 }
             }
         }
     }
     // **** Do location related migration:
     if (!empty($locBlocks)) {
         $locComponent = array('email' => 'Email', 'phone' => 'Phone', 'im' => 'IM', 'openid' => 'OpenID', 'address' => 'Address');
         $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
         $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
         foreach ($locBlocks as $name => $block) {
             if (!is_array($block) || CRM_Utils_System::isNull($block)) {
                 continue;
             }
             $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
             $primaryDAOId = array_key_exists($name, $primaryBlockIds) ? array_pop($primaryBlockIds[$name]) : NULL;
             $billingDAOId = array_key_exists($name, $billingBlockIds) ? array_pop($billingBlockIds[$name]) : NULL;
             foreach ($block as $blkCount => $values) {
                 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
                 $operation = CRM_Utils_Array::value('operation', $values, 2);
                 $otherBlockId = CRM_Utils_Array::value($blkCount, $migrationInfo['other_details']['loc_block_ids'][$name]);
                 // keep 1-1 mapping for address - loc type.
                 $idKey = $blkCount;
                 if (array_key_exists($name, $locComponent)) {
                     $idKey = $locTypeId;
                 }
                 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
                     $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
                 }
                 if (!$otherBlockId) {
                     continue;
                 }
                 // for the block which belongs to other-contact, link the contact to main-contact
                 $otherBlockDAO = new $daoName();
                 $otherBlockDAO->id = $otherBlockId;
                 $otherBlockDAO->contact_id = $mainId;
                 $otherBlockDAO->location_type_id = $locTypeId;
                 // if main contact already has primary & billing, set the flags to 0.
                 if ($primaryDAOId) {
                     $otherBlockDAO->is_primary = 0;
                 }
                 if ($billingDAOId) {
                     $otherBlockDAO->is_billing = 0;
                 }
                 // overwrite - need to delete block which belongs to main-contact.
                 if (isset($mainBlockId) && $mainBlockId && $operation == 2) {
                     $deleteDAO = new $daoName();
                     $deleteDAO->id = $mainBlockId;
                     $deleteDAO->find(TRUE);
                     // if we about to delete a primary / billing block, set the flags for new block
                     // that we going to assign to main-contact
                     if ($primaryDAOId && $primaryDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_primary = 1;
                     }
                     if ($billingDAOId && $billingDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_billing = 1;
                     }
                     $deleteDAO->delete();
                     $deleteDAO->free();
                 }
                 $otherBlockDAO->update();
                 $otherBlockDAO->free();
             }
         }
     }
     // **** Do tables related migrations
     if (!empty($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
         unset($moveTables, $tableOperations);
     }
     // **** Do contact related migrations
     CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
     // fix custom fields so they're edible by createProfileContact()
     static $treeCache = array();
     if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
         $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], CRM_Core_DAO::$_nullObject, NULL, -1);
     }
     $cgTree =& $treeCache[$migrationInfo['main_details']['contact_type']];
     $cFields = array();
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             if (empty($cFields[$fid])) {
                 continue;
             }
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     $customParams = array('entityID' => $mainId, $key => TRUE);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (!empty($customfieldValues[$key])) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value) {
                                 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             }
                             //hack to remove null and duplicate values from array.
                             foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                 if ($v != '' && !in_array($v, $mergeValue)) {
                                     $mergeValue[] = $v;
                                 }
                             }
                             //keep state and country as array format.
                             //for checkbox and m-select format w/ VALUE_SEPARATOR
                             if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $mergeValue) . CRM_Core_DAO::VALUE_SEPARATOR;
                             } else {
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     } elseif (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                         //we require submitted values should be in array format
                         if ($value) {
                             $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             //hack to remove null values from array.
                             $mergeValue = array();
                             foreach ($mergeValueArray as $k => $v) {
                                 if ($v != '') {
                                     $mergeValue[] = $v;
                                 }
                             }
                             $submitted[$key] = $mergeValue;
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // **** Do file custom fields related migrations
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
     // like, delete a file...
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
         $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         if (!empty($fileIds[$mainId])) {
             CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
         }
         // move the other contact's file to main contact
         //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
         if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
             $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
         } else {
             $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         if (CRM_Core_DAO::singleValueQuery("\n        SELECT id\n        FROM civicrm_entity_file\n        WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")) {
             $sql = "\n          UPDATE civicrm_entity_file\n          SET entity_id = {$mainId}\n          WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
         } else {
             $sql = "\n          INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )\n          VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     }
     // move view only custom fields CRM-5362
     $viewOnlyCustomFields = array();
     foreach ($submitted as $key => $value) {
         $fid = (int) substr($key, 7);
         if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
             $viewOnlyCustomFields[$key] = $value;
         }
     }
     // special case to set values for view only, CRM-5362
     if (!empty($viewOnlyCustomFields)) {
         $viewOnlyCustomFields['entityID'] = $mainId;
         CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
     }
     // **** Delete other contact & update prev-next caching
     $otherParams = array('contact_id' => $otherId, 'id' => $otherId, 'version' => 3);
     if (CRM_Core_Permission::check('merge duplicate contacts') && CRM_Core_Permission::check('delete contacts')) {
         // if ext id is submitted then set it null for contact to be deleted
         if (!empty($submitted['external_identifier'])) {
             $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
             CRM_Core_DAO::executeQuery($query);
         }
         civicrm_api('contact', 'delete', $otherParams);
         CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
     }
     // FIXME: else part
     /*         else { */
     /*             CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
     /*         } */
     // CRM-15681 merge sub_types
     if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
         if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
             $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
         } else {
             $submitted['contact_sub_type'] = $other_sub_types;
         }
     }
     // **** Update contact related info for the main contact
     if (!empty($submitted)) {
         $submitted['contact_id'] = $mainId;
         //update current employer field
         if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
             if (!CRM_Utils_System::isNull($currentEmloyerId)) {
                 $submitted['current_employer'] = $submitted['current_employer_id'];
             } else {
                 $submitted['current_employer'] = '';
             }
             unset($submitted['current_employer_id']);
         }
         //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
         if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
             $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
         }
         if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
             $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
         }
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
         unset($submitted);
     }
     CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
     return TRUE;
 }
Exemple #8
0
 /**
  * Process activity creation.
  *
  * @param array $params
  *   Associated array of submitted values.
  *
  * @return self|null|object
  */
 protected function processActivity(&$params)
 {
     $activityAssigned = array();
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     // format assignee params
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
         //skip those assignee contacts which are already assigned
         //while sending a copy.CRM-4509.
         $activityAssigned = array_flip($params['assignee_contact_id']);
         if ($this->_activityId) {
             $assigneeContacts = CRM_Activity_BAO_ActivityContact::getNames($this->_activityId, $assigneeID);
             $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
         }
     }
     // call begin post process. Idea is to let injecting file do
     // any processing before the activity is added/updated.
     $this->beginPostProcess($params);
     $activity = CRM_Activity_BAO_Activity::create($params);
     // add tags if exists
     $tagParams = array();
     if (!empty($params['tag'])) {
         foreach ($params['tag'] as $tag) {
             $tagParams[$tag] = 1;
         }
     }
     //save static tags
     CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);
     //save free tags
     if (isset($params['activity_taglist']) && !empty($params['activity_taglist'])) {
         CRM_Core_Form_Tag::postProcess($params['activity_taglist'], $activity->id, 'civicrm_activity', $this);
     }
     // call end post process. Idea is to let injecting file do any
     // processing needed, after the activity has been added/updated.
     $this->endPostProcess($params, $activity);
     // CRM-9590
     if (!empty($params['is_multi_activity'])) {
         $this->_activityIds[] = $activity->id;
     } else {
         $this->_activityId = $activity->id;
     }
     // create follow up activity if needed
     $followupStatus = '';
     $followupActivity = NULL;
     if (!empty($params['followup_activity_type_id'])) {
         $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
         $followupStatus = ts('A followup activity has been scheduled.');
     }
     // send copy to assignee contacts.CRM-4509
     $mailStatus = '';
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
         $activityIDs = array($activity->id);
         if ($followupActivity) {
             $activityIDs = array_merge($activityIDs, array($followupActivity->id));
         }
         $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityIDs, TRUE, FALSE);
         if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
             $mailToContacts = array();
             //build an associative array with unique email addresses.
             foreach ($activityAssigned as $id => $dnc) {
                 if (isset($id) && array_key_exists($id, $assigneeContacts)) {
                     $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
                 }
             }
             if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
                 //include attachments while sending a copy of activity.
                 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
                 $ics = new CRM_Activity_BAO_ICalendar($activity);
                 $ics->addAttachment($attachments, $mailToContacts);
                 // CRM-8400 add param with _currentlyViewedContactId for URL link in mail
                 CRM_Case_BAO_Case::sendActivityCopy(NULL, $activity->id, $mailToContacts, $attachments, NULL);
                 $ics->cleanup();
                 $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
             }
         }
         // Also send email to follow-up activity assignees if set
         if ($followupActivity) {
             $mailToFollowupContacts = array();
             foreach ($assigneeContacts as $values) {
                 if ($values['activity_id'] == $followupActivity->id) {
                     $mailToFollowupContacts[$values['email']] = $values;
                 }
             }
             if (!CRM_Utils_array::crmIsEmptyArray($mailToFollowupContacts)) {
                 $ics = new CRM_Activity_BAO_ICalendar($followupActivity);
                 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $followupActivity->id);
                 $ics->addAttachment($attachments, $mailToFollowupContacts);
                 CRM_Case_BAO_Case::sendActivityCopy(NULL, $followupActivity->id, $mailToFollowupContacts, $attachments, NULL);
                 $ics->cleanup();
                 $mailStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
             }
         }
     }
     // set status message
     $subject = '';
     if (!empty($params['subject'])) {
         $subject = "'" . $params['subject'] . "'";
     }
     CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2 %3', array(1 => $subject, 2 => $followupStatus, 3 => $mailStatus)), ts('Saved'), 'success');
     return $activity;
 }
function mte_checkSettings($context)
{
    $usedFor = 1;
    if ($context == 'civimail') {
        $usedFor = 2;
    }
    $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mandrill_smtp_settings');
    if (CRM_Utils_array::value('is_active', $mailingBackend) && array_key_exists('used_for', $mailingBackend) && !empty($mailingBackend['used_for'][$usedFor])) {
        return TRUE;
    }
    return FALSE;
}
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess($params = NULL)
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $deleteParams = array('id' => $this->_activityId);
         $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($this->_activityId);
         CRM_Activity_BAO_Activity::deleteActivity($deleteParams, $moveToTrash);
         // delete tags for the entity
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus(ts("Selected Activity has been deleted successfully."));
         return;
     }
     // store the submitted values in an array
     if (!$params) {
         $params = $this->controller->exportValues($this->_name);
     }
     //set activity type id
     if (!CRM_Utils_Array::value('activity_type_id', $params)) {
         $params['activity_type_id'] = $this->_activityTypeId;
     }
     if (CRM_Utils_Array::value('hidden_custom', $params) && !isset($params['custom'])) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_activityId, 'Activity');
     }
     // store the date with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     // assigning formated value to related variable
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         $params['target_contact_id'] = explode(',', $params['target_contact_id']);
     } else {
         $params['target_contact_id'] = array();
     }
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = array();
     }
     // get ids for associated contacts
     if (!$params['source_contact_id']) {
         $params['source_contact_id'] = $this->_currentUserId;
     } else {
         $params['source_contact_id'] = $this->_submitValues['source_contact_qid'];
     }
     if (isset($this->_activityId)) {
         $params['id'] = $this->_activityId;
     }
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity', $this->_activityId);
     // format target params
     if (!$this->_single) {
         $params['target_contact_id'] = $this->_contactIds;
     }
     $activityAssigned = array();
     // format assignee params
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
         //skip those assignee contacts which are already assigned
         //while sending a copy.CRM-4509.
         $activityAssigned = array_flip($params['assignee_contact_id']);
         if ($this->_activityId) {
             $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($this->_activityId);
             $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
         }
     }
     // call begin post process. Idea is to let injecting file do
     // any processing before the activity is added/updated.
     $this->beginPostProcess($params);
     $activity = CRM_Activity_BAO_Activity::create($params);
     // add tags if exists
     $tagParams = array();
     if (!empty($params['tag'])) {
         foreach ($params['tag'] as $tag) {
             $tagParams[$tag] = 1;
         }
     }
     //save static tags
     CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);
     //save free tags
     if (isset($params['activity_taglist']) && !empty($params['activity_taglist'])) {
         CRM_Core_Form_Tag::postProcess($params['activity_taglist'], $activity->id, 'civicrm_activity', $this);
     }
     // call end post process. Idea is to let injecting file do any
     // processing needed, after the activity has been added/updated.
     $this->endPostProcess($params, $activity);
     // CRM-9590
     $this->_activityId = $activity->id;
     // create follow up activity if needed
     $followupStatus = '';
     if (CRM_Utils_Array::value('followup_activity_type_id', $params)) {
         $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
         $followupStatus = ts('A followup activity has been scheduled.');
     }
     // send copy to assignee contacts.CRM-4509
     $mailStatus = '';
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id']) && CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
         $mailToContacts = array();
         $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activity->id, TRUE, FALSE);
         //build an associative array with unique email addresses.
         foreach ($activityAssigned as $id => $dnc) {
             if (isset($id) && array_key_exists($id, $assigneeContacts)) {
                 $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
             }
         }
         if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
             //include attachments while sendig a copy of activity.
             $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
             // CRM-8400 add param with _currentlyViewedContactId for URL link in mail
             $result = CRM_Case_BAO_Case::sendActivityCopy(NULL, $activity->id, $mailToContacts, $attachments, NULL);
             $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
         }
     }
     // set status message
     if (CRM_Utils_Array::value('subject', $params)) {
         $params['subject'] = "'" . $params['subject'] . "'";
     }
     CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2. %3', array(1 => $params['subject'], 2 => $followupStatus, 3 => $mailStatus)));
     return array('activity' => $activity);
 }
 /**
  * Add fields to $profileAddressFields as appropriate.
  * profileAddressFields is assigned to the template to tell it
  * what fields are in the profile address
  * that potentially should be copied to the Billing fields
  * we want to give precedence to 
  *   1) Billing & 
  *   2) then Primary designated as 'Primary
  *   3) location_type is primary
  *   4) if none of these apply then it just uses the first one
  *   
  *   as this will be used to
  * transfer profile address data to billing fields
  * http://issues.civicrm.org/jira/browse/CRM-5869
  * @param string $key Field key - e.g. street_address-Primary, first_name
  * @params array $profileAddressFields array of profile fields that relate to address fields
  */
 static function assignAddressField($key, &$profileAddressFields)
 {
     $billing_id = CRM_Core_BAO_LocationType::getBilling();
     list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
     //check for valid fields ( fields that are present in billing block )
     $validBillingFields = array('first_name', 'middle_name', 'last_name', 'street_address', 'supplemental_address_1', 'city', 'state_province', 'postal_code', 'country');
     if (!in_array($prefixName, $validBillingFields)) {
         return;
     }
     if (!empty($index) && (!CRM_Utils_array::value($prefixName, $profileAddressFields) || $index == $billing_id || $index == 'Primary' && $profileAddressFields[$prefixName] != $billing_id || $index == CRM_Core_BAO_LocationType::getDefault()->id && $profileAddressFields[$prefixName] != $billing_id && $profileAddressFields[$prefixName] != 'Primary')) {
         $profileAddressFields[$prefixName] = $index;
     }
 }
 /** 
  * global form rule 
  * 
  * @param array $fields  the input form values 
  * @param array $files   the uploaded files if any 
  * @param array $options additional user data 
  * 
  * @return true if no errors, else array of errors 
  * @access public 
  * @static 
  */
 static function formRule($fields, $files, $self)
 {
     $errors = array();
     $amount = self::computeAmount($fields, $self);
     //check for atleast one pricefields should be selected
     if (CRM_Utils_Array::value('priceSetId', $fields)) {
         $priceField = new CRM_Price_DAO_Field();
         $priceField->price_set_id = $fields['priceSetId'];
         $priceField->find();
         $check = array();
         while ($priceField->fetch()) {
             if (!empty($fields["price_{$priceField->id}"])) {
                 $check[] = $priceField->id;
             }
         }
         if (empty($check)) {
             if ($self->_useForMember == 1) {
                 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
             } else {
                 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
             }
         }
         require_once 'CRM/Price/BAO/Set.php';
         if ($self->_useForMember == 1 && !empty($check)) {
             $priceFieldIDS = array();
             $priceFieldMemTypes = array();
             foreach ($self->_priceSet['fields'] as $priceId => $value) {
                 if (!empty($fields['price_' . $priceId])) {
                     if (is_array($fields['price_' . $priceId])) {
                         foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
                             if ($isSet) {
                                 $priceFieldIDS[] = $priceFldVal;
                             }
                         }
                     } else {
                         $priceFieldIDS[] = $fields['price_' . $priceId];
                     }
                     if (CRM_Utils_Array::value('options', $value)) {
                         foreach ($value['options'] as $val) {
                             if (CRM_Utils_Array::value('membership_type_id', $val)) {
                                 $priceFieldMemTypes[] = $val['membership_type_id'];
                             }
                         }
                     }
                 }
             }
             $ids = implode(',', $priceFieldIDS);
             $priceFieldIDS['id'] = $fields['priceSetId'];
             $self->set('memberPriceFieldIDS', $priceFieldIDS);
             $count = CRM_Price_BAO_Set::getMembershipCount($ids);
             foreach ($count as $id => $occurance) {
                 if ($occurance > 1) {
                     $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
                 }
             }
             if (empty($priceFieldMemTypes)) {
                 $errors['_qf_default'] = ts('Please select at least one membership option.');
             }
         }
         CRM_Price_BAO_Set::processAmount($self->_values['fee'], $fields, $lineItem);
         if ($fields['amount'] < 0) {
             $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
         }
         $amount = $fields['amount'];
     }
     if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks' && $self->_values['amount_block_is_active']) {
         require_once 'CRM/Contribute/DAO/Product.php';
         require_once 'CRM/Utils/Money.php';
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $fields['selectProduct'];
         $productDAO->find(true);
         $min_amount = $productDAO->min_contribution;
         if ($amount < $min_amount) {
             $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
         }
     }
     if ($self->_values['honor_block_is_active'] && CRM_Utils_Array::value('honor_type_id', $fields)) {
         // make sure there is a first name and last name if email is not there
         if (!CRM_Utils_Array::value('honor_email', $fields)) {
             if (!CRM_Utils_Array::value('honor_first_name', $fields) || !CRM_Utils_Array::value('honor_last_name', $fields)) {
                 $errors['honor_last_name'] = ts('In Honor Of - First Name and Last Name, OR an Email Address is required.');
             }
         }
     }
     if (isset($fields['is_recur']) && $fields['is_recur']) {
         if ($fields['frequency_interval'] <= 0) {
             $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
         }
         if ($fields['frequency_unit'] == '0') {
             $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).');
         }
     }
     if (CRM_Utils_Array::value('is_recur', $fields) && $fields['is_pay_later']) {
         $errors['is_pay_later'] = ' ';
         $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
     }
     if (CRM_Utils_Array::value('is_for_organization', $fields) && !property_exists($self, 'organizationName')) {
         if (!CRM_Utils_Array::value('organization_name', $fields['onbehalf'])) {
             if (CRM_Utils_Array::value('org_option', $fields) && !$fields['onbehalfof_id']) {
                 $errors['organization_id'] = ts('Please select an organization or enter a new one.');
             } else {
                 if (!CRM_Utils_Array::value('org_option', $fields)) {
                     $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.');
                 }
             }
         }
         foreach ($fields['onbehalf'] as $key => $value) {
             if (strstr($key, 'email')) {
                 $emailLocType = explode('-', $key);
             }
         }
         if (!CRM_Utils_Array::value("email-{$emailLocType[1]}", $fields['onbehalf'])) {
             $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.');
         }
     }
     if (CRM_Utils_Array::value('selectMembership', $fields) && $fields['selectMembership'] != 'no_thanks') {
         require_once 'CRM/Member/BAO/Membership.php';
         require_once 'CRM/Member/BAO/MembershipType.php';
         if (!empty($self->_membershipTypeValues)) {
             $memTypeDetails = $self->_membershipTypeValues[$fields['selectMembership']];
         } else {
             $memTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($self, $fields['selectMembership']);
         }
         if ($self->_values['amount_block_is_active'] && !CRM_Utils_Array::value('is_separate_payment', $self->_membershipBlock)) {
             require_once 'CRM/Utils/Money.php';
             if ($amount < CRM_Utils_Array::value('minimum_fee', $memTypeDetails)) {
                 $errors['selectMembership'] = ts('The Membership you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($memTypeDetails['minimum_fee'])));
             }
         } else {
             if (CRM_Utils_Array::value('minimum_fee', $memTypeDetails)) {
                 // we dont have an amount, so lets get an amount for cc checks
                 $amount = $memTypeDetails['minimum_fee'];
             }
         }
     }
     if ($self->_values['is_monetary']) {
         //validate other amount.
         $checkOtherAmount = false;
         if (CRM_Utils_Array::value('amount', $fields) == 'amount_other_radio' || CRM_Utils_Array::value('amount_other', $fields)) {
             $checkOtherAmount = true;
         }
         $otherAmountVal = CRM_Utils_Array::value('amount_other', $fields);
         if ($checkOtherAmount || $otherAmountVal) {
             if (!$otherAmountVal) {
                 $errors['amount_other'] = ts('Amount is required field.');
             }
             //validate for min and max.
             if ($otherAmountVal) {
                 $min = CRM_Utils_Array::value('min_amount', $self->_values);
                 $max = CRM_Utils_Array::value('max_amount', $self->_values);
                 if ($min && $otherAmountVal < $min) {
                     $errors['amount_other'] = ts('Contribution amount must be at least %1', array(1 => $min));
                 }
                 if ($max && $otherAmountVal > $max) {
                     $errors['amount_other'] = ts('Contribution amount cannot be more than %1.', array(1 => $max));
                 }
             }
         }
     }
     // validate PCP fields - if not anonymous, we need a nick name value
     if ($self->_pcpId && CRM_Utils_Array::value('pcp_display_in_roll', $fields) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') {
         $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
     }
     // return if this is express mode
     $config = CRM_Core_Config::singleton();
     if ($self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
         if (CRM_Utils_Array::value($self->_expressButtonName . '_x', $fields) || CRM_Utils_Array::value($self->_expressButtonName . '_y', $fields) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) {
             return $errors;
         }
     }
     //validate the pledge fields.
     if (CRM_Utils_Array::value('pledge_block_id', $self->_values)) {
         //validation for pledge payment.
         if (CRM_Utils_Array::value('pledge_id', $self->_values)) {
             if (empty($fields['pledge_amount'])) {
                 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
             }
         } else {
             if (CRM_Utils_Array::value('is_pledge', $fields)) {
                 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == false) {
                     $errors['pledge_installments'] = ts('Please enter a valid pledge installment.');
                 } else {
                     if (CRM_Utils_Array::value('pledge_installments', $fields) == null) {
                         $errors['pledge_installments'] = ts('Pledge Installments is required field.');
                     } else {
                         if (CRM_Utils_array::value('pledge_installments', $fields) == 1) {
                             $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
                         } else {
                             if (CRM_Utils_array::value('pledge_installments', $fields) == 0) {
                                 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
                             }
                         }
                     }
                 }
                 //validation for Pledge Frequency Interval.
                 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == false) {
                     $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
                 } else {
                     if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == null) {
                         $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
                     } else {
                         if (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) {
                             $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
                         }
                     }
                 }
             }
         }
     }
     // also return if paylater mode
     if (CRM_Utils_Array::value('is_pay_later', $fields)) {
         return empty($errors) ? true : $errors;
     }
     // if the user has chosen a free membership or the amount is less than zero
     // i.e. we skip calling the payment processor and hence dont need credit card
     // info
     if ((double) $amount <= 0.0) {
         return $errors;
     }
     foreach ($self->_fields as $name => $fld) {
         if ($fld['is_required'] && CRM_Utils_System::isNull(CRM_Utils_Array::value($name, $fields))) {
             $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title']));
         }
     }
     // make sure that credit card number and cvv are valid
     require_once 'CRM/Utils/Rule.php';
     if (CRM_Utils_Array::value('credit_card_type', $fields)) {
         if (CRM_Utils_Array::value('credit_card_number', $fields) && !CRM_Utils_Rule::creditCardNumber($fields['credit_card_number'], $fields['credit_card_type'])) {
             $errors['credit_card_number'] = ts('Please enter a valid Credit Card Number');
         }
         if (CRM_Utils_Array::value('cvv2', $fields) && !CRM_Utils_Rule::cvv($fields['cvv2'], $fields['credit_card_type'])) {
             $errors['cvv2'] = ts('Please enter a valid Credit Card Verification Number');
         }
     }
     $elements = array('email_greeting' => 'email_greeting_custom', 'postal_greeting' => 'postal_greeting_custom', 'addressee' => 'addressee_custom');
     foreach ($elements as $greeting => $customizedGreeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
             if ($customizedValue == $greetingType && !CRM_Utils_Array::value($customizedGreeting, $fields)) {
                 $errors[$customizedGreeting] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting))));
             }
         }
     }
     return empty($errors) ? true : $errors;
 }
 /**
  * takes an associative array and creates a membership object
  *
  * the function extracts all the params it needs to initialize the created
  * membership object. The params array could contain additional unused name/value
  * pairs
  *
  * @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_Member_BAO_Membership object
  * @access public
  * @static
  */
 static function &add(&$params, &$ids)
 {
     // get activity types for use in activity record creation
     $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
     if (CRM_Utils_Array::value('membership', $ids)) {
         CRM_Utils_Hook::pre('edit', 'Membership', $ids['membership'], $params);
         $oldStatus = NULL;
         $oldType = NULL;
         $membershipObj = new CRM_Member_DAO_Membership();
         $membershipObj->id = $ids['membership'];
         $membershipObj->find();
         while ($membershipObj->fetch()) {
             $oldStatus = $membershipObj->status_id;
             $oldType = $membershipObj->membership_type_id;
         }
     } else {
         CRM_Utils_Hook::pre('create', 'Membership', NULL, $params);
     }
     if (array_key_exists('reminder_date', $params) && !$params['reminder_date']) {
         $params['reminder_date'] = 'null';
     }
     if (array_key_exists('is_override', $params) && !$params['is_override']) {
         $params['is_override'] = 'null';
     }
     $membership = new CRM_Member_BAO_Membership();
     $membership->copyValues($params);
     $membership->id = CRM_Utils_Array::value('membership', $ids);
     $membership->save();
     $membership->free();
     $session = CRM_Core_Session::singleton();
     if (empty($membership->contact_id) || empty($membership->status_id)) {
         // this means we are in renewal mode and are just updating the membership
         // record or this is an API update call and all fields are not present in the update record
         // however the hooks dont care and want all data CRM-7784
         $tempMembership = new CRM_Member_DAO_Membership();
         $tempMembership->id = $membership->id;
         $tempMembership->find(TRUE);
         $membership = $tempMembership;
     }
     //get the log start date.
     //it is set during renewal of membership.
     $logStartDate = CRM_Utils_array::value('log_start_date', $params);
     $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : CRM_Utils_Date::isoToMysql($membership->start_date);
     $values = self::getStatusANDTypeValues($membership->id);
     $membershipLog = array('membership_id' => $membership->id, 'status_id' => $membership->status_id, 'start_date' => $logStartDate, 'end_date' => CRM_Utils_Date::isoToMysql($membership->end_date), 'renewal_reminder_date' => CRM_Utils_Date::isoToMysql($membership->reminder_date), 'modified_date' => date('Ymd'), 'membership_type_id' => $values[$membership->id]['membership_type_id']);
     $session = CRM_Core_Session::singleton();
     // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
     if ($session->get('userID')) {
         $membershipLog['modified_id'] = $session->get('userID');
     } elseif (!empty($ids['userId'])) {
         $membershipLog['modified_id'] = $ids['userId'];
     } else {
         $membershipLog['modified_id'] = $membership->contact_id;
     }
     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
     // reset the group contact cache since smart groups might be affected due to this
     CRM_Contact_BAO_GroupContactCache::remove();
     if (CRM_Utils_Array::value('membership', $ids)) {
         if ($membership->status_id != $oldStatus) {
             $allStatus = CRM_Member_PseudoConstant::membershipStatus();
             $activityParam = array('subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}", 'source_contact_id' => $membershipLog['modified_id'], 'target_contact_id' => $membership->contact_id, 'source_record_id' => $membership->id, 'activity_type_id' => array_search('Change Membership Status', $activityTypes), 'status_id' => 2, 'version' => 3, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s'), 'is_auto' => 0, 'is_current_revision' => 1, 'is_deleted' => 0);
             $activityResult = civicrm_api('activity', 'create', $activityParam);
         }
         if (isset($membership->membership_type_id) && $membership->membership_type_id != $oldType) {
             $membershipTypes = CRM_Member_PseudoConstant::membershipType();
             $activityParam = array('subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}", 'source_contact_id' => $membershipLog['modified_id'], 'target_contact_id' => $membership->contact_id, 'source_record_id' => $membership->id, 'activity_type_id' => array_search('Change Membership Type', $activityTypes), 'status_id' => 2, 'version' => 3, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s'), 'is_auto' => 0, 'is_current_revision' => 1, 'is_deleted' => 0);
             $activityResult = civicrm_api('activity', 'create', $activityParam);
         }
         CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
     } else {
         CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership);
     }
     return $membership;
 }
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = null;
         //block deleting activities which affects
         //case attributes.CRM-4543
         $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
         $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', false, false, false, $activityCondition);
         if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
             $params = array('id' => $this->_activityId);
             $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, true);
             if ($activityDelete) {
                 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
             }
         } else {
             $statusMsg = ts("Selected Activity cannot be deleted.");
         }
         require_once 'CRM/Core/BAO/EntityTag.php';
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = null;
         $params = array('id' => $this->_activityId);
         $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
         if ($activityRestore) {
             $statusMsg = ts('The selected activity has been restored.<br />');
         }
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     if ($params['source_contact_id']) {
         $params['source_contact_id'] = $params['source_contact_qid'];
     }
     //set parent id if its edit mode
     if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
         $params['parent_id'] = $parentId;
     }
     // required for status msg
     $recordStatus = 'created';
     // store the dates with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     $params['activity_type_id'] = $this->_activityTypeId;
     require_once 'CRM/Case/XMLProcessor/Process.php';
     $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
     $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
     $this->assign('multiClient', $isMultiClient);
     $targetContacts = array($this->_currentlyViewedContactId);
     if (CRM_Utils_Array::value('hidden_target_contact', $params) && CRM_Utils_Array::value('target_contact_id', $params)) {
         $targetContacts = array_unique(explode(',', $params['target_contact_id']));
     }
     $params['target_contact_id'] = $targetContacts;
     // format activity custom data
     if (CRM_Utils_Array::value('hidden_custom', $params)) {
         if ($this->_activityId) {
             // unset custom fields-id from params since we want custom
             // fields to be saved for new activity.
             foreach ($params as $key => $value) {
                 $match = array();
                 if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) {
                     $params[$match[1] . '-1'] = $params[$key];
                     // for autocomplete transfer hidden value instead of label
                     if ($params[$key] && isset($params[$key . '_id'])) {
                         $params[$match[1] . '-1_id'] = $params[$key . '_id'];
                         unset($params[$key . '_id']);
                     }
                     unset($params[$key]);
                 }
             }
         }
         // build custom data getFields array
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', false, false, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', false, false, null, null, true));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_activityId, 'Activity');
     }
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         $assineeContacts = explode(',', $params['assignee_contact_id']);
         $assineeContacts = array_unique($assineeContacts);
         unset($params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = $assineeContacts = array();
     }
     if (isset($this->_activityId)) {
         // activity which hasn't been modified by a user yet
         if ($this->_defaults['is_auto'] == 1) {
             $params['is_auto'] = 0;
         }
         // always create a revision of an case activity. CRM-4533
         $newActParams = $params;
         // add target contact values in update mode
         if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
             $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
         }
         // record status for status msg
         $recordStatus = 'updated';
     }
     if (!isset($newActParams)) {
         // add more attachments if needed for old activity
         CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($params);
         $params['case_id'] = $this->_caseId;
         // activity create/update
         $activity = CRM_Activity_BAO_Activity::create($params);
         // call end post process, after the activity has been created/updated.
         $this->endPostProcess($params, $activity);
     } else {
         // since the params we need to set are very few, and we don't want rest of the
         // work done by bao create method , lets use dao object to make the changes
         $params = array('id' => $this->_activityId);
         $params['is_current_revision'] = 0;
         $activity = new CRM_Activity_DAO_Activity();
         $activity->copyValues($params);
         $activity->save();
     }
     // create a new version of activity if activity was found to
     // have been modified/created by user
     if (isset($newActParams)) {
         // set proper original_id
         if (CRM_Utils_Array::value('original_id', $this->_defaults)) {
             $newActParams['original_id'] = $this->_defaults['original_id'];
         } else {
             $newActParams['original_id'] = $activity->id;
         }
         //is_current_revision will be set to 1 by default.
         // add attachments if any
         CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($newActParams);
         $newActParams['case_id'] = $this->_caseId;
         $activity = CRM_Activity_BAO_Activity::create($newActParams);
         // call end post process, after the activity has been created/updated.
         $this->endPostProcess($newActParams, $activity);
         // copy files attached to old activity if any, to new one,
         // as long as users have not selected the 'delete attachment' option.
         if (!CRM_Utils_Array::value('is_delete_attachment', $newActParams)) {
             CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id);
         }
         // copy back params to original var
         $params = $newActParams;
     }
     if ($activity->id) {
         // add tags if exists
         $tagParams = array();
         if (!empty($params['tag'])) {
             foreach ($params['tag'] as $tag) {
                 $tagParams[$tag] = 1;
             }
         }
         //save static tags
         require_once 'CRM/Core/BAO/EntityTag.php';
         CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);
         //save free tags
         if (isset($params['taglist']) && !empty($params['taglist'])) {
             require_once 'CRM/Core/Form/Tag.php';
             CRM_Core_Form_Tag::postProcess($params['taglist'], $activity->id, 'civicrm_activity', $this);
         }
     }
     $params['assignee_contact_id'] = $assineeContacts;
     // update existing case record if needed
     $caseParams = $params;
     $caseParams['id'] = $this->_caseId;
     if (CRM_Utils_Array::value('case_type_id', $caseParams)) {
         $caseParams['case_type_id'] = CRM_Case_BAO_Case::VALUE_SEPERATOR . $caseParams['case_type_id'] . CRM_Case_BAO_Case::VALUE_SEPERATOR;
     }
     if (CRM_Utils_Array::value('case_status_id', $caseParams)) {
         $caseParams['status_id'] = $caseParams['case_status_id'];
     }
     // unset params intended for activities only
     unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']);
     $case = CRM_Case_BAO_Case::create($caseParams);
     // create case activity record
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $this->_caseId);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     // create activity assignee records
     $assigneeParams = array('activity_id' => $activity->id);
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
         //skip those assignee contacts which are already assigned
         //while sending a copy.CRM-4509.
         $activityAssigned = array_flip($params['assignee_contact_id']);
         $activityId = isset($this->_activityId) ? $this->_activityId : $activity->id;
         $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityId);
         $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
         foreach ($params['assignee_contact_id'] as $key => $id) {
             $assigneeParams['assignee_contact_id'] = $id;
             CRM_Activity_BAO_Activity::createActivityAssignment($assigneeParams);
         }
         //modify assigne_contact as per newly assigned contact before sending copy. CRM-4509.
         $params['assignee_contact_id'] = $activityAssigned;
     }
     // Insert civicrm_log record for the activity (e.g. store the
     // created / edited by contact id and date for the activity)
     // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
     // send copy to selected contacts.
     $mailStatus = '';
     $mailToContacts = array();
     //CRM-5695
     //check for notification settings for assignee contacts
     $selectedContacts = array('contact_check');
     $config =& CRM_Core_Config::singleton();
     if ($config->activityAssigneeNotification) {
         $selectedContacts[] = 'assignee_contact_id';
     }
     foreach ($selectedContacts as $dnt => $val) {
         if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) {
             if ($val == 'contact_check') {
                 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
             } else {
                 $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activity->id, true, false);
                 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
             }
             //build an associative array with unique email addresses.
             foreach ($params[$val] as $id => $dnc) {
                 if (isset($id) && array_key_exists($id, $this->_relatedContacts)) {
                     //if email already exists in array then append with ', ' another role only otherwise add it to array.
                     if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
                         $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
                         $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
                     } else {
                         $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
                     }
                 }
             }
         }
     }
     if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
         //include attachments while sendig a copy of activity.
         $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
         $result = CRM_Case_BAO_Case::sendActivityCopy($this->_currentlyViewedContactId, $activity->id, $mailToContacts, $attachments, $this->_caseId);
         if (empty($result)) {
             $mailStatus = '';
         }
     } else {
         $mailStatus = '';
     }
     // create follow up activity if needed
     $followupStatus = '';
     if (CRM_Utils_Array::value('followup_activity_type_id', $params)) {
         $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
         if ($followupActivity) {
             $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $this->_caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
             $followupStatus = ts("A followup activity has been scheduled.");
         }
     }
     CRM_Core_Session::setStatus(ts("'%1' activity has been %2. %3 %4", array(1 => $this->_activityTypeName, 2 => $recordStatus, 3 => $followupStatus, 4 => $mailStatus)));
 }
 /**
  * A function to build an array of information required by merge function and the merge UI.
  *
  * @param  int     $mainId         main contact with whom merge has to happen
  * @param  int     $otherId        duplicate contact which would be deleted after merge operation
  *
  * @static
  * @access public
  */
 static function getRowsElementsAndInfo($mainId, $otherId)
 {
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     // Fetch contacts
     foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
         $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
         $result = civicrm_api('contact', 'get', $params);
         if (empty($result['values'][$cid]['contact_type'])) {
             return FALSE;
         }
         ${$moniker} = $result['values'][$cid];
     }
     static $fields = array();
     if (empty($fields)) {
         $fields = CRM_Contact_DAO_Contact::fields();
         CRM_Core_DAO::freeResult();
     }
     // FIXME: there must be a better way
     foreach (array('main', 'other') as $moniker) {
         $contact =& ${$moniker};
         $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
         $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
         $specialValues[$moniker] = array('preferred_communication_method' => $value);
         if (!empty($contact['preferred_communication_method'])) {
             // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
             $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
             $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
         }
         $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method'));
         CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
     }
     static $optionValueFields = array();
     if (empty($optionValueFields)) {
         $optionValueFields = CRM_Core_OptionValue::getFields();
     }
     foreach ($optionValueFields as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     $diffs = self::findDifferences($main, $other);
     $rows = $elements = $relTableElements = $migrationInfo = array();
     foreach ($diffs['contact'] as $field) {
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
                 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
             }
             $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
                 if ($label === '0') {
                     $label = ts('[ ]');
                 }
                 if ($label === '1') {
                     $label = ts('[x]');
                 }
             } elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
                 $label = CRM_Utils_Array::value('prefix', $contact);
                 $value = CRM_Utils_Array::value('prefix_id', $contact);
                 $field = 'prefix_id';
             } elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
                 $label = CRM_Utils_Array::value('suffix', $contact);
                 $value = CRM_Utils_Array::value('suffix_id', $contact);
                 $field = 'suffix_id';
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 if ($value === NULL) {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $qfZeroBug;
                 }
                 if (is_array($value) && empty($value[1])) {
                     $value[1] = NULL;
                 }
                 $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value);
                 $migrationInfo["move_{$field}"] = $value;
             }
         }
         $rows["move_{$field}"]['title'] = $fields[$field]['title'];
     }
     // handle location blocks.
     $locationBlocks = array('email', 'phone', 'address');
     $locations = array();
     foreach ($locationBlocks as $block) {
         foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
             $cnt = 1;
             $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
             $count = $values['count'];
             if ($count) {
                 if ($count > $cnt) {
                     foreach ($values['values'] as $value) {
                         if ($block == 'address') {
                             CRM_Core_BAO_Address::fixAddress($value);
                             $display = CRM_Utils_Address::format($value);
                             $locations[$moniker][$block][$cnt] = $value;
                             $locations[$moniker][$block][$cnt]['display'] = $display;
                         } else {
                             $locations[$moniker][$block][$cnt] = $value;
                         }
                         $cnt++;
                     }
                 } else {
                     $id = $values['id'];
                     if ($block == 'address') {
                         CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
                         $display = CRM_Utils_Address::format($values['values'][$id]);
                         $locations[$moniker][$block][$cnt] = $values['values'][$id];
                         $locations[$moniker][$block][$cnt]['display'] = $display;
                     } else {
                         $locations[$moniker][$block][$cnt] = $values['values'][$id];
                     }
                 }
             }
         }
     }
     $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $mainLocBlock = $locBlockIds = array();
     $locBlockIds['main'] = $locBlockIds['other'] = array();
     foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
         $name = strtolower($block);
         foreach (array('main', 'other') as $moniker) {
             $locIndex = CRM_Utils_Array::value($moniker, $locations);
             $blockValue = CRM_Utils_Array::value($name, $locIndex, array());
             if (empty($blockValue)) {
                 $locValue[$moniker][$name] = 0;
                 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
             } else {
                 $locValue[$moniker][$name] = TRUE;
                 foreach ($blockValue as $count => $blkValues) {
                     $fldName = $name;
                     $locTypeId = $blkValues['location_type_id'];
                     if ($name == 'im') {
                         $fldName = 'name';
                     }
                     if ($name == 'address') {
                         $fldName = 'display';
                     }
                     $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName, $blkValues);
                     $locTypes[$moniker][$name][$count] = $locTypeId;
                     if ($moniker == 'main' && in_array($name, $locationBlocks)) {
                         $mainLocBlock["main_{$name}{$locTypeId}"] = CRM_Utils_Array::value($fldName, $blkValues);
                         $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
                     } else {
                         $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
                     }
                 }
             }
         }
         if ($locValue['other'][$name] != 0) {
             foreach ($locLabel['other'][$name] as $count => $value) {
                 $locTypeId = $locTypes['other'][$name][$count];
                 $rows["move_location_{$name}_{$count}"]['other'] = $value;
                 $rows["move_location_{$name}_{$count}"]['main'] = CRM_Utils_Array::value($count, $locLabel['main'][$name]);
                 $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId]));
                 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
                 $migrationInfo["move_location_{$name}_{$count}"] = 1;
                 // make sure default location type is always on top
                 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
                 $locTypeValues = $allLocationTypes;
                 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
                 unset($locTypeValues[$mainLocTypeId]);
                 // keep 1-1 mapping for address - location type.
                 $js = NULL;
                 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
                     $js = array('onChange' => "mergeBlock('{$name}', this, {$count} );");
                 }
                 $elements[] = array('select', "location[{$name}][{$count}][locTypeId]", NULL, $defaultLocType + $locTypeValues, $js);
                 // keep location-type-id same as that of other-contact
                 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
                 if ($name != 'address') {
                     $elements[] = array('advcheckbox', "location[{$name}][{$count}][operation]", NULL, ts('add new'));
                     // always use add operation
                     $migrationInfo['location'][$name][$count]['operation'] = 1;
                 }
             }
         }
     }
     // add the related tables and unset the ones that don't sport any of the duplicate contact's info
     $config = CRM_Core_Config::singleton();
     $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
     $mainUser = NULL;
     if ($mainUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $mainUser = user_load($mainUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $mainUser = JFactory::getUser($mainUfId);
         }
     }
     $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
     $otherUser = NULL;
     if ($otherUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $otherUser = user_load($otherUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $otherUser = JFactory::getUser($otherUfId);
         }
     }
     $relTables = CRM_Dedupe_Merger::relTables();
     $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
     $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
     foreach ($relTables as $name => $null) {
         if (!in_array($name, $activeRelTables) && !($name == 'rel_table_users' && in_array($name, $activeMainRelTables))) {
             unset($relTables[$name]);
             continue;
         }
         $relTableElements[] = array('checkbox', "move_{$name}");
         $migrationInfo["move_{$name}"] = 1;
         $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
         $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
         if ($name == 'rel_table_users') {
             $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
             $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
             $find = array('$ufid', '$ufname');
             if ($mainUser) {
                 $replace = array($mainUfId, $mainUser->name);
                 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
             if ($otherUser) {
                 $replace = array($otherUfId, $otherUser->name);
                 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
         }
         if ($name == 'rel_table_memberships') {
             $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
             $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
         }
     }
     foreach ($relTables as $name => $null) {
         $relTables["move_{$name}"] = $relTables[$name];
         unset($relTables[$name]);
     }
     // handle custom fields
     $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, CRM_Utils_Array::value('contact_sub_type', $main));
     $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, CRM_Utils_Array::value('contact_sub_type', $other));
     CRM_Core_DAO::freeResult();
     foreach ($otherTree as $gid => $group) {
         $foundField = FALSE;
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             if (in_array($fid, $diffs['custom'])) {
                 if (!$foundField) {
                     $rows["custom_group_{$gid}"]['title'] = $group['title'];
                     $foundField = TRUE;
                 }
                 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                     }
                 }
                 $value = "null";
                 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                         if ($values['data'] === 0 || $values['data'] === '0') {
                             $values['data'] = $qfZeroBug;
                         }
                         $value = $values['data'] ? $values['data'] : $value;
                     }
                 }
                 $rows["move_custom_{$fid}"]['title'] = $field['label'];
                 $elements[] = array('advcheckbox', "move_custom_{$fid}", NULL, NULL, NULL, $value);
                 $migrationInfo["move_custom_{$fid}"] = $value;
             }
         }
     }
     $result = array('rows' => $rows, 'elements' => $elements, 'rel_table_elements' => $relTableElements, 'main_loc_block' => $mainLocBlock, 'rel_tables' => $relTables, 'main_details' => $main, 'other_details' => $other, 'migration_info' => $migrationInfo);
     $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
     $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
     return $result;
 }
 static function sendMailings($mappingID, $now)
 {
     $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
     $fromEmailAddress = "{$domainValues['0']} <{$domainValues['1']}>";
     $mapping = new CRM_Core_DAO_ActionMapping();
     $mapping->id = $mappingID;
     $mapping->find(TRUE);
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->mapping_id = $mappingID;
     $actionSchedule->is_active = 1;
     $actionSchedule->find(FALSE);
     $tokenFields = array();
     $session = CRM_Core_Session::singleton();
     while ($actionSchedule->fetch()) {
         $extraSelect = $extraJoin = $extraWhere = '';
         if ($actionSchedule->record_activity) {
             if ($mapping->entity == 'civicrm_membership') {
                 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
             } else {
                 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
             }
             $activityStatusID = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
         }
         if ($mapping->entity == 'civicrm_activity') {
             $tokenEntity = 'activity';
             $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
             $extraSelect = ", ov.label as activity_type, e.id as activity_id";
             $extraJoin = "INNER JOIN civicrm_option_group og ON og.name = 'activity_type'\nINNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
             $extraWhere = "AND e.is_current_revision = 1 AND e.is_deleted = 0";
         }
         if ($mapping->entity == 'civicrm_participant') {
             $tokenEntity = 'event';
             $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone');
             $extraSelect = ", ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone  ";
             $extraJoin = "\nINNER JOIN civicrm_event ev ON e.event_id = ev.id\nINNER JOIN civicrm_option_group og ON og.name = 'event_type'\nINNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT  JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT  JOIN civicrm_address address ON address.id = lb.address_id\nLEFT  JOIN civicrm_email email ON email.id = lb.email_id\nLEFT  JOIN civicrm_phone phone ON phone.id = lb.phone_id\n";
         }
         if ($mapping->entity == 'civicrm_membership') {
             $tokenEntity = 'membership';
             $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
             $extraSelect = ", mt.minimum_fee as fee, e.id as id , e.join_date, e.start_date, e.end_date, ms.name as status, mt.name as type";
             $extraJoin = "\n INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id\n INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id";
         }
         $query = "\nSELECT reminder.id as reminderID, reminder.*, e.id as entityID, e.* {$extraSelect}\nFROM  civicrm_action_log reminder\nINNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id\n{$extraJoin}\nWHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL\n{$extraWhere}";
         $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
         while ($dao->fetch()) {
             $entityTokenParams = array();
             foreach ($tokenFields as $field) {
                 if ($field == 'location') {
                     $loc = array();
                     $stateProvince = CRM_Core_PseudoConstant::stateProvince();
                     $loc['street_address'] = $dao->street_address;
                     $loc['city'] = $dao->city;
                     $loc['state_province'] = CRM_Utils_array::value($dao->state_province_id, $stateProvince);
                     $loc['postal_code'] = $dao->postal_code;
                     $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
                 } elseif ($field == 'info_url') {
                     $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                 } elseif ($field == 'registration_url') {
                     $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                 } elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
                     $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->{$field});
                 } else {
                     $entityTokenParams["{$tokenEntity}." . $field] = $dao->{$field};
                 }
             }
             $isError = 0;
             $errorMsg = '';
             $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contact_id);
             if ($toEmail) {
                 $result = CRM_Core_BAO_ActionSchedule::sendReminder($dao->contact_id, $toEmail, $actionSchedule->id, $fromEmailAddress, $entityTokenParams);
                 if (!$result || is_a($result, 'PEAR_Error')) {
                     // we could not send an email, for now we ignore, CRM-3406
                     $isError = 1;
                 }
             } else {
                 $isError = 1;
                 $errorMsg = "Couldn\\'t find recipient\\'s email address.";
             }
             // update action log record
             $logParams = array('id' => $dao->reminderID, 'is_error' => $isError, 'message' => $errorMsg ? $errorMsg : "null", 'action_date_time' => $now);
             CRM_Core_BAO_ActionLog::create($logParams);
             // insert activity log record if needed
             if ($actionSchedule->record_activity) {
                 $activityParams = array('subject' => $actionSchedule->title, 'details' => $actionSchedule->body_html, 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $dao->contact_id, 'target_contact_id' => $dao->contact_id, 'activity_date_time' => date('YmdHis'), 'status_id' => $activityStatusID, 'activity_type_id' => $activityTypeID, 'source_record_id' => $dao->entityID);
                 $activity = CRM_Activity_BAO_Activity::create($activityParams);
             }
         }
         $dao->free();
     }
 }
 /**
  * Assign the minimal set of variables to the template.
  */
 public function assignToTemplate()
 {
     $name = CRM_Utils_Array::value('billing_first_name', $this->_params);
     if (!empty($this->_params['billing_middle_name'])) {
         $name .= " {$this->_params['billing_middle_name']}";
     }
     $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
     $name = trim($name);
     $this->assign('billingName', $name);
     $this->set('name', $name);
     $this->assign('paymentProcessor', $this->_paymentProcessor);
     $vars = array('amount', 'currencyID', 'credit_card_type', 'trxn_id', 'amount_level');
     $config = CRM_Core_Config::singleton();
     if (isset($this->_values['is_recur']) && !empty($this->_paymentProcessor['is_recur'])) {
         $this->assign('is_recur_enabled', 1);
         $vars = array_merge($vars, array('is_recur', 'frequency_interval', 'frequency_unit', 'installments'));
     }
     if (in_array('CiviPledge', $config->enableComponents) && CRM_Utils_Array::value('is_pledge', $this->_params) == 1) {
         $this->assign('pledge_enabled', 1);
         $vars = array_merge($vars, array('is_pledge', 'pledge_frequency_interval', 'pledge_frequency_unit', 'pledge_installments'));
     }
     // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
     // function to get correct amount level consistently. Remove setting of the amount level in
     // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
     // to cover all variants.
     if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
         $this->_params['amount_level'] = '';
     }
     foreach ($vars as $v) {
         if (isset($this->_params[$v])) {
             if ($v == "amount" && $this->_params[$v] === 0) {
                 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
             }
             $this->assign($v, $this->_params[$v]);
         }
     }
     // assign the address formatted up for display
     $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
     $addressFields = array();
     foreach ($addressParts as $part) {
         list($n, $id) = explode('-', $part);
         $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $this->_params);
     }
     $this->assign('address', CRM_Utils_Address::format($addressFields));
     if (!empty($this->_params['onbehalf_profile_id']) && !empty($this->_params['onbehalf'])) {
         $this->assign('onBehalfName', $this->_params['organization_name']);
         $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
         $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
     }
     //fix for CRM-3767
     $assignCCInfo = FALSE;
     if ($this->_amount > 0.0) {
         $assignCCInfo = TRUE;
     } elseif (!empty($this->_params['selectMembership'])) {
         $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
         if ($memFee > 0.0) {
             $assignCCInfo = TRUE;
         }
     }
     // The concept of contributeMode is deprecated.
     // The payment processor object can provide info about the fields it shows.
     if ($this->_contributeMode == 'direct' && $assignCCInfo) {
         if ($this->_paymentProcessor && $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) {
             $this->assign('account_holder', $this->_params['account_holder']);
             $this->assign('bank_identification_number', $this->_params['bank_identification_number']);
             $this->assign('bank_name', $this->_params['bank_name']);
             $this->assign('bank_account_number', $this->_params['bank_account_number']);
         } else {
             $date = CRM_Utils_Date::format(CRM_Utils_array::value('credit_card_exp_date', $this->_params));
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard(CRM_Utils_array::value('credit_card_number', $this->_params)));
         }
     }
     $this->assign('email', $this->controller->exportValue('Main', "email-{$this->_bltID}"));
     // also assign the receipt_text
     if (isset($this->_values['receipt_text'])) {
         $this->assign('receipt_text', $this->_values['receipt_text']);
     }
 }
 /**
  * Add fields to $profileAddressFields as appropriate.
  * profileAddressFields is assigned to the template to tell it
  * what fields are in the profile address
  * that potentially should be copied to the Billing fields
  * we want to give precedence to
  *   1) Billing &
  *   2) then Primary designated as 'Primary
  *   3) location_type is primary
  *   4) if none of these apply then it just uses the first one
  *
  *   as this will be used to
  * transfer profile address data to billing fields
  * http://issues.civicrm.org/jira/browse/CRM-5869
  *
  * @param string $key Field key - e.g. street_address-Primary, first_name
  * @param array $profileAddressFields array of profile fields that relate to address fields
  * @param array $profileFilter filter to apply to profile fields - expected usage is to only fill based on
  * the bottom profile per CRM-13726
  */
 static function assignAddressField($key, &$profileAddressFields, $profileFilter)
 {
     $billing_id = CRM_Core_BAO_LocationType::getBilling();
     list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
     $profileFields = civicrm_api3('uf_field', 'get', array_merge($profileFilter, array('is_active' => 1, 'return' => 'field_name')));
     //check for valid fields ( fields that are present in billing block )
     $validBillingFields = array('first_name', 'middle_name', 'last_name', 'street_address', 'supplemental_address_1', 'city', 'state_province', 'postal_code', 'country');
     $validProfileFields = array();
     foreach ($profileFields['values'] as $field) {
         if (in_array($field['field_name'], $validBillingFields)) {
             $validProfileFields[] = $field['field_name'];
         }
     }
     if (!in_array($prefixName, $validProfileFields)) {
         return;
     }
     if (!empty($index) && (!CRM_Utils_array::value($prefixName, $profileAddressFields) || $index == $billing_id || $index == 'Primary' && $profileAddressFields[$prefixName] != $billing_id || $index == CRM_Core_BAO_LocationType::getDefault()->id && $profileAddressFields[$prefixName] != $billing_id && $profileAddressFields[$prefixName] != 'Primary')) {
         $profileAddressFields[$prefixName] = $index;
     }
 }
Exemple #19
0
 /**
  * Global form rule.
  *
  * @param array $fields
  *   The input form values.
  * @param array $files
  *   The uploaded files if any.
  * @param CRM_Core_Form $self
  *
  * @return bool|array
  *   true if no errors, else array of errors
  */
 public static function formRule($fields, $files, $self)
 {
     $errors = array();
     $amount = self::computeAmount($fields, $self->_values);
     if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) {
         $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, FALSE, TRUE);
         $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
         $unallowedOrgs = array();
         foreach (array_keys($lifeMember) as $memTypeId) {
             $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
         }
     }
     //check for atleast one pricefields should be selected
     if (!empty($fields['priceSetId'])) {
         $priceField = new CRM_Price_DAO_PriceField();
         $priceField->price_set_id = $fields['priceSetId'];
         $priceField->orderBy('weight');
         $priceField->find();
         $check = array();
         $membershipIsActive = TRUE;
         $previousId = $otherAmount = FALSE;
         while ($priceField->fetch()) {
             if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
                 $previousId = $priceField->id;
                 if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
                     $membershipIsActive = FALSE;
                 }
             }
             if ($priceField->name == 'other_amount') {
                 if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) {
                     $otherAmount = $priceField->id;
                 } elseif (!empty($fields["price_{$priceField->id}"])) {
                     $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
                     $min = CRM_Utils_Array::value('min_amount', $self->_values);
                     $max = CRM_Utils_Array::value('max_amount', $self->_values);
                     if ($min && $otherAmountVal < $min) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min));
                     }
                     if ($max && $otherAmountVal > $max) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max));
                     }
                 }
             }
             if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) {
                 $check[] = $priceField->id;
             }
         }
         $currentMemberships = NULL;
         if ($membershipIsActive) {
             $is_test = $self->_mode != 'live' ? 1 : 0;
             $memContactID = $self->_membershipContactID;
             // For anonymous user check using dedupe rule
             // if user has Cancelled Membership
             if (!$memContactID) {
                 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
                 $dedupeParams['check_permission'] = FALSE;
                 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
                 // if we find more than one contact, use the first one
                 $memContactID = CRM_Utils_Array::value(0, $ids);
             }
             $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID, $is_test);
             $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.';
             foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
                 if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) {
                     if (!is_array($fields['price_' . $fieldKey])) {
                         if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]]) && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) {
                             $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])));
                         }
                     } else {
                         foreach ($fields['price_' . $fieldKey] as $key => $ignore) {
                             if (array_key_exists('membership_type_id', $fieldValue['options'][$key]) && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) {
                                 $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id'])));
                             }
                         }
                     }
                 }
             }
         }
         // CRM-12233
         if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $self->_values['amount_block_is_active']) {
             $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
             foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
                 // if 'No thank you' membership is selected then set $membershipFieldId
                 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
                     $membershipFieldId = $fieldKey;
                 } elseif ($membershipFieldId) {
                     if ($fieldValue['name'] == 'other_amount') {
                         $otherFieldId = $fieldKey;
                     } elseif ($fieldValue['name'] == 'contribution_amount') {
                         $contributionFieldId = $fieldKey;
                     }
                     if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
                         $errorKey = $fieldKey;
                     }
                 }
             }
             // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
             if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
                 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
             }
         }
         if (empty($check)) {
             if ($self->_useForMember == 1 && $membershipIsActive) {
                 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
             } else {
                 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
             }
         }
         if ($otherAmount && !empty($check)) {
             $errors["price_{$otherAmount}"] = ts('Amount is required field.');
         }
         if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
             $priceFieldIDS = array();
             $priceFieldMemTypes = array();
             foreach ($self->_priceSet['fields'] as $priceId => $value) {
                 if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) {
                     if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
                         foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
                             if ($isSet) {
                                 $priceFieldIDS[] = $priceFldVal;
                             }
                         }
                     } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
                         // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
                         // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
                         $priceFieldIDS[] = $fields['price_' . $priceId];
                     }
                     if (!empty($value['options'])) {
                         foreach ($value['options'] as $val) {
                             if (!empty($val['membership_type_id']) && ($fields['price_' . $priceId] == $val['id'] || isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))) {
                                 $priceFieldMemTypes[] = $val['membership_type_id'];
                             }
                         }
                     }
                 }
             }
             if (!empty($lifeMember)) {
                 foreach ($priceFieldIDS as $priceFieldId) {
                     if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) {
                         $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
                         break;
                     }
                 }
             }
             if (!empty($priceFieldIDS)) {
                 $ids = implode(',', $priceFieldIDS);
                 $priceFieldIDS['id'] = $fields['priceSetId'];
                 $self->set('memberPriceFieldIDS', $priceFieldIDS);
                 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
                 foreach ($count as $id => $occurrence) {
                     if ($occurrence > 1) {
                         $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
                     }
                 }
             }
             if (empty($priceFieldMemTypes)) {
                 $errors['_qf_default'] = ts('Please select at least one membership option.');
             }
         }
         CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
         if ($fields['amount'] < 0) {
             $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
         }
         $amount = $fields['amount'];
     }
     if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') {
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $fields['selectProduct'];
         $productDAO->find(TRUE);
         $min_amount = $productDAO->min_contribution;
         if ($amount < $min_amount) {
             $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
             CRM_Core_Session::setStatus($errors['selectProduct']);
         }
     }
     //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
     CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
     if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) {
         $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
     }
     if (!empty($fields['is_for_organization']) && !property_exists($self, 'organizationName')) {
         if (empty($fields['onbehalf']['organization_name'])) {
             if (!empty($fields['org_option']) && !$fields['onbehalfof_id']) {
                 $errors['organization_id'] = ts('Please select an organization or enter a new one.');
             } elseif (empty($fields['org_option'])) {
                 $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.');
             }
         }
         foreach ($fields['onbehalf'] as $key => $value) {
             if (strstr($key, 'email')) {
                 $emailLocType = explode('-', $key);
             }
         }
         if (empty($fields['onbehalf']["email-{$emailLocType[1]}"])) {
             $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.');
         }
     }
     // validate PCP fields - if not anonymous, we need a nick name value
     if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') {
         $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
     }
     // return if this is express mode
     $config = CRM_Core_Config::singleton();
     if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
         if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) {
             return $errors;
         }
     }
     //validate the pledge fields.
     if (!empty($self->_values['pledge_block_id'])) {
         //validation for pledge payment.
         if (!empty($self->_values['pledge_id'])) {
             if (empty($fields['pledge_amount'])) {
                 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
             }
         } elseif (!empty($fields['is_pledge'])) {
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
                 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
             } else {
                 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
                     $errors['pledge_installments'] = ts('Pledge Installments is required field.');
                 } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 1) {
                     $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
                 } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 0) {
                     $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
                 }
             }
             //validation for Pledge Frequency Interval.
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
                 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
             } else {
                 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
                     $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
                 } elseif (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) {
                     $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
                 }
             }
         }
     }
     // also return if paylater mode
     if (CRM_Utils_Array::value('payment_processor_id', $fields) == 0 && $self->_isBillingAddressRequiredForPayLater == 0) {
         return empty($errors) ? TRUE : $errors;
     }
     // if the user has chosen a free membership or the amount is less than zero
     // i.e. we skip calling the payment processor and hence dont need credit card
     // info
     if ((double) $amount <= 0.0) {
         return $errors;
     }
     if (!empty($self->_paymentFields)) {
         CRM_Core_Form::validateMandatoryFields($self->_paymentFields, $fields, $errors);
     }
     CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
             if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
                 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting))));
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
 /**
  * global form rule
  *
  * @param array $fields  the input form values
  * @param array $files   the uploaded files if any
  * @param array $options additional user data
  *
  * @return true if no errors, else array of errors
  * @access public
  * @static
  */
 static function formRule($fields, $files, $self)
 {
     $errors = array();
     $amount = self::computeAmount($fields, $self);
     if (CRM_Utils_Array::value('selectMembership', $fields) && $fields['selectMembership'] != 'no_thanks' || CRM_Utils_Array::value('priceSetId', $fields) && $self->_useForMember) {
         $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_userID, FALSE, TRUE);
         $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
         $unallowedOrgs = array();
         foreach (array_keys($lifeMember) as $memTypeId) {
             $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
         }
     }
     //check for atleast one pricefields should be selected
     if (CRM_Utils_Array::value('priceSetId', $fields)) {
         $priceField = new CRM_Price_DAO_Field();
         $priceField->price_set_id = $fields['priceSetId'];
         $priceField->orderBy('weight');
         $priceField->find();
         $check = array();
         $membershipIsActive = TRUE;
         $previousId = $otherAmount = FALSE;
         while ($priceField->fetch()) {
             if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
                 $previousId = $priceField->id;
                 if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
                     $membershipIsActive = FALSE;
                 }
             }
             if ($priceField->name == 'other_amount') {
                 if ($self->_quickConfig && !CRM_Utils_Array::value("price_{$priceField->id}", $fields) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) {
                     $otherAmount = $priceField->id;
                 } elseif (!empty($fields["price_{$priceField->id}"])) {
                     $otherAmountVal = $fields["price_{$priceField->id}"];
                     $min = CRM_Utils_Array::value('min_amount', $self->_values);
                     $max = CRM_Utils_Array::value('max_amount', $self->_values);
                     if ($min && $otherAmountVal < $min) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min));
                     }
                     if ($max && $otherAmountVal > $max) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max));
                     }
                 }
             }
             if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) {
                 $check[] = $priceField->id;
             }
         }
         if (empty($check)) {
             if ($self->_useForMember == 1 && $membershipIsActive) {
                 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
             } else {
                 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
             }
         }
         if ($otherAmount && !empty($check)) {
             $errors["price_{$otherAmount}"] = ts('Amount is required field.');
         }
         if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
             $priceFieldIDS = array();
             $priceFieldMemTypes = array();
             foreach ($self->_priceSet['fields'] as $priceId => $value) {
                 if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && !CRM_Utils_Array::value('is_required', $self->_membershipBlock)) {
                     if (CRM_Utils_Array::value('price_' . $priceId, $fields) && is_array($fields['price_' . $priceId])) {
                         foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
                             if ($isSet) {
                                 $priceFieldIDS[] = $priceFldVal;
                             }
                         }
                     } elseif (!$value['is_enter_qty'] && CRM_Utils_Array::value('price_' . $priceId, $fields)) {
                         // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
                         // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
                         $priceFieldIDS[] = $fields['price_' . $priceId];
                     }
                     if (CRM_Utils_Array::value('options', $value)) {
                         foreach ($value['options'] as $val) {
                             if (CRM_Utils_Array::value('membership_type_id', $val)) {
                                 $priceFieldMemTypes[] = $val['membership_type_id'];
                             }
                         }
                     }
                 }
             }
             if (!empty($lifeMember)) {
                 foreach ($priceFieldIDS as $priceFieldId) {
                     if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_FieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) {
                         $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
                         break;
                     }
                 }
             }
             if (!empty($priceFieldIDS)) {
                 $ids = implode(',', $priceFieldIDS);
                 $priceFieldIDS['id'] = $fields['priceSetId'];
                 $self->set('memberPriceFieldIDS', $priceFieldIDS);
                 $count = CRM_Price_BAO_Set::getMembershipCount($ids);
                 foreach ($count as $id => $occurance) {
                     if ($occurance > 1) {
                         $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
                     }
                 }
             }
             if (empty($priceFieldMemTypes)) {
                 $errors['_qf_default'] = ts('Please select at least one membership option.');
             }
         }
         $fieldId = $memPresent = $membershipLabel = $fieldOption = $proceFieldAmount = NULL;
         if ($self->_separateMembershipPayment == 0 && $self->_quickConfig) {
             foreach ($self->_priceSet['fields'] as $fieldKey => $fieldVal) {
                 if ($fieldVal['name'] == 'membership_amount') {
                     $fieldId = $fieldVal['id'];
                     $fieldOption = $fields['price_' . $fieldId];
                     $memPresent = TRUE;
                 } else {
                     if (CRM_Utils_Array::value('price_' . $fieldKey, $fields) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
                         $fieldId = $fieldVal['id'];
                         if ($fieldVal['name'] == 'other_amount') {
                             $proceFieldAmount = $self->_submitValues['price_' . $fieldId];
                         } else {
                             $proceFieldAmount = $fieldVal['options'][$self->_submitValues['price_' . $fieldId]]['amount'];
                         }
                         unset($fields['price_' . $fieldId]);
                         break;
                     }
                 }
             }
         }
         CRM_Price_BAO_Set::processAmount($self->_values['fee'], $fields, $lineItem);
         if ($proceFieldAmount) {
             if ($proceFieldAmount < $lineItem[$fieldOption]['line_total']) {
                 $errors["price_{$fieldId}"] = ts('The Membership you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($lineItem[$fieldOption]['line_total'])));
             }
             $fields['amount'] = $proceFieldAmount;
         }
         if ($fields['amount'] < 0) {
             $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
         }
         $amount = $fields['amount'];
     }
     if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks' && $self->_values['amount_block_is_active']) {
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $fields['selectProduct'];
         $productDAO->find(TRUE);
         $min_amount = $productDAO->min_contribution;
         if ($amount < $min_amount) {
             $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
         }
     }
     if ($self->_values['honor_block_is_active'] && CRM_Utils_Array::value('honor_type_id', $fields)) {
         // make sure there is a first name and last name if email is not there
         if (!CRM_Utils_Array::value('honor_email', $fields)) {
             if (!CRM_Utils_Array::value('honor_first_name', $fields) || !CRM_Utils_Array::value('honor_last_name', $fields)) {
                 $errors['honor_last_name'] = ts('In Honor Of - First Name and Last Name, OR an Email Address is required.');
             }
         }
     }
     if (CRM_Utils_Array::value('is_recur', $fields)) {
         if ($fields['frequency_interval'] <= 0) {
             $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
         }
         if ($fields['frequency_unit'] == '0') {
             $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).');
         }
     }
     if (CRM_Utils_Array::value('is_recur', $fields) && CRM_Utils_Array::value('payment_processor', $fields) == 0) {
         $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
     }
     if (CRM_Utils_Array::value('is_for_organization', $fields) && !property_exists($self, 'organizationName')) {
         if (!CRM_Utils_Array::value('organization_name', $fields['onbehalf'])) {
             if (CRM_Utils_Array::value('org_option', $fields) && !$fields['onbehalfof_id']) {
                 $errors['organization_id'] = ts('Please select an organization or enter a new one.');
             } elseif (!CRM_Utils_Array::value('org_option', $fields)) {
                 $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.');
             }
         }
         foreach ($fields['onbehalf'] as $key => $value) {
             if (strstr($key, 'email')) {
                 $emailLocType = explode('-', $key);
             }
         }
         if (!CRM_Utils_Array::value("email-{$emailLocType[1]}", $fields['onbehalf'])) {
             $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.');
         }
     }
     // validate PCP fields - if not anonymous, we need a nick name value
     if ($self->_pcpId && CRM_Utils_Array::value('pcp_display_in_roll', $fields) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') {
         $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
     }
     // return if this is express mode
     $config = CRM_Core_Config::singleton();
     if ($self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
         if (CRM_Utils_Array::value($self->_expressButtonName . '_x', $fields) || CRM_Utils_Array::value($self->_expressButtonName . '_y', $fields) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) {
             return $errors;
         }
     }
     //validate the pledge fields.
     if (CRM_Utils_Array::value('pledge_block_id', $self->_values)) {
         //validation for pledge payment.
         if (CRM_Utils_Array::value('pledge_id', $self->_values)) {
             if (empty($fields['pledge_amount'])) {
                 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
             }
         } elseif (CRM_Utils_Array::value('is_pledge', $fields)) {
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
                 $errors['pledge_installments'] = ts('Please enter a valid pledge installment.');
             } else {
                 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
                     $errors['pledge_installments'] = ts('Pledge Installments is required field.');
                 } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 1) {
                     $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
                 } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 0) {
                     $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
                 }
             }
             //validation for Pledge Frequency Interval.
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
                 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
             } else {
                 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
                     $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
                 } elseif (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) {
                     $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
                 }
             }
         }
     }
     // also return if paylater mode
     if (CRM_Utils_Array::value('payment_processor', $fields) == 0) {
         return empty($errors) ? TRUE : $errors;
     }
     // if the user has chosen a free membership or the amount is less than zero
     // i.e. we skip calling the payment processor and hence dont need credit card
     // info
     if ((double) $amount <= 0.0) {
         return $errors;
     }
     if (isset($self->_paymentFields)) {
         foreach ($self->_paymentFields as $name => $fld) {
             if ($fld['is_required'] && CRM_Utils_System::isNull(CRM_Utils_Array::value($name, $fields))) {
                 $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title']));
             }
         }
     }
     // make sure that credit card number and cvv are valid
     if (CRM_Utils_Array::value('credit_card_type', $fields)) {
         if (CRM_Utils_Array::value('credit_card_number', $fields) && !CRM_Utils_Rule::creditCardNumber($fields['credit_card_number'], $fields['credit_card_type'])) {
             $errors['credit_card_number'] = ts('Please enter a valid Credit Card Number');
         }
         if (CRM_Utils_Array::value('cvv2', $fields) && !CRM_Utils_Rule::cvv($fields['cvv2'], $fields['credit_card_type'])) {
             $errors['cvv2'] = ts('Please enter a valid Credit Card Verification Number');
         }
     }
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
             if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
                 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting))));
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
Exemple #21
0
 /**
  * @param $rows
  *
  * @return array
  */
 public function statistics(&$rows)
 {
     $statistics = parent::statistics($rows);
     $isStatusFilter = FALSE;
     $relStatus = NULL;
     if (CRM_Utils_Array::value('is_active_value', $this->_params) == '1') {
         $relStatus = 'Is equal to Active';
     } elseif (CRM_Utils_Array::value('is_active_value', $this->_params) == '0') {
         $relStatus = 'Is equal to Inactive';
     }
     if (!empty($statistics['filters'])) {
         foreach ($statistics['filters'] as $id => $value) {
             //for displaying relationship type filter
             if ($value['title'] == 'Relationship') {
                 $relTypes = CRM_Core_PseudoConstant::relationshipType();
                 $op = CRM_Utils_array::value('relationship_type_id_op', $this->_params) == 'in' ? ts('Is one of') . ' ' : ts('Is not one of') . ' ';
                 $relationshipTypes = array();
                 foreach ($this->_params['relationship_type_id_value'] as $relationship) {
                     $relationshipTypes[] = $relTypes[$relationship]['label_' . $this->relationType];
                 }
                 $statistics['filters'][$id]['value'] = $op . implode(', ', $relationshipTypes);
             }
             //for displaying relationship status
             if ($value['title'] == 'Relationship Status') {
                 $isStatusFilter = TRUE;
                 $statistics['filters'][$id]['value'] = $relStatus;
             }
         }
     }
     //for displaying relationship status
     if (!$isStatusFilter && $relStatus) {
         $statistics['filters'][] = array('title' => 'Relationship Status', 'value' => $relStatus);
     }
     return $statistics;
 }
Exemple #22
0
 /**
  * Function to process the activities
  *
  * @param object $form         form object
  * @param array  $params       associated array of the submitted values
  * @param array  $ids          array of ids
  * @param string $activityType activity Type
  * @param boolean $record   true if it is Record Activity 
  * @access public
  * @return
  */
 public function create(&$params)
 {
     // check required params
     if (!self::dataExists($params)) {
         CRM_Core_Error::fatal('Not enough data to create activity object,');
     }
     $activity =& new CRM_Activity_DAO_Activity();
     if (!CRM_Utils_Array::value('status_id', $params)) {
         if (isset($params['activity_date_time']) && strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)) {
             $params['status_id'] = 2;
         } else {
             $params['status_id'] = 1;
         }
     }
     //set priority to Normal for Auto-populated activities (for Cases)
     if (!CRM_Utils_Array::value('priority_id', $params)) {
         require_once 'CRM/Core/PseudoConstant.php';
         $priority = CRM_Core_PseudoConstant::priority();
         $params['priority_id'] = array_search('Normal', $priority);
     }
     if (empty($params['id'])) {
         unset($params['id']);
     }
     if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
         $params['target_contact_id'] = array_unique($params['target_contact_id']);
     }
     if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
     }
     $activity->copyValues($params);
     // start transaction
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $result = $activity->save();
     if (is_a($result, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $result;
     }
     $activityId = $activity->id;
     // check and attach and files as needed
     require_once 'CRM/Core/BAO/File.php';
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
     // attempt to save activity assignment
     $resultAssignment = null;
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         require_once 'CRM/Activity/BAO/ActivityAssignment.php';
         $assignmentParams = array('activity_id' => $activityId);
         if (is_array($params['assignee_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityAssignment', $params, true)) {
                 // first delete existing assignments if any
                 self::deleteActivityAssignment($activityId);
             }
             foreach ($params['assignee_contact_id'] as $acID) {
                 if ($acID) {
                     $assignmentParams['assignee_contact_id'] = $acID;
                     $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
                     if (is_a($resultAssignment, 'CRM_Core_Error')) {
                         $transaction->rollback();
                         return $resultAssignment;
                     }
                 }
             }
         } else {
             $assignmentParams['assignee_contact_id'] = $params['assignee_contact_id'];
             if (CRM_Utils_Array::value('id', $params)) {
                 $assignment =& new CRM_Activity_BAO_ActivityAssignment();
                 $assignment->activity_id = $activityId;
                 $assignment->find(true);
                 if ($assignment->assignee_contact_id != $params['assignee_contact_id']) {
                     $assignmentParams['id'] = $assignment->id;
                     $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
                 }
             } else {
                 $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityAssignment', $params, true)) {
             self::deleteActivityAssignment($activityId);
         }
     }
     if (is_a($resultAssignment, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $resultAssignment;
     }
     // attempt to save activity targets
     $resultTarget = null;
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         $targetParams = array('activity_id' => $activityId);
         $resultTarget = array();
         if (is_array($params['target_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityTarget', $params, true)) {
                 // first delete existing targets if any
                 self::deleteActivityTarget($activityId);
             }
             foreach ($params['target_contact_id'] as $tid) {
                 if ($tid) {
                     $targetParams['target_contact_id'] = $tid;
                     $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
                     if (is_a($resultTarget, 'CRM_Core_Error')) {
                         $transaction->rollback();
                         return $resultTarget;
                     }
                 }
             }
         } else {
             $targetParams['target_contact_id'] = $params['target_contact_id'];
             if (CRM_Utils_Array::value('id', $params)) {
                 $target =& new CRM_Activity_BAO_ActivityTarget();
                 $target->activity_id = $activityId;
                 $target->find(true);
                 if ($target->target_contact_id != $params['target_contact_id']) {
                     $targetParams['id'] = $target->id;
                     $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
                 }
             } else {
                 $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityTarget', $params, true)) {
             self::deleteActivityTarget($activityId);
         }
     }
     // write to changelog before transation is committed/rolled
     // back (and prepare status to display)
     if (CRM_Utils_Array::value('id', $params)) {
         $logMsg = "Activity (id: {$result->id} ) updated with ";
     } else {
         $logMsg = "Activity created for ";
     }
     $msgs = array();
     if (isset($params['source_contact_id'])) {
         $msgs[] = "source={$params['source_contact_id']}";
     }
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         if (is_array($params['target_contact_id']) && !CRM_Utils_array::crmIsEmptyArray($params['target_contact_id'])) {
             $msgs[] = "target=" . implode(',', $params['target_contact_id']);
             // take only first target
             // will be used for recently viewed display
             $t = array_slice($params['target_contact_id'], 0, 1);
             $recentContactId = $t[0];
         } else {
             if (isset($params['target_contact_id'])) {
                 $msgs[] = "target={$params['target_contact_id']}";
                 // will be used for recently viewed display
                 $recentContactId = $params['target_contact_id'];
             }
         }
     } else {
         // at worst, take source for recently viewed display
         $recentContactId = $params['source_contact_id'];
     }
     if (isset($params['assignee_contact_id'])) {
         if (is_array($params['assignee_contact_id'])) {
             $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
         } else {
             $msgs[] = "assignee={$params['assignee_contact_id']}";
         }
     }
     $logMsg .= implode(', ', $msgs);
     self::logActivityAction($result, $logMsg);
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
     }
     $transaction->commit();
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         require_once 'CRM/Utils/Recent.php';
         if (CRM_Utils_Array::value('case_id', $params)) {
             $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
             $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home");
         } else {
             $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home";
             if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
                 $url = CRM_Utils_System::url('civicrm/contact/view/activity', $q);
             } else {
                 $url = CRM_Utils_System::url('civicrm/activity', $q);
             }
         }
         if (!isset($activity->parent_id)) {
             require_once 'CRM/Contact/BAO/Contact.php';
             $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
             // add the recently created Activity
             $activityTypes = CRM_Core_Pseudoconstant::activityType(true, true);
             $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
             $title = "";
             if (isset($activitySubject)) {
                 $title = $activitySubject . ' - ';
             }
             $title = $title . $recentContactDisplay . ' (' . $activityTypes[$activity->activity_type_id] . ')';
             CRM_Utils_Recent::add($title, $url, $activity->id, 'Activity', $recentContactId, $recentContactDisplay);
         }
     }
     if (CRM_Utils_Array::value('id', $params)) {
         CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
     } else {
         CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
     }
     return $result;
 }
 /**
  * takes an associative array and creates a membership object
  *
  * the function extract all the params it needs to initialize the create a
  * membership object. the params array could contain additional unused name/value
  * pairs
  *
  * @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_Member_BAO_Membership object
  * @access public
  * @static
  */
 static function &add(&$params, &$ids)
 {
     require_once 'CRM/Utils/Hook.php';
     if (CRM_Utils_Array::value('membership', $ids)) {
         CRM_Utils_Hook::pre('edit', 'Membership', $ids['membership'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Membership', null, $params);
     }
     // converting dates to mysql format
     if (isset($params['join_date'])) {
         $params['join_date'] = CRM_Utils_Date::isoToMysql($params['join_date']);
     }
     if (isset($params['start_date'])) {
         $params['start_date'] = CRM_Utils_Date::isoToMysql($params['start_date']);
     }
     if (CRM_Utils_Array::value('end_date', $params)) {
         $params['end_date'] = CRM_Utils_Date::isoToMysql($params['end_date']);
     } else {
         $params['end_date'] = 'null';
     }
     if (CRM_Utils_Array::value('reminder_date', $params)) {
         $params['reminder_date'] = CRM_Utils_Date::isoToMysql($params['reminder_date']);
     } else {
         $params['reminder_date'] = 'null';
     }
     if (!CRM_Utils_Array::value('is_override', $params)) {
         $params['is_override'] = 'null';
     }
     $membership = new CRM_Member_BAO_Membership();
     $membership->copyValues($params);
     $membership->id = CRM_Utils_Array::value('membership', $ids);
     $membership->save();
     $membership->free();
     $session =& CRM_Core_Session::singleton();
     //get the log start date.
     //it is set during renewal of membership.
     $logStartDate = CRM_Utils_array::value('log_start_date', $params);
     $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $membership->start_date;
     $membershipLog = array('membership_id' => $membership->id, 'status_id' => $membership->status_id, 'start_date' => $logStartDate, 'end_date' => $membership->end_date, 'renewal_reminder_date' => $membership->reminder_date, 'modified_id' => CRM_Utils_Array::value('userId', $ids), 'modified_date' => date('Ymd'));
     require_once 'CRM/Member/BAO/MembershipLog.php';
     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
     // reset the group contact cache since smart groups might be affected due to this
     require_once 'CRM/Contact/BAO/GroupContactCache.php';
     CRM_Contact_BAO_GroupContactCache::remove();
     if (CRM_Utils_Array::value('membership', $ids)) {
         CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
     } else {
         CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership);
     }
     return $membership;
 }
Exemple #24
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess($params = null)
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $deleteParams = array('id' => $this->_activityId);
         CRM_Activity_BAO_Activity::deleteActivity($deleteParams);
         CRM_Core_Session::setStatus(ts("Selected Activity has been deleted sucessfully."));
         return;
     }
     // store the submitted values in an array
     if (!$params) {
         $params = $this->controller->exportValues($this->_name);
     }
     //set activity type id
     if (!CRM_Utils_Array::value('activity_type_id', $params)) {
         $params['activity_type_id'] = $this->_activityTypeId;
     }
     if (CRM_Utils_Array::value('hidden_custom', $params) && !isset($params['custom'])) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', false, false, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', false, false, null, null, true));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_activityId, 'Activity');
     }
     // store the date with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     // assigning formated value to related variable
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         $params['target_contact_id'] = explode(',', $params['target_contact_id']);
     } else {
         $params['target_contact_id'] = array();
     }
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = array();
     }
     // get ids for associated contacts
     if (!$params['source_contact_id']) {
         $params['source_contact_id'] = $this->_currentUserId;
     } else {
         $params['source_contact_id'] = $this->_submitValues['source_contact_qid'];
     }
     if (isset($this->_activityId)) {
         $params['id'] = $this->_activityId;
     }
     // add attachments as needed
     CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity', $this->_activityId);
     // format target params
     if (!$this->_single) {
         $params['target_contact_id'] = $this->_contactIds;
     }
     $activityAssigned = array();
     // format assignee params
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
         //skip those assignee contacts which are already assigned
         //while sending a copy.CRM-4509.
         $activityAssigned = array_flip($params['assignee_contact_id']);
         if ($this->_activityId) {
             $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($this->_activityId);
             $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
         }
     }
     // call begin post process. Idea is to let injecting file do
     // any processing before the activity is added/updated.
     $this->beginPostProcess($params);
     $activity = CRM_Activity_BAO_Activity::create($params);
     // call end post process. Idea is to let injecting file do any
     // processing needed, after the activity has been added/updated.
     $this->endPostProcess($params, $activity);
     // create follow up activity if needed
     $followupStatus = '';
     if (CRM_Utils_Array::value('followup_activity_type_id', $params)) {
         $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
         $followupStatus = "A followup activity has been scheduled.";
     }
     // send copy to assignee contacts.CRM-4509
     $mailStatus = '';
     $config =& CRM_Core_Config::singleton();
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id']) && $config->activityAssigneeNotification) {
         $mailToContacts = array();
         $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activity->id, true, false);
         //build an associative array with unique email addresses.
         foreach ($activityAssigned as $id => $dnc) {
             if (isset($id) && array_key_exists($id, $assigneeContacts)) {
                 $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
             }
         }
         if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
             //include attachments while sendig a copy of activity.
             $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
             require_once "CRM/Case/BAO/Case.php";
             $result = CRM_Case_BAO_Case::sendActivityCopy(null, $activity->id, $mailToContacts, $attachments, null);
             $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
         }
     }
     // set status message
     if (CRM_Utils_Array::value('subject', $params)) {
         $params['subject'] = "'" . $params['subject'] . "'";
     }
     CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2. %3', array(1 => $params['subject'], 2 => $followupStatus, 3 => $mailStatus)));
     return array('activity' => $activity);
 }
 /**
  * global form rule
  *
  * @param array $fields  the input form values
  * @param array $files   the uploaded files if any
  * @param array $options additional user data
  *
  * @return true if no errors, else array of errors
  * @access public
  * @static
  */
 static function formRule($fields, $files, $self)
 {
     $errors = array();
     //as for separate membership payment we has to have
     //contribution amount section enabled, hence to disable it need to
     //check if separate membership payment enabled,
     //if so disable first separate membership payment option
     //then disable contribution amount section. CRM-3801,
     $membershipBlock = new CRM_Member_DAO_MembershipBlock();
     $membershipBlock->entity_table = 'civicrm_contribution_page';
     $membershipBlock->entity_id = $self->_id;
     $membershipBlock->is_active = 1;
     $hasMembershipBlk = FALSE;
     if ($membershipBlock->find(TRUE)) {
         if (CRM_Utils_Array::value('amount_block_is_active', $fields) && ($setID = CRM_Price_BAO_Set::getFor('civicrm_contribution_page', $self->_id, NULL, 1))) {
             $extends = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $setID, 'extends');
             if ($extends && $extends == CRM_Core_Component::getComponentID('CiviMember')) {
                 $errors['amount_block_is_active'] = ts('You cannot use a Membership Price Set when the Contribution Amounts section is enabled. Click the Memberships tab above, and select your Membership Price Set on that form. Membership Price Sets may include additional fields for non-membership options that require an additional fee (e.g. magazine subscription) or an additional voluntary contribution.');
                 return $errors;
             }
         }
         $hasMembershipBlk = TRUE;
         if ($membershipBlock->is_separate_payment && !$fields['amount_block_is_active']) {
             $errors['amount_block_is_active'] = ts('To disable Contribution Amounts section you need to first disable Separate Membership Payment option from Membership Settings.');
         }
     }
     $minAmount = CRM_Utils_Array::value('min_amount', $fields);
     $maxAmount = CRM_Utils_Array::value('max_amount', $fields);
     if (!empty($minAmount) && !empty($maxAmount)) {
         $minAmount = CRM_Utils_Rule::cleanMoney($minAmount);
         $maxAmount = CRM_Utils_Rule::cleanMoney($maxAmount);
         if ((double) $minAmount > (double) $maxAmount) {
             $errors['min_amount'] = ts('Minimum Amount should be less than Maximum Amount');
         }
     }
     if (isset($fields['is_pay_later'])) {
         if (empty($fields['pay_later_text'])) {
             $errors['pay_later_text'] = ts('Please enter the text for the \'pay later\' checkbox displayed on the contribution form.');
         }
         if (empty($fields['pay_later_receipt'])) {
             $errors['pay_later_receipt'] = ts('Please enter the instructions to be sent to the contributor when they choose to \'pay later\'.');
         }
     }
     // don't allow price set w/ membership signup, CRM-5095
     if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
         // don't allow price set w/ membership.
         if ($hasMembershipBlk) {
             $errors['price_set_id'] = ts('You cannot enable both a Contribution Price Set and Membership Signup on the same online contribution page.');
         }
     } else {
         if (isset($fields['is_recur'])) {
             if (empty($fields['recur_frequency_unit'])) {
                 $errors['recur_frequency_unit'] = ts('At least one recurring frequency option needs to be checked.');
             }
         }
         // validation for pledge fields.
         if (CRM_Utils_array::value('is_pledge_active', $fields)) {
             if (empty($fields['pledge_frequency_unit'])) {
                 $errors['pledge_frequency_unit'] = ts('At least one pledge frequency option needs to be checked.');
             }
             if (CRM_Utils_array::value('is_recur', $fields)) {
                 $errors['is_recur'] = ts('You cannot enable both Recurring Contributions AND Pledges on the same online contribution page.');
             }
         }
         // If Contribution amount section is enabled, then
         // Allow other amounts must be enabeld OR the Fixed Contribution
         // Contribution options must contain at least one set of values.
         if (CRM_Utils_Array::value('amount_block_is_active', $fields)) {
             if (!CRM_Utils_Array::value('is_allow_other_amount', $fields) && !$priceSetId) {
                 //get the values of amount block
                 $values = CRM_Utils_Array::value('value', $fields);
                 $isSetRow = FALSE;
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (isset($values[$i]) && strlen(trim($values[$i])) > 0) {
                         $isSetRow = TRUE;
                     }
                 }
                 if (!$isSetRow) {
                     $errors['amount_block_is_active'] = ts('If you want to enable the \'Contribution Amounts section\', you need to either \'Allow Other Amounts\' and/or enter at least one row in the \'Fixed Contribution Amounts\' table.');
                 }
             }
         }
     }
     if (CRM_Utils_Array::value('is_recur_interval', $fields)) {
         foreach (array_keys($fields['payment_processor']) as $paymentProcessorID) {
             $paymentProcessorType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PaymentProcessor', $paymentProcessorID, 'payment_processor_type');
             if ($paymentProcessorType == 'Google_Checkout') {
                 $errors['is_recur_interval'] = ts('Google Checkout does not support recurring intervals');
                 break;
             }
         }
     }
     return $errors;
 }
Exemple #26
0
    function handle( $config ) {
        
        // Get the function name being called from the q parameter in the query string
        $q = CRM_Utils_array::value( 'q', $_REQUEST );
        $args = explode( '/', $q );
        // If the function isn't in the civicrm namespace, reject the request.
        if ( $args[0] != 'civicrm' ) {
            return self::error( 'Unknown function invocation.' );
        }

        // If the query string is malformed, reject the request.
        if ( ( count( $args ) != 3 ) && ( $args[1] != 'login' ) && ( $args[1] != 'ping') ) {
            return self::error( 'Unknown function invocation.' );
        }

        // Everyone should be required to provide the server key, so the whole 
        //  interface can be disabled in more change to the configuration file.
        //  This used to be done in the authenticate function, but that was bad...trust me
        // first check for civicrm site key
        if ( ! CRM_Utils_System::authenticateKey( false ) ) {
            $docLink = CRM_Utils_System::docURL2( "Command-line Script Configuration", true );
            return self::error( 'Could not authenticate user, invalid site key. More info at: ' . $docLink );
        }
	
        require_once 'CRM/Utils/Request.php';

        $store = null;
        if ( $args[1] == 'login' ) {
            $name = CRM_Utils_Request::retrieve( 'name', 'String', $store, false, null, 'REQUEST' );
            $pass = CRM_Utils_Request::retrieve( 'pass', 'String', $store, false, null, 'REQUEST' );
            if ( empty( $name ) ||
                 empty( $pass ) ) {
                return self::error( 'Invalid name / password.' );
            }
            return self::authenticate( $name, $pass );
        } else if ($args[1] == 'ping' ) {
            return self::ping();
        }
	
        // At this point we know we are not calling either login or ping (neither of which 
        //  require authentication prior to being called.  Therefore, at this point we need
        //  to make sure we're working with a trusted user.
	
        // There are two ways to check for a trusted user:
        //  First: they can be someone that has a valid session currently
        //  Second: they can be someone that has provided an API_Key
	
        $valid_user = false;

        // Check for valid session.  Session ID's only appear here if you have
        // run the rest_api login function.  That might be a problem for the 
        // AJAX methods.  
        $session = CRM_Core_Session::singleton();
        if ($session->get('PHPSESSID') ) {
            $valid_user = true;
        }
	
        // If the user does not have a valid session (most likely to be used by people using
        // an ajax interface), we need to check to see if they are carring a valid user's 
        // secret key.
        if ( !$valid_user ) {
            require_once 'CRM/Core/DAO.php';
            $api_key = CRM_Utils_Request::retrieve( 'api_key', 'String', $store, false, null, 'REQUEST' );
            $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
        }
	
        // If we didn't find a valid user either way, then die.
        if ( empty($valid_user) ) {
            return self::error("Valid session, or user api_key required");
        }

        return self::process( $args );
    }
 /**
  * Process the activities.
  *
  * @param array $params
  *   Associated array of the submitted values.
  *
  * @throws CRM_Core_Exception
  *
  * @return CRM_Activity_BAO_Activity|null|object
  */
 public static function create(&$params)
 {
     // check required params
     if (!self::dataExists($params)) {
         throw new CRM_Core_Exception('Not enough data to create activity object');
     }
     $activity = new CRM_Activity_DAO_Activity();
     if (isset($params['id']) && empty($params['id'])) {
         unset($params['id']);
     }
     if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
         if (isset($params['activity_date_time']) && strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)) {
             $params['status_id'] = 2;
         } else {
             $params['status_id'] = 1;
         }
     }
     // Set priority to Normal for Auto-populated activities (for Cases)
     if (CRM_Utils_Array::value('priority_id', $params) === NULL && !CRM_Utils_Array::value('id', $params)) {
         $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
         $params['priority_id'] = array_search('Normal', $priority);
     }
     if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
         $params['target_contact_id'] = array_unique($params['target_contact_id']);
     }
     if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
     }
     // CRM-9137
     if (!empty($params['id'])) {
         CRM_Utils_Hook::pre('edit', 'Activity', $activity->id, $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Activity', NULL, $params);
     }
     $activity->copyValues($params);
     if (isset($params['case_id'])) {
         // CRM-8708, preserve case ID even though it's not part of the SQL model
         $activity->case_id = $params['case_id'];
     } elseif (is_numeric($activity->id)) {
         // CRM-8708, preserve case ID even though it's not part of the SQL model
         $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
     }
     // start transaction
     $transaction = new CRM_Core_Transaction();
     $result = $activity->save();
     if (is_a($result, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $result;
     }
     $activityId = $activity->id;
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
     if (isset($params['source_contact_id'])) {
         $acParams = array('activity_id' => $activityId, 'contact_id' => $params['source_contact_id'], 'record_type_id' => $sourceID);
         self::deleteActivityContact($activityId, $sourceID);
         CRM_Activity_BAO_ActivityContact::create($acParams);
     }
     // check and attach and files as needed
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
     // attempt to save activity assignment
     $resultAssignment = NULL;
     if (!empty($params['assignee_contact_id'])) {
         $assignmentParams = array('activity_id' => $activityId);
         if (is_array($params['assignee_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
                 // first delete existing assignments if any
                 self::deleteActivityContact($activityId, $assigneeID);
             }
             $values = array();
             foreach ($params['assignee_contact_id'] as $acID) {
                 if ($acID) {
                     $values[] = "( {$activityId}, {$acID}, {$assigneeID} )";
                 }
             }
             while (!empty($values)) {
                 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
                 $str = implode(',', $input);
                 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};";
                 CRM_Core_DAO::executeQuery($sql);
             }
         } else {
             $assignmentParams['contact_id'] = $params['assignee_contact_id'];
             $assignmentParams['record_type_id'] = $assigneeID;
             if (!empty($params['id'])) {
                 $assignment = new CRM_Activity_BAO_ActivityContact();
                 $assignment->activity_id = $activityId;
                 $assignment->record_type_id = $assigneeID;
                 $assignment->find(TRUE);
                 if ($assignment->contact_id != $params['assignee_contact_id']) {
                     $assignmentParams['id'] = $assignment->id;
                     $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
                 }
             } else {
                 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
             self::deleteActivityContact($activityId, $assigneeID);
         }
     }
     if (is_a($resultAssignment, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $resultAssignment;
     }
     // attempt to save activity targets
     $resultTarget = NULL;
     if (!empty($params['target_contact_id'])) {
         $targetParams = array('activity_id' => $activityId);
         $resultTarget = array();
         if (is_array($params['target_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
                 // first delete existing targets if any
                 self::deleteActivityContact($activityId, $targetID);
             }
             $values = array();
             foreach ($params['target_contact_id'] as $tid) {
                 if ($tid) {
                     $values[] = "( {$activityId}, {$tid},  {$targetID} )";
                 }
             }
             while (!empty($values)) {
                 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
                 $str = implode(',', $input);
                 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};";
                 CRM_Core_DAO::executeQuery($sql);
             }
         } else {
             $targetParams['contact_id'] = $params['target_contact_id'];
             $targetParams['record_type_id'] = $targetID;
             if (!empty($params['id'])) {
                 $target = new CRM_Activity_BAO_ActivityContact();
                 $target->activity_id = $activityId;
                 $target->record_type_id = $targetID;
                 $target->find(TRUE);
                 if ($target->contact_id != $params['target_contact_id']) {
                     $targetParams['id'] = $target->id;
                     $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
                 }
             } else {
                 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
             self::deleteActivityContact($activityId, $targetID);
         }
     }
     // write to changelog before transaction is committed/rolled
     // back (and prepare status to display)
     if (!empty($params['id'])) {
         $logMsg = "Activity (id: {$result->id} ) updated with ";
     } else {
         $logMsg = "Activity created for ";
     }
     $msgs = array();
     if (isset($params['source_contact_id'])) {
         $msgs[] = "source={$params['source_contact_id']}";
     }
     if (!empty($params['target_contact_id'])) {
         if (is_array($params['target_contact_id']) && !CRM_Utils_array::crmIsEmptyArray($params['target_contact_id'])) {
             $msgs[] = "target=" . implode(',', $params['target_contact_id']);
             // take only first target
             // will be used for recently viewed display
             $t = array_slice($params['target_contact_id'], 0, 1);
             $recentContactId = $t[0];
         } elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
             $msgs[] = "target={$params['target_contact_id']}";
             // will be used for recently viewed display
             $recentContactId = $params['target_contact_id'];
         }
     } else {
         // at worst, take source for recently viewed display
         $recentContactId = CRM_Utils_Array::value('source_contact_id', $params);
     }
     if (isset($params['assignee_contact_id'])) {
         if (is_array($params['assignee_contact_id'])) {
             $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
         } else {
             $msgs[] = "assignee={$params['assignee_contact_id']}";
         }
     }
     $logMsg .= implode(', ', $msgs);
     self::logActivityAction($result, $logMsg);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
     }
     $transaction->commit();
     if (empty($params['skipRecentView'])) {
         $recentOther = array();
         if (!empty($params['case_id'])) {
             $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
             $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home");
         } else {
             $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home";
             if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
                 $url = CRM_Utils_System::url('civicrm/activity', $q);
                 if ($activity->activity_type_id == CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name')) {
                     $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/pdf/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home");
                 } else {
                     $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
                 if (CRM_Core_Permission::check("delete activities")) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/activity/view', $q);
                 if (CRM_Core_Permission::check('delete activities')) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
             }
         }
         if (!isset($activity->parent_id)) {
             $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
             // add the recently created Activity
             $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
             $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
             $title = "";
             if (isset($activitySubject)) {
                 $title = $activitySubject . ' - ';
             }
             $title = $title . $recentContactDisplay;
             if (!empty($activityTypes[$activity->activity_type_id])) {
                 $title .= ' (' . $activityTypes[$activity->activity_type_id] . ')';
             }
             CRM_Utils_Recent::add($title, $url, $activity->id, 'Activity', $recentContactId, $recentContactDisplay, $recentOther);
         }
     }
     // reset the group contact cache since smart groups might be affected due to this
     CRM_Contact_BAO_GroupContactCache::remove();
     if (!empty($params['id'])) {
         CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
     } else {
         CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
     }
     // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
     $matches = array();
     if (preg_match('/\\[case #([0-9a-h]{7})\\]/', CRM_Utils_Array::value('subject', $params), $matches)) {
         $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
         $hash = $matches[1];
         $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('{$key}', id)), 1, 7) = '{$hash}'";
         $caseParams = array('activity_id' => $activity->id, 'case_id' => CRM_Core_DAO::singleValueQuery($query));
         if ($caseParams['case_id']) {
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
         } else {
             self::logActivityAction($activity, "unknown case hash encountered: {$hash}");
         }
     }
     return $result;
 }
Exemple #28
0
 public function postProcess()
 {
     $formValues = $this->exportValues();
     // user can't choose to move cases without activities (CRM-3778)
     if ($formValues['move_rel_table_cases'] == '1' && array_key_exists('move_rel_table_activities', $formValues)) {
         $formValues['move_rel_table_activities'] = '1';
     }
     // reset all selected contact ids from session
     // when we came from search context, CRM-3526
     $session =& CRM_Core_Session::singleton();
     if ($session->get('selectedSearchContactIds')) {
         $session->resetScope('selectedSearchContactIds');
     }
     $relTables =& CRM_Dedupe_Merger::relTables();
     $moveTables = $locBlocks = array();
     foreach ($formValues as $key => $value) {
         if ($value == $this->_qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::$validFields) or substr($key, 0, 12) == 'move_custom_') and $value != null) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != null) {
             $locField = explode('_', $key);
             $fieldName = $locField[2];
             $fieldCount = $locField[3];
             $operation = CRM_Utils_Array::value('operation', $formValues['location'][$fieldName][$fieldCount]);
             // default operation is overwrite.
             if (!$operation) {
                 $operation = 2;
             }
             $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
             $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $formValues['location'][$fieldName][$fieldCount]);
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
         }
     }
     // process location blocks.
     if (!empty($locBlocks)) {
         $locComponent = array('email' => 'Email', 'phone' => 'Phone', 'im' => 'IM', 'openid' => 'OpenID', 'address' => 'Address');
         require_once 'CRM/Contact/BAO/Contact.php';
         $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($this->_cid, array('is_primary' => 1));
         $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($this->_cid, array('is_billing' => 1));
         foreach ($locBlocks as $name => $block) {
             if (!is_array($block) || CRM_Utils_System::isNull($block)) {
                 continue;
             }
             $daoName = $locComponent[$name];
             $primaryDAOId = array_key_exists($name, $primaryBlockIds) ? array_pop($primaryBlockIds[$name]) : null;
             $billingDAOId = array_key_exists($name, $billingBlockIds) ? array_pop($billingBlockIds[$name]) : null;
             foreach ($block as $blkCount => $values) {
                 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
                 $operation = CRM_Utils_Array::value('operation', $values, 2);
                 $updateBlockId = CRM_Utils_Array::value($blkCount, $this->_locBlockIds['other'][$name]);
                 // keep 1-1 mapping for address - loc type.
                 $idKey = $blkCount;
                 if ($name == 'address') {
                     $idKey = $locTypeId;
                 }
                 $deleteBlockId = CRM_Utils_Array::value($idKey, $this->_locBlockIds['main'][$name]);
                 if (!$updateBlockId) {
                     continue;
                 }
                 require_once "CRM/Core/DAO/{$daoName}.php";
                 eval("\$updateDAO =& new CRM_Core_DAO_{$daoName}();");
                 $updateDAO->id = $updateBlockId;
                 $updateDAO->contact_id = $this->_cid;
                 $updateDAO->location_type_id = $locTypeId;
                 // contact having primary block.
                 if ($primaryDAOId) {
                     $updateDAO->is_primary = 0;
                 }
                 if ($billingDAOId) {
                     $updateDAO->is_billing = 0;
                 }
                 // overwrite - need to delete block from main contact.
                 if ($deleteBlockId && $operation == 2) {
                     eval("\$deleteDAO =& new CRM_Core_DAO_{$daoName}();");
                     $deleteDAO->id = $deleteBlockId;
                     $deleteDAO->find(true);
                     // since we overwrite primary block.
                     if ($primaryDAOId && $primaryDAOId == $deleteDAO->id) {
                         $updateDAO->is_primary = 1;
                     }
                     if ($billingDAOId && $billingDAOId == $deleteDAO->id) {
                         $updateDAO->is_billing = 1;
                     }
                     $deleteDAO->delete();
                     $deleteDAO->free();
                 }
                 $updateDAO->update();
                 $updateDAO->free();
             }
         }
     }
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, true);
     // FIXME: fix custom fields so they're edible by createProfileContact()
     $cgTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, null, -1);
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     require_once 'CRM/Core/BAO/CustomValueTable.php';
                     $customParams = array('entityID' => $this->_cid, $key => true);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (CRM_Utils_array::value($key, $customfieldValues)) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value) {
                                 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             }
                             //hack to remove null and duplicate values from array.
                             foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                 if ($v != '' && !in_array($v, $mergeValue)) {
                                     $mergeValue[] = $v;
                                 }
                             }
                             //keep state and country as array format.
                             //for checkbox and m-select format w/ VALUE_SEPERATOR
                             if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                 $submitted[$key] = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $mergeValue) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                             } else {
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     } else {
                         if (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                             //we require submitted values should be in array format
                             if ($value) {
                                 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                                 //hack to remove null values from array.
                                 $mergeValue = array();
                                 foreach ($mergeValueArray as $k => $v) {
                                     if ($v != '') {
                                         $mergeValue[] = $v;
                                     }
                                 }
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // handle the related tables
     if (isset($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($this->_cid, $this->_oid, $moveTables);
     }
     // move file custom fields
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::delete() shouldn't actually,
     // like, delete a file...
     require_once 'CRM/Core/BAO/File.php';
     require_once 'CRM/Core/DAO/CustomField.php';
     require_once 'CRM/Core/DAO/CustomGroup.php';
     require_once 'CRM/Core/DAO/EntityFile.php';
     require_once 'CRM/Core/Config.php';
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$this->_cid}, {$this->_oid})";
         $dao =& CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         CRM_Core_BAO_File::delete($fileIds[$this->_cid], $this->_cid, $customId);
         // move the other contact's file to main contact
         $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$this->_oid]} WHERE entity_id = {$this->_cid}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         $sql = "UPDATE civicrm_entity_file SET entity_id = {$this->_cid} WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$this->_oid]}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     }
     // move other's belongings and delete the other contact
     CRM_Dedupe_Merger::moveContactBelongings($this->_cid, $this->_oid);
     $otherParams = array('contact_id' => $this->_oid);
     if (CRM_Core_Permission::check('delete contacts')) {
         civicrm_contact_delete($otherParams);
     } else {
         CRM_Core_Session::setStatus(ts('Do not have sufficient permission to delete duplicate contact.'));
     }
     if (isset($submitted)) {
         $submitted['contact_id'] = $this->_cid;
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $this->_cid);
     }
     CRM_Core_Session::setStatus(ts('The contacts have been merged.'));
     $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
     CRM_Utils_System::redirect($url);
 }
Exemple #29
0
 /**  
  * global form rule  
  *  
  * @param array $fields  the input form values  
  * @param array $files   the uploaded files if any  
  * @param array $options additional user data  
  *  
  * @return true if no errors, else array of errors  
  * @access public  
  * @static  
  */
 static function formRule($fields, $files, $self)
 {
     $errors = array();
     $minAmount = CRM_Utils_Array::value('min_amount', $fields);
     $maxAmount = CRM_Utils_Array::value('max_amount', $fields);
     if (!empty($minAmount) && !empty($maxAmount)) {
         $minAmount = CRM_Utils_Rule::cleanMoney($minAmount);
         $maxAmount = CRM_Utils_Rule::cleanMoney($maxAmount);
         if ((double) $minAmount > (double) $maxAmount) {
             $errors['min_amount'] = ts('Minimum Amount should be less than Maximum Amount');
         }
     }
     if (isset($fields['is_pay_later'])) {
         if (empty($fields['pay_later_text'])) {
             $errors['pay_later_text'] = ts('Please enter the text for the \'pay later\' checkbox displayed on the contribution form.');
         }
         if (empty($fields['pay_later_receipt'])) {
             $errors['pay_later_receipt'] = ts('Please enter the instructions to be sent to the contributor when they choose to \'pay later\'.');
         }
     }
     //as for separate membership payment we has to have
     //contribution amount section enabled, hence to disable it need to
     //check if separate membership payment enabled,
     //if so disable first separate membership payment option
     //then disable contribution amount section. CRM-3801,
     require_once 'CRM/Member/DAO/MembershipBlock.php';
     $membershipBlock = new CRM_Member_DAO_MembershipBlock();
     $membershipBlock->entity_table = 'civicrm_contribution_page';
     $membershipBlock->entity_id = $self->_id;
     $membershipBlock->is_active = 1;
     $hasMembershipBlk = false;
     if ($membershipBlock->find(true)) {
         $hasMembershipBlk = true;
         if ($membershipBlock->is_separate_payment && !$fields['amount_block_is_active']) {
             $errors['amount_block_is_active'] = ts('To disable Contribution Amounts section you need to first disable Separate Membership Payment option from Membership Settings.');
         }
     }
     // don't allow price set w/ membership signup, CRM-5095
     if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
         // don't allow price set w/ membership.
         if ($hasMembershipBlk) {
             $errors['price_set_id'] = ts('You cannot enable both Price Set and Membership Signup on the same online contribution page.');
         }
     } else {
         if (isset($fields['is_recur'])) {
             if (empty($fields['recur_frequency_unit'])) {
                 $errors['recur_frequency_unit'] = ts('At least one recurring frequency option needs to be checked.');
             }
         }
         // validation for pledge fields.
         if (CRM_Utils_array::value('is_pledge_active', $fields)) {
             if (empty($fields['pledge_frequency_unit'])) {
                 $errors['pledge_frequency_unit'] = ts('At least one pledge frequency option needs to be checked.');
             }
             if (CRM_Utils_array::value('is_recur', $fields)) {
                 $errors['is_recur'] = ts('You cannot enable both Recurring Contributions AND Pledges on the same online contribution page.');
             }
         }
         // If Contribution amount section is enabled, then
         // Allow other amounts must be enabeld OR the Fixed Contribution
         // Contribution options must contain at least one set of values.
         if (CRM_Utils_Array::value('amount_block_is_active', $fields)) {
             if (!CRM_Utils_Array::value('is_allow_other_amount', $fields) && !$priceSetId) {
                 //get the values of amount block
                 $values = CRM_Utils_Array::value('value', $fields);
                 $isSetRow = false;
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (isset($values[$i]) && strlen(trim($values[$i])) > 0) {
                         $isSetRow = true;
                     }
                 }
                 if (!$isSetRow) {
                     $errors['amount_block_is_active'] = ts('If you want to enable the \'Contribution Amounts section\', you need to either \'Allow Other Amounts\' and/or enter at least one row in the \'Fixed Contribution Amounts\' table.');
                 }
             }
         }
     }
     return $errors;
 }
Exemple #30
0
 function loadCMSBootstrap()
 {
     $q = CRM_Utils_array::value('q', $_REQUEST);
     $args = explode('/', $q);
     // If the function isn't in the civicrm namespace or request
     // is for login or ping
     if (empty($args) || $args[0] != 'civicrm' || count($args) != 3 && $args[1] != 'login' && $args[1] != 'ping' || $args[1] == 'login' || $args[1] == 'ping') {
         return;
     }
     $uid = null;
     $session = CRM_Core_Session::singleton();
     if (!CRM_Utils_System::authenticateKey(false)) {
         return;
     }
     if ($session->get('PHPSESSID') && $session->get('cms_user_id')) {
         $uid = $session->get('cms_user_id');
     }
     if (!$uid) {
         require_once 'CRM/Core/DAO.php';
         require_once 'CRM/Utils/Request.php';
         $store = null;
         $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, false, null, 'REQUEST');
         $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
         if ($contact_id) {
             require_once 'CRM/Core/BAO/UFMatch.php';
             $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
         }
     }
     if ($uid) {
         CRM_Utils_System::loadBootStrap(null, null, $uid);
     }
 }