/** * Build the form object. * * * @param CRM_Core_Form $form * * @return void */ public static function buildQuickForm(&$form) { $toArray = array(); $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc'); $providerSelect = array(); foreach ($providers as $provider) { $providerSelect[$provider['id']] = $provider['title']; } $suppressedSms = 0; //here we are getting logged in user id as array but we need target contact id. CRM-5988 $cid = $form->get('cid'); if ($cid) { $form->_contactIds = array($cid); } $to = $form->add('text', 'to', ts('To'), array('class' => 'huge'), TRUE); $form->add('text', 'activity_subject', ts('Name The SMS'), array('class' => 'huge'), TRUE); $toSetDefault = TRUE; if (property_exists($form, '_context') && $form->_context == 'standalone') { $toSetDefault = FALSE; } // when form is submitted recompute contactIds $allToSMS = array(); if ($to->getValue()) { $allToPhone = explode(',', $to->getValue()); $form->_contactIds = array(); foreach ($allToPhone as $value) { list($contactId, $phone) = explode('::', $value); if ($contactId) { $form->_contactIds[] = $contactId; $form->_toContactPhone[] = $phone; } } $toSetDefault = TRUE; } //get the group of contacts as per selected by user in case of Find Activities if (!empty($form->_activityHolderIds)) { $extendTargetContacts = 0; $invalidActivity = 0; $validActivities = 0; foreach ($form->_activityHolderIds as $key => $id) { //valid activity check if (CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $id, 'subject', 'id') != self::RECIEVED_SMS_ACTIVITY_SUBJECT) { $invalidActivity++; continue; } $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); //target contacts limit check $ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $targetID)); if (count($ids) > 1) { $extendTargetContacts++; continue; } $validActivities++; $form->_contactIds = empty($form->_contactIds) ? $ids : array_unique(array_merge($form->_contactIds, $ids)); } if (!$validActivities) { $errorMess = ""; if ($extendTargetContacts) { $errorMess = ts('One selected activity consists of more than one target contact.', array('count' => $extendTargetContacts, 'plural' => '%count selected activities consist of more than one target contact.')); } if ($invalidActivity) { $errorMess = $errorMess ? ' ' : ''; $errorMess .= ts('The selected activity is invalid.', array('count' => $invalidActivity, 'plural' => '%count selected activities are invalid.')); } CRM_Core_Error::statusBounce(ts("%1: SMS Reply will not be sent.", array(1 => $errorMess))); } } if (is_array($form->_contactIds) && !empty($form->_contactIds) && $toSetDefault) { $returnProperties = array('sort_name' => 1, 'phone' => 1, 'do_not_sms' => 1, 'is_deceased' => 1, 'display_name' => 1); list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_contactIds, $returnProperties, FALSE, FALSE); // make a copy of all contact details $form->_allContactDetails = $form->_contactDetails; foreach ($form->_contactIds as $key => $contactId) { $value = $form->_contactDetails[$contactId]; //to check if the phone type is "Mobile" $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name'); if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') { //to check for "if the contact id belongs to a specified activity type" $actDetails = CRM_Activity_BAO_Activity::getContactActivity($contactId); if (self::RECIEVED_SMS_ACTIVITY_SUBJECT != CRM_Utils_Array::retrieveValueRecursive($actDetails, 'subject')) { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } if (isset($value['phone_type_id']) && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) || $value['do_not_sms'] || empty($value['phone']) || !empty($value['is_deceased'])) { //if phone is not primary check if non-primary phone is "Mobile" if (!empty($value['phone']) && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) && empty($value['is_deceased'])) { $filter = array('do_not_sms' => 0); $contactPhones = CRM_Core_BAO_Phone::allPhones($contactId, FALSE, 'Mobile', $filter); if (count($contactPhones) > 0) { $mobilePhone = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'phone'); $form->_contactDetails[$contactId]['phone_id'] = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'id'); $form->_contactDetails[$contactId]['phone'] = $mobilePhone; $form->_contactDetails[$contactId]['phone_type_id'] = CRM_Utils_Array::value('Mobile', $phoneTypes); } else { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } else { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } if (isset($mobilePhone)) { $phone = $mobilePhone; } elseif (empty($form->_toContactPhone)) { $phone = $value['phone']; } else { $phone = CRM_Utils_Array::value($key, $form->_toContactPhone); } if ($phone) { $toArray[] = array('text' => '"' . $value['sort_name'] . '" (' . $phone . ')', 'id' => "{$contactId}::{$phone}"); } } if (empty($toArray)) { CRM_Core_Error::statusBounce(ts('Selected contact(s) do not have a valid Phone, or communication preferences specify DO NOT SMS, or they are deceased')); } } //activity related variables if (isset($invalidActivity)) { $form->assign('invalidActivity', $invalidActivity); } if (isset($extendTargetContacts)) { $form->assign('extendTargetContacts', $extendTargetContacts); } $form->assign('toContact', json_encode($toArray)); $form->assign('suppressedSms', $suppressedSms); $form->assign('totalSelectedContacts', count($form->_contactIds)); $form->add('select', 'sms_provider_id', ts('From'), $providerSelect, TRUE); CRM_Mailing_BAO_Mailing::commonCompose($form); if ($form->_single) { // also fix the user context stack if ($form->_context) { $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1'); } else { $url = CRM_Utils_System::url('civicrm/contact/view', "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"); } $session = CRM_Core_Session::singleton(); $session->replaceUserContext($url); $form->addDefaultButtons(ts('Send SMS'), 'upload', 'cancel'); } else { $form->addDefaultButtons(ts('Send SMS'), 'upload'); } $form->addFormRule(array('CRM_Contact_Form_Task_SMSCommon', 'formRule'), $form); }
/** * @param $token * @param $contribution * @param bool $html * @param bool $escapeSmarty * * @return mixed|string */ public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) { self::_buildContributionTokens(); switch ($token) { case 'total_amount': case 'net_amount': case 'fee_amount': case 'non_deductible_amount': $value = CRM_Utils_Money::format(CRM_Utils_Array::retrieveValueRecursive($contribution, $token)); break; case 'receive_date': $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token); $value = CRM_Utils_Date::customFormat($value, NULL, array('j', 'm', 'Y')); break; default: if (!in_array($token, self::$_tokens['contribution'])) { $value = "{contribution.{$token}}"; } else { $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token); } break; } if ($escapeSmarty) { $value = self::tokenEscapeSmarty($value); } return $value; }
/** * @param array $params * @param int $participantId * @param int $contributionId * @param $feeBlock * @param array $lineItems * @param $paidAmount * @param int $priceSetId */ public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) { $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses); $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses); $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant'); CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems); // get the submitted foreach ($feeBlock as $id => $values) { CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems); $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id'); } if (!empty($submittedLineItems)) { $insertLines = $submittedLineItems; $submittedFieldValueIds = array_keys($submittedLineItems); $updateLines = array(); foreach ($previousLineItems as $id => $previousLineItem) { // check through the submitted items if the previousItem exists, // if found in submitted items, do not use it for new item creations if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) { // if submitted line items are existing don't fire INSERT query unset($insertLines[$previousLineItem['price_field_value_id']]); // for updating the line items i.e. use-case - once deselect-option selecting again if ($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] || $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1 || $previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty']) { $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']]; $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id; } } } $submittedFields = implode(', ', $submittedFieldId); $submittedFieldValues = implode(', ', $submittedFieldValueIds); } if (!empty($submittedFields) && !empty($submittedFieldValues)) { $updateLineItem = "UPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nSET li.qty = 0,\n li.line_total = 0.00,\n li.tax_amount = NULL\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n (price_field_value_id NOT IN ({$submittedFieldValues}))\n"; CRM_Core_DAO::executeQuery($updateLineItem); // gathering necessary info to record negative (deselected) financial_item $updateFinancialItem = "\n SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount\n FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})\nGROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id\n"; $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem); $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'DESC', TRUE); $trxnId['id'] = $trxn['financialTrxnId']; $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings); $updateFinancialItemInfoValues = array(); $financialItemsArray = array(); while ($updateFinancialItemInfoDAO->fetch()) { $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO; $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis'); // the below params are not needed unset($updateFinancialItemInfoValues['id']); unset($updateFinancialItemInfoValues['created_date']); // if not submitted and difference is not 0 make it negative if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) { // INSERT negative financial_items $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount']; if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) { $updateFinancialItemInfoValues['tax']['amount'] = -$previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']; $updateFinancialItemInfoValues['tax']['description'] = $taxTerm; if ($updateFinancialItemInfoValues['financial_type_id']) { $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']); } } // INSERT negative financial_items for tax amount $financialItemsArray[] = $updateFinancialItemInfoValues; } elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) { $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount']; // INSERT financial_items for tax amount if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] && isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])) { $updateFinancialItemInfoValues['tax']['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount']; $updateFinancialItemInfoValues['tax']['description'] = $taxTerm; if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) { $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']); } } $financialItemsArray[] = $updateFinancialItemInfoValues; } } } elseif (empty($submittedFields) && empty($submittedFieldValues)) { $updateLineItem = "UPDATE civicrm_line_item li\n INNER JOIN civicrm_financial_item fi\n ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\n SET li.qty = 0,\n li.line_total = 0.00,\n li.tax_amount = NULL\n WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})"; CRM_Core_DAO::executeQuery($updateLineItem); } $amountLevel = array(); $totalParticipant = $participantCount = 0; if (!empty($updateLines)) { foreach ($updateLines as $valueId => $vals) { $taxAmount = "NULL"; if (isset($vals['tax_amount'])) { $taxAmount = $vals['tax_amount']; } $amountLevel[] = $vals['label'] . ' - ' . (double) $vals['qty']; if (isset($vals['participant_count'])) { $participantCount = $vals['participant_count']; $totalParticipant += $vals['participant_count']; } $updateLineItem = "\nUPDATE civicrm_line_item li\nSET li.qty = {$vals['qty']},\n li.line_total = {$vals['line_total']},\n li.tax_amount = {$taxAmount},\n li.unit_price = {$vals['unit_price']},\n li.participant_count = {$participantCount},\n li.label = %1\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n (price_field_value_id = {$valueId})\n"; CRM_Core_DAO::executeQuery($updateLineItem, array(1 => array($vals['label'], 'String'))); } } // insert new 'adjusted amount' transaction entry and update contribution entry. // ensure entity_financial_trxn table has a linking of it. // insert new line items if (!empty($insertLines)) { foreach ($insertLines as $valueId => $lineParams) { $lineParams['entity_table'] = 'civicrm_participant'; $lineParams['entity_id'] = $participantId; $lineParams['contribution_id'] = $contributionId; $lineObj = CRM_Price_BAO_LineItem::create($lineParams); } } // the recordAdjustedAmt code would execute over here $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); if (count($ids) > 1) { $total = 0; foreach ($ids as $val) { $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant'); } $updatedAmount = $total; } else { $updatedAmount = $params['amount']; } if (strlen($params['tax_amount']) != 0) { $taxAmount = $params['tax_amount']; } else { $taxAmount = "NULL"; } $displayParticipantCount = ''; if ($totalParticipant > 0) { $displayParticipantCount = ' Participant Count -' . $totalParticipant; } $updateAmountLevel = NULL; if (!empty($amountLevel)) { $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR; } $trxn = self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel); $trxnId = array(); if ($trxn) { $trxnId['id'] = $trxn->id; foreach ($financialItemsArray as $updateFinancialItemInfoValues) { CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId); if (!empty($updateFinancialItemInfoValues['tax'])) { $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount']; $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description']; if (!empty($updateFinancialItemInfoValues['financial_account_id'])) { $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id']; } CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId); } } } $fetchCon = array('id' => $contributionId); $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); // insert financial items if (!empty($insertLines)) { foreach ($insertLines as $valueId => $lineParams) { $lineParams['entity_table'] = 'civicrm_participant'; $lineParams['entity_id'] = $participantId; $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray); // insert financial items // ensure entity_financial_trxn table has a linking of it. $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnId); if (isset($lineObj->tax_amount)) { CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnId); } } } // update participant fee_amount column $partUpdateFeeAmt['id'] = $participantId; $getUpdatedLineItems = "SELECT *\nFROM civicrm_line_item\nWHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)"; $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems); while ($getUpdatedLineItemsDAO->fetch()) { $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (double) $getUpdatedLineItemsDAO->qty; } $partUpdateFeeAmt['fee_level'] = implode(', ', $line); $partUpdateFeeAmt['fee_amount'] = $params['amount']; self::add($partUpdateFeeAmt); //activity creation self::addActivityForSelection($participantId, 'Change Registration'); }
/** * Format profile contact parameters. * * @param array $params * @param $fields * @param int $contactID * @param int $ufGroupId * @param null $ctype * @param bool $skipCustom * * @return array */ public static function formatProfileContactParams(&$params, &$fields, $contactID = NULL, $ufGroupId = NULL, $ctype = NULL, $skipCustom = FALSE) { $data = $contactDetails = array(); // get the contact details (hier) if ($contactID) { list($details, $options) = self::getHierContactDetails($contactID, $fields); $contactDetails = $details[$contactID]; $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails); $data['contact_sub_type'] = CRM_Utils_Array::value('contact_sub_type', $contactDetails); } else { //we should get contact type only if contact if ($ufGroupId) { $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId); //special case to handle profile with only contact fields if ($data['contact_type'] == 'Contact') { $data['contact_type'] = 'Individual'; } elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) { $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']); } } elseif ($ctype) { $data['contact_type'] = $ctype; } else { $data['contact_type'] = 'Individual'; } } //fix contact sub type CRM-5125 if (array_key_exists('contact_sub_type', $params) && !empty($params['contact_sub_type'])) { $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, (array) $params['contact_sub_type']) . CRM_Core_DAO::VALUE_SEPARATOR; } elseif (array_key_exists('contact_sub_type_hidden', $params) && !empty($params['contact_sub_type_hidden'])) { // if profile was used, and had any subtype, we obtain it from there $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, (array) $params['contact_sub_type_hidden']) . CRM_Core_DAO::VALUE_SEPARATOR; } if ($ctype == 'Organization') { $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails); } elseif ($ctype == 'Household') { $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails); } $locationType = array(); $count = 1; if ($contactID) { //add contact id $data['contact_id'] = $contactID; $primaryLocationType = self::getPrimaryLocationType($contactID); } else { $defaultLocation = CRM_Core_BAO_LocationType::getDefault(); $defaultLocationId = $defaultLocation->id; } // get the billing location type $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); $billingLocationTypeId = array_search('Billing', $locationTypes); $blocks = array('email', 'phone', 'im', 'openid'); $multiplFields = array('url'); // prevent overwritten of formatted array, reset all block from // params if it is not in valid format (since import pass valid format) foreach ($blocks as $blk) { if (array_key_exists($blk, $params) && !is_array($params[$blk])) { unset($params[$blk]); } } $primaryPhoneLoc = NULL; $session = CRM_Core_Session::singleton(); foreach ($params as $key => $value) { $fieldName = $locTypeId = $typeId = NULL; list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3); //store original location type id $actualLocTypeId = $locTypeId; if ($locTypeId == 'Primary') { if ($contactID) { if (in_array($fieldName, $blocks)) { $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName); } else { $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address'); } $primaryLocationType = $locTypeId; } else { $locTypeId = $defaultLocationId; } } if (is_numeric($locTypeId) && !in_array($fieldName, $multiplFields) && substr($fieldName, 0, 7) != 'custom_') { $index = $locTypeId; if (is_numeric($typeId)) { $index .= '-' . $typeId; } if (!in_array($index, $locationType)) { $locationType[$count] = $index; $count++; } $loc = CRM_Utils_Array::key($index, $locationType); $blockName = in_array($fieldName, $blocks) ? $fieldName : 'address'; $data[$blockName][$loc]['location_type_id'] = $locTypeId; //set is_billing true, for location type "Billing" if ($locTypeId == $billingLocationTypeId) { $data[$blockName][$loc]['is_billing'] = 1; } if ($contactID) { //get the primary location type if ($locTypeId == $primaryLocationType) { $data[$blockName][$loc]['is_primary'] = 1; } } elseif ($locTypeId == $defaultLocationId) { $data[$blockName][$loc]['is_primary'] = 1; } if (in_array($fieldName, array('phone'))) { if ($typeId) { $data['phone'][$loc]['phone_type_id'] = $typeId; } else { $data['phone'][$loc]['phone_type_id'] = ''; } $data['phone'][$loc]['phone'] = $value; //special case to handle primary phone with different phone types // in this case we make first phone type as primary if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) { $primaryPhoneLoc = $loc; } if ($loc != $primaryPhoneLoc) { unset($data['phone'][$loc]['is_primary']); } } elseif ($fieldName == 'phone_ext') { $data['phone'][$loc]['phone_ext'] = $value; } elseif ($fieldName == 'email') { $data['email'][$loc]['email'] = $value; } elseif ($fieldName == 'im') { if (isset($params[$key . '-provider_id'])) { $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id']; } if (strpos($key, '-provider_id') !== FALSE) { $data['im'][$loc]['provider_id'] = $params[$key]; } else { $data['im'][$loc]['name'] = $value; } } elseif ($fieldName == 'openid') { $data['openid'][$loc]['openid'] = $value; } else { if ($fieldName === 'state_province') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['state_province_id'] = $value; } elseif (empty($value)) { $data['address'][$loc]['state_province_id'] = ''; } else { $data['address'][$loc]['state_province'] = $value; } } elseif ($fieldName === 'country') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['country_id'] = $value; } elseif (empty($value)) { $data['address'][$loc]['country_id'] = ''; } else { $data['address'][$loc]['country'] = $value; } } elseif ($fieldName === 'county') { $data['address'][$loc]['county_id'] = $value; } elseif ($fieldName == 'address_name') { $data['address'][$loc]['name'] = $value; } elseif (substr($fieldName, 0, 14) === 'address_custom') { $data['address'][$loc][substr($fieldName, 8)] = $value; } else { $data['address'][$loc][$fieldName] = $value; } } } else { if (substr($key, 0, 4) === 'url-') { $websiteField = explode('-', $key); $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1]; $data['website'][$websiteField[1]]['url'] = $value; } elseif (in_array($key, self::$_greetingTypes, TRUE)) { //save email/postal greeting and addressee values if any, CRM-4575 $data[$key . '_id'] = $value; } elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) { // for autocomplete transfer hidden value instead of label if ($params[$key] && isset($params[$key . '_id'])) { $value = $params[$key . '_id']; } // we need to append time with date if ($params[$key] && isset($params[$key . '_time'])) { $value .= ' ' . $params[$key . '_time']; } // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128 if (($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN) == 0 && ($value == '' || !isset($value))) { continue; } $valueId = NULL; if (!empty($params['customRecordValues'])) { if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) { foreach ($params['customRecordValues'] as $recId => $customFields) { if (is_array($customFields) && !empty($customFields)) { foreach ($customFields as $customFieldName) { if ($customFieldName == $key) { $valueId = $recId; break; } } } } } } $type = $data['contact_type']; if (!empty($data['contact_sub_type'])) { $type = $data['contact_sub_type']; $type = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($type, CRM_Core_DAO::VALUE_SEPARATOR)); // generally a contact even if, has multiple subtypes the parent-type is going to be one only // and since formatCustomField() would be interested in parent type, lets consider only one subtype // as the results going to be same. $type = $type[0]; } CRM_Core_BAO_CustomField::formatCustomField($customFieldId, $data['custom'], $value, $type, $valueId, $contactID); } elseif ($key == 'edit') { continue; } else { if ($key == 'location') { foreach ($value as $locationTypeId => $field) { foreach ($field as $block => $val) { if ($block == 'address' && array_key_exists('address_name', $val)) { $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name']; } } } } if ($key == 'phone' && isset($params['phone_ext'])) { $data[$key] = $value; foreach ($value as $cnt => $phoneBlock) { if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) { $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext'); } } } elseif (in_array($key, array('nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id')) && ($value == '' || !isset($value)) && ($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN) == 0) { // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value // to avoid update with empty values continue; } else { $data[$key] = $value; } } } } if (!isset($data['contact_type'])) { $data['contact_type'] = 'Individual'; } //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone) $privacy = CRM_Core_SelectValues::privacy(); foreach ($privacy as $key => $value) { if (array_key_exists($key, $fields)) { // do not reset values for existing contacts, if fields are added to a profile if (array_key_exists($key, $params)) { $data[$key] = $params[$key]; if (empty($params[$key])) { $data[$key] = 0; } } elseif (!$contactID) { $data[$key] = 0; } } } return array($data, $contactDetails); }
/** * format params for update and fill mode * * @param $params array referance to an array containg all the * values for import * @param $onDuplicate int * @param $cid int contact id */ function formatParams(&$params, $onDuplicate, $cid) { if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) { return; } $contactParams = array('contact_id' => $cid); $defaults = array(); $contactObj = CRM_Contact_BAO_Contact::retrieve($contactParams, $defaults); $modeUpdate = $modeFill = false; if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) { $modeUpdate = true; } if ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) { $modeFill = true; } require_once 'CRM/Core/BAO/CustomGroup.php'; $groupTree = CRM_Core_BAO_CustomGroup::getTree($params['contact_type'], CRM_Core_DAO::$_nullObject, $cid, 0, null); CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults, false, false); $contact = get_object_vars($contactObj); $location = null; foreach ($params as $key => $value) { if ($key == 'id' || $key == 'contact_type') { continue; } if ($key == 'location') { $location = true; } else { if (in_array($key, array('email_greeting', 'postal_greeting', 'addressee'))) { // CRM-4575, need to null custom if ($params["{$key}_id"] != 4) { $params["{$key}_custom"] = 'null'; } unset($params[$key]); } else { if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) { $custom = true; } else { $getValue = CRM_Utils_Array::retrieveValueRecursive($contact, $key); if ($key == 'contact_source') { $params['source'] = $params[$key]; unset($params[$key]); } if ($modeFill && isset($getValue)) { unset($params[$key]); } } } } } if ($location) { for ($loc = 1; $loc <= count($params['location']); $loc++) { //if location block is already present for the contact //then do not fill any data for that location type, CRM-4424 if ($modeFill) { foreach ($contact['location'] as $location => $locationDetails) { $getValue = CRM_Utils_Array::value('location_type_id', $locationDetails); if (isset($getValue) && $getValue == $params['location'][$loc]['location_type_id']) { unset($params['location'][$loc]); break; } } } if (array_key_exists('address', $contact['location'][$loc])) { $fields = array('street_address', 'city', 'state_province_id', 'postal_code', 'postal_code_suffix', 'country_id'); foreach ($fields as $field) { $getValue = CRM_Utils_Array::retrieveValueRecursive($contact['location'][$loc]['address'], $field); if ($modeFill && isset($getValue)) { unset($params['location'][$loc]['address'][$field]); } } } $fields = array('email' => 'email', 'phone' => 'phone', 'im' => 'name'); foreach ($fields as $key => $field) { if (array_key_exists($key, $contact['location'][$loc])) { for ($c = 1; $c <= count($params['location'][$loc][$key]); $c++) { $getValue = CRM_Utils_Array::retrieveValueRecursive($contact['location'][$loc][$key][$c], $field); if ($modeFill && isset($getValue)) { unset($params['location'][$loc][$key][$c][$field]); } } } } } } }
/** * Format params for update and fill mode. * * @param array $params * reference to an array containing all the. * values for import * @param int $onDuplicate * @param int $cid * contact id. */ public function formatParams(&$params, $onDuplicate, $cid) { if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) { return; } $contactParams = array('contact_id' => $cid); $defaults = array(); $contactObj = CRM_Contact_BAO_Contact::retrieve($contactParams, $defaults); $modeUpdate = $modeFill = FALSE; if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) { $modeUpdate = TRUE; } if ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) { $modeFill = TRUE; } $groupTree = CRM_Core_BAO_CustomGroup::getTree($params['contact_type'], CRM_Core_DAO::$_nullObject, $cid, 0, NULL); CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults, FALSE, FALSE); $locationFields = array('email' => 'email', 'phone' => 'phone', 'im' => 'name', 'website' => 'website', 'address' => 'address'); $contact = get_object_vars($contactObj); foreach ($params as $key => $value) { if ($key == 'id' || $key == 'contact_type') { continue; } if (array_key_exists($key, $locationFields)) { continue; } elseif (in_array($key, array('email_greeting', 'postal_greeting', 'addressee'))) { // CRM-4575, need to null custom if ($params["{$key}_id"] != 4) { $params["{$key}_custom"] = 'null'; } unset($params[$key]); } elseif ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) { $custom = TRUE; } else { $getValue = CRM_Utils_Array::retrieveValueRecursive($contact, $key); if ($key == 'contact_source') { $params['source'] = $params[$key]; unset($params[$key]); } if ($modeFill && isset($getValue)) { unset($params[$key]); } } } foreach ($locationFields as $locKeys) { if (is_array(CRM_Utils_Array::value($locKeys, $params))) { foreach ($params[$locKeys] as $key => $value) { if ($modeFill) { $getValue = CRM_Utils_Array::retrieveValueRecursive($contact, $locKeys); if (isset($getValue)) { foreach ($getValue as $cnt => $values) { if ($locKeys == 'website') { if ($getValue[$cnt]['website_type_id'] == $params[$locKeys][$key]['website_type_id']) { unset($params[$locKeys][$key]); } } else { if (!empty($getValue[$cnt]['location_type_id']) && !empty($params[$locKeys][$key]['location_type_id']) && $getValue[$cnt]['location_type_id'] == $params[$locKeys][$key]['location_type_id']) { unset($params[$locKeys][$key]); } } } } } } if (count($params[$locKeys]) == 0) { unset($params[$locKeys]); } } } }
/** * build form elements. * params object $form object of the form * * @param CRM_Core_Form $form * The form object that we are operating on. * @param int $contactId * Contact id. * @param int $type * What components are we interested in. * @param bool $visibility * Visibility of the field. * @param null $isRequired * @param string $groupName * If used for building group block. * @param string $tagName * If used for building tag block. * @param string $fieldName * This is used in batch profile(i.e to build multiple blocks). * * @param string $groupElementType * */ public static function buildQuickForm(&$form, $contactId = 0, $type = self::ALL, $visibility = FALSE, $isRequired = NULL, $groupName = 'Group(s)', $tagName = 'Tag(s)', $fieldName = NULL, $groupElementType = 'checkbox') { if (!isset($form->_tagGroup)) { $form->_tagGroup = array(); } // NYSS 5670 if (!$contactId && !empty($form->_contactId)) { $contactId = $form->_contactId; } $type = (int) $type; if ($type & self::GROUP) { $fName = 'group'; if ($fieldName) { $fName = $fieldName; } $groupID = isset($form->_grid) ? $form->_grid : NULL; if ($groupID && $visibility) { $ids = array($groupID => $groupID); } else { if ($visibility) { $group = CRM_Core_PseudoConstant::allGroup(); } else { $group = CRM_Core_PseudoConstant::group(); } $ids = $group; } if ($groupID || !empty($group)) { $groups = CRM_Contact_BAO_Group::getGroupsHierarchy($ids); $attributes['skiplabel'] = TRUE; $elements = array(); $groupsOptions = array(); foreach ($groups as $id => $group) { // make sure that this group has public visibility if ($visibility && $group['visibility'] == 'User and User Admin Only') { continue; } if ($groupElementType == 'select') { $groupsOptions[$id] = $group['title']; } else { $form->_tagGroup[$fName][$id]['description'] = $group['description']; $elements[] =& $form->addElement('advcheckbox', $id, NULL, $group['title'], $attributes); } } if ($groupElementType == 'select' && !empty($groupsOptions)) { $form->add('select', $fName, $groupName, $groupsOptions, FALSE, array('id' => $fName, 'multiple' => 'multiple', 'class' => 'crm-select2')); $form->assign('groupCount', count($groupsOptions)); } if ($groupElementType == 'checkbox' && !empty($elements)) { $form->addGroup($elements, $fName, $groupName, ' <br />'); $form->assign('groupCount', count($elements)); if ($isRequired) { $form->addRule($fName, ts('%1 is a required field.', array(1 => $groupName)), 'required'); } } $form->assign('groupElementType', $groupElementType); } } if ($type & self::TAG) { $fName = 'tag'; if ($fieldName) { $fName = $fieldName; } $form->_tagGroup[$fName] = 1; // get the list of all the categories $tags = new CRM_Core_BAO_Tag(); $tree = $tags->getTree('civicrm_contact', TRUE); // let's not load jstree if there are not children. This also fixes blank // display at the beginning of checkboxes $loadJsTree = CRM_Utils_Array::retrieveValueRecursive($tree, 'children'); $form->assign('loadjsTree', FALSE); if (!empty($loadJsTree)) { // CODE FROM CRM/Tag/Form/Tag.php // CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'packages/jquery/plugins/jstree/jquery.jstree.js', 0, 'html-header', FALSE)->addStyleFile('civicrm', 'packages/jquery/plugins/jstree/themes/default/style.css', 0, 'html-header'); $form->assign('loadjsTree', TRUE); } $elements = array(); self::climbtree($form, $tree, $elements); $form->addGroup($elements, $fName, $tagName, '<br />'); $form->assign('tagCount', count($elements)); $form->assign('tree', $tree); $form->assign('tag', $tree); $form->assign('entityID', $contactId); $form->assign('entityTable', 'civicrm_contact'); if ($isRequired) { $form->addRule($fName, ts('%1 is a required field.', array(1 => $tagName)), 'required'); } // build tag widget $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_contact'); CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_contact', $contactId, FALSE, TRUE); } $form->assign('tagGroup', $form->_tagGroup); }
/** * @param $params * @param $participantId * @param $contributionId * @param $feeBlock * @param $lineItems * @param $paidAmount * @param $priceSetId */ static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) { $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses); $pendngRefundStatusId = array_search('Pending refund', $contributionStatuses); $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant'); CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems); // get the submitted foreach ($feeBlock as $id => $values) { CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems); $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id'); } $insertLines = $submittedLineItems; $submittedFieldValueIds = array_keys($submittedLineItems); $updateLines = array(); foreach ($previousLineItems as $id => $previousLineItem) { // check through the submitted items if the previousItem exists, // if found in submitted items, do not use it for new item creations if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) { // if submitted line items are existing don't fire INSERT query unset($insertLines[$previousLineItem['price_field_value_id']]); // for updating the line items i.e. use-case - once deselect-option selecting again if ($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) { $updateLines[$previousLineItem['price_field_value_id']]['qty'] = $submittedLineItems[$previousLineItem['price_field_value_id']]['qty']; $updateLines[$previousLineItem['price_field_value_id']]['line_total'] = $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']; } } } $submittedFields = implode(', ', $submittedFieldId); $submittedFieldValues = implode(', ', $submittedFieldValueIds); if (!empty($submittedFields) && !empty($submittedFieldValues)) { $updateLineItem = "UPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nSET li.qty = 0,\n li.line_total = 0.00\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n (price_field_value_id NOT IN ({$submittedFieldValues}))\n"; CRM_Core_DAO::executeQuery($updateLineItem); // gathering necessary info to record negative (deselected) financial_item $updateFinancialItem = "\n SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id\n FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})\nGROUP BY li.entity_table, li.entity_id, price_field_value_id\n"; $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem); $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'ASC', TRUE); $trxnId['id'] = $trxn['financialTrxnId']; $updateFinancialItemInfoValues = array(); while ($updateFinancialItemInfoDAO->fetch()) { $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO; $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis'); // the below params are not needed unset($updateFinancialItemInfoValues['id']); unset($updateFinancialItemInfoValues['created_date']); // if not submitted and difference is not 0 make it negative if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) { // INSERT negative financial_items $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount']; CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId); } elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) { $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount']; CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId); } } } if (!empty($updateLines)) { foreach ($updateLines as $valueId => $vals) { $updateLineItem = "\nUPDATE civicrm_line_item li\nSET li.qty = {$vals['qty']},\n li.line_total = {$vals['line_total']}\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n (price_field_value_id = {$valueId})\n"; CRM_Core_DAO::executeQuery($updateLineItem); } } // insert new 'adjusted amount' transaction entry and update contribution entry. // ensure entity_financial_trxn table has a linking of it. // insert new line items foreach ($insertLines as $valueId => $lineParams) { $lineParams['entity_table'] = 'civicrm_participant'; $lineParams['entity_id'] = $participantId; $lineObj = CRM_Price_BAO_LineItem::create($lineParams); } // the recordAdjustedAmt code would execute over here $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); if (count($ids) > 1) { $total = 0; foreach ($ids as $val) { $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant'); } $updatedAmount = $total; } else { $updatedAmount = $params['amount']; } self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId); $fetchCon = array('id' => $contributionId); $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); // insert financial items foreach ($insertLines as $valueId => $lineParams) { $lineParams['entity_table'] = 'civicrm_participant'; $lineParams['entity_id'] = $participantId; $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray); // insert financial items // ensure entity_financial_trxn table has a linking of it. $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution); } // update participant fee_amount column $partUpdateFeeAmt['id'] = $participantId; $partUpdateFeeAmt['fee_amount'] = $params['amount']; self::add($partUpdateFeeAmt); //activity creation self::addActivityForSelection($participantId, 'Change Registration'); }
public function getContactTokenReplacement($token, &$contact, $html = false, $returnBlankToken = false) { if (self::$_tokens['contact'] == null) { /* This should come from UF */ self::$_tokens['contact'] = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields('All')), array('checksum', 'contact_id')); } /* Construct value from $token and $contact */ $value = null; // check if the token we were passed is valid // we have to do this because this function is // called only when we find a token in the string if (!in_array($token, self::$_tokens['contact'])) { $value = "{contact.{$token}}"; } else { if ($token == 'checksum') { require_once 'CRM/Contact/BAO/Contact/Utils.php'; $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($contact['contact_id']); $value = "cs={$cs}"; } else { $value = CRM_Utils_Array::retrieveValueRecursive($contact, $token); } } if (!$html) { $value = str_replace('&', '&', $value); } // if null then return actual token if ($returnBlankToken && !$value) { $value = "{contact.{$token}}"; } return $value; }
/** * Build the form object. * * @return void */ public function buildQuickForm() { // get categories for the contact id $entityTag = CRM_Core_BAO_EntityTag::getTag($this->_entityID, $this->_entityTable); $this->assign('tagged', $entityTag); // get the list of all the categories $allTag = CRM_Core_BAO_Tag::getTagsUsedFor($this->_entityTable); // need to append the array with the " checked " if contact is tagged with the tag foreach ($allTag as $tagID => $varValue) { if (in_array($tagID, $entityTag)) { $tagAttribute = array('checked' => 'checked', 'id' => "tag_{$tagID}"); } else { $tagAttribute = array('id' => "tag_{$tagID}"); } $tagChk[$tagID] = $this->createElement('checkbox', $tagID, '', '', $tagAttribute); } $this->addGroup($tagChk, 'tagList', NULL, NULL, TRUE); $tags = new CRM_Core_BAO_Tag(); $tree = $tags->getTree($this->_entityTable, TRUE); // let's not load jstree if there are not children. This also fixes blank // display at the beginning of checkboxes $loadJsTree = CRM_Utils_Array::retrieveValueRecursive($tree, 'children'); $this->assign('loadjsTree', FALSE); if (!empty($loadJsTree)) { CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'packages/jquery/plugins/jstree/jquery.jstree.js', 0, 'html-header', FALSE)->addStyleFile('civicrm', 'packages/jquery/plugins/jstree/themes/default/style.css', 0, 'html-header'); $this->assign('loadjsTree', TRUE); } $this->assign('tree', $tree); $this->assign('tag', $allTag); //build tag widget $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_contact'); CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, $this->_entityTable, $this->_entityID); }
/** * A function to build an array of information required by merge function and the merge UI. * * @param int $mainId main contact with whom merge has to happen * @param int $otherId duplicate contact which would be deleted after merge operation * * @return array|bool|int * @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(); } // get all contact subtypes $contactSubTypes = CRM_Contact_BAO_ContactType::subTypePairs(NULL, TRUE, ''); // 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, 'contact_sub_type' => $value, 'communication_style_id' => $value); if (!empty($contact['preferred_communication_method'])) { // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method']; $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR; } $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method')); CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names); if (!empty($contact['contact_sub_type'])) { $specialValues[$moniker]['contact_sub_type'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $contact['contact_sub_type']); // fix contact sub type label for contact with sub type $subtypes = array(); foreach ($contact['contact_sub_type'] as $key => $value) { $subtypes[] = CRM_Utils_Array::retrieveValueRecursive($contactSubTypes, $value); } $contact['contact_sub_type_display'] = $specialValues[$moniker]['contact_sub_type_display'] = implode(', ', $subtypes); } if (!empty($contact['communication_style'])) { $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style']; } } static $optionValueFields = array(); if (empty($optionValueFields)) { $optionValueFields = CRM_Core_OptionValue::getFields(); } foreach ($optionValueFields as $field => $params) { $fields[$field]['title'] = $params['title']; } $diffs = self::findDifferences($main, $other); $rows = $elements = $relTableElements = $migrationInfo = array(); 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('individual_prefix', $contact); $value = CRM_Utils_Array::value('prefix_id', $contact); $field = 'prefix_id'; } elseif ($field == 'individual_suffix' || $field == 'suffix_id') { $label = CRM_Utils_Array::value('individual_suffix', $contact); $value = CRM_Utils_Array::value('suffix_id', $contact); $field = 'suffix_id'; } $rows["move_{$field}"][$moniker] = $label; if ($moniker == 'other') { //CRM-14334 if ($value === NULL || $value == '') { $value = 'null'; } if ($value === 0 or $value === '0') { $value = $qfZeroBug; } if (is_array($value) && empty($value[1])) { $value[1] = NULL; } $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value); $migrationInfo["move_{$field}"] = $value; } } $rows["move_{$field}"]['title'] = $fields[$field]['title']; } // handle location blocks. $locationBlocks = array('email', 'phone', 'address'); $locations = array(); foreach ($locationBlocks as $block) { foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) { $cnt = 1; $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3)); $count = $values['count']; if ($count) { if ($count > $cnt) { foreach ($values['values'] as $value) { if ($block == 'address') { CRM_Core_BAO_Address::fixAddress($value); $display = CRM_Utils_Address::format($value); $locations[$moniker][$block][$cnt] = $value; $locations[$moniker][$block][$cnt]['display'] = $display; } else { $locations[$moniker][$block][$cnt] = $value; } $cnt++; } } else { $id = $values['id']; if ($block == 'address') { CRM_Core_BAO_Address::fixAddress($values['values'][$id]); $display = CRM_Utils_Address::format($values['values'][$id]); $locations[$moniker][$block][$cnt] = $values['values'][$id]; $locations[$moniker][$block][$cnt]['display'] = $display; } else { $locations[$moniker][$block][$cnt] = $values['values'][$id]; } } } } } $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $mainLocBlock = $locBlockIds = array(); $locBlockIds['main'] = $locBlockIds['other'] = array(); foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) { $name = strtolower($block); foreach (array('main', 'other') as $moniker) { $locIndex = CRM_Utils_Array::value($moniker, $locations); $blockValue = CRM_Utils_Array::value($name, $locIndex, array()); if (empty($blockValue)) { $locValue[$moniker][$name] = 0; $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array(); } else { $locValue[$moniker][$name] = TRUE; foreach ($blockValue as $count => $blkValues) { $fldName = $name; $locTypeId = $blkValues['location_type_id']; if ($name == 'im') { $fldName = 'name'; } if ($name == 'address') { $fldName = 'display'; } $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName, $blkValues); $locTypes[$moniker][$name][$count] = $locTypeId; if ($moniker == 'main' && in_array($name, $locationBlocks)) { $mainLocBlock["main_{$name}{$locTypeId}"] = CRM_Utils_Array::value($fldName, $blkValues); $locBlockIds['main'][$name][$locTypeId] = $blkValues['id']; } else { $locBlockIds[$moniker][$name][$count] = $blkValues['id']; } } } } if ($locValue['other'][$name] != 0) { foreach ($locLabel['other'][$name] as $count => $value) { $locTypeId = $locTypes['other'][$name][$count]; $rows["move_location_{$name}_{$count}"]['other'] = $value; $rows["move_location_{$name}_{$count}"]['main'] = CRM_Utils_Array::value($count, $locLabel['main'][$name]); $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId])); $elements[] = array('advcheckbox', "move_location_{$name}_{$count}"); $migrationInfo["move_location_{$name}_{$count}"] = 1; // make sure default location type is always on top $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId); $locTypeValues = $allLocationTypes; $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]); unset($locTypeValues[$mainLocTypeId]); // keep 1-1 mapping for address - location type. $js = NULL; if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) { $js = array('onChange' => "mergeBlock('{$name}', this, {$count} );"); } $elements[] = array('select', "location[{$name}][{$count}][locTypeId]", NULL, $defaultLocType + $locTypeValues, $js); // keep location-type-id same as that of other-contact $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId; if ($name != 'address') { $elements[] = array('advcheckbox', "location[{$name}][{$count}][operation]", NULL, ts('add new')); // always use add operation $migrationInfo['location'][$name][$count]['operation'] = 1; } } } } // add the related tables and unset the ones that don't sport any of the duplicate contact's info $config = CRM_Core_Config::singleton(); $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId); $mainUser = NULL; if ($mainUfId) { // d6 compatible if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { $mainUser = user_load($mainUfId); } elseif ($config->userFramework == 'Joomla') { $mainUser = JFactory::getUser($mainUfId); } } $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId); $otherUser = NULL; if ($otherUfId) { // d6 compatible if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { $otherUser = user_load($otherUfId); } elseif ($config->userFramework == 'Joomla') { $otherUser = JFactory::getUser($otherUfId); } } $relTables = CRM_Dedupe_Merger::relTables(); $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId); $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId); foreach ($relTables as $name => $null) { if (!in_array($name, $activeRelTables) && !($name == 'rel_table_users' && in_array($name, $activeMainRelTables))) { unset($relTables[$name]); continue; } $relTableElements[] = array('checkbox', "move_{$name}"); $migrationInfo["move_{$name}"] = 1; $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); if ($name == 'rel_table_users') { $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']); $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']); $find = array('$ufid', '$ufname'); if ($mainUser) { $replace = array($mainUfId, $mainUser->name); $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']); } if ($otherUser) { $replace = array($otherUfId, $otherUser->name); $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']); } } if ($name == 'rel_table_memberships') { $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new')); $migrationInfo["operation"]["move_{$name}"]['add'] = 1; } } foreach ($relTables as $name => $null) { $relTables["move_{$name}"] = $relTables[$name]; unset($relTables[$name]); } // handle custom fields $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, CRM_Utils_Array::value('contact_sub_type', $main)); $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, CRM_Utils_Array::value('contact_sub_type', $other)); CRM_Core_DAO::freeResult(); foreach ($otherTree as $gid => $group) { $foundField = FALSE; if (!isset($group['fields'])) { continue; } foreach ($group['fields'] as $fid => $field) { if (in_array($fid, $diffs['custom'])) { if (!$foundField) { $rows["custom_group_{$gid}"]['title'] = $group['title']; $foundField = TRUE; } if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) { foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE); } } $value = "null"; if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) { foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE); if ($values['data'] === 0 || $values['data'] === '0') { $values['data'] = $qfZeroBug; } $value = $values['data'] ? $values['data'] : $value; } } $rows["move_custom_{$fid}"]['title'] = $field['label']; $elements[] = array('advcheckbox', "move_custom_{$fid}", NULL, NULL, NULL, $value); $migrationInfo["move_custom_{$fid}"] = $value; } } } $result = array('rows' => $rows, 'elements' => $elements, 'rel_table_elements' => $relTableElements, 'main_loc_block' => $mainLocBlock, 'rel_tables' => $relTables, 'main_details' => $main, 'other_details' => $other, 'migration_info' => $migrationInfo); $result['main_details']['loc_block_ids'] = $locBlockIds['main']; $result['other_details']['loc_block_ids'] = $locBlockIds['other']; return $result; }
/** * Function to check whether allow to edit any contact's subtype * on the basis of custom data and relationship of specific subtype * * @param int $contactId contact id. * @param string $subType subtype. * * @return boolean true/false. * @static */ static function allowEditSubtype($contactId, $subType, $groupTree = null) { if (!$contactId || empty($subType)) { return true; } require_once 'CRM/Contact/BAO/ContactType.php'; $contactType = CRM_Contact_BAO_ContactType::getBasicType($subType); $subTypeGroupTree = array(); if (!array_key_exists($contactType . '_' . $subType, $subTypeGroupTree) && empty($groupTree)) { $form = null; require_once 'CRM/Core/BAO/CustomGroup.php'; $subTypeGroupTree[$contactType . '_' . $subType] = CRM_Core_BAO_CustomGroup::getTree($contactType, $form, $contactId, null, $subType, null); } else { $subTypeGroupTree[$contactType . '_' . $subType] = $groupTree; } if (!empty($subTypeGroupTree[$contactType . '_' . $subType])) { foreach ($subTypeGroupTree[$contactType . '_' . $subType] as $groupId => $groupDetails) { if (CRM_Utils_Array::value('extends_entity_column_value', $groupDetails)) { $customValue = CRM_Utils_Array::retrieveValueRecursive($groupDetails['fields'], 'element_value'); if (!empty($customValue)) { return false; } else { continue; } } } } if (!array_key_exists('rel_' . $contactType . '_' . $subType, $subTypeGroupTree)) { require_once 'CRM/Contact/BAO/Relationship.php'; $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, $contactType, false, 'label', true, $subType, true); $subTypeGroupTree['rel_' . $contactType . '_' . $subType] = $relationshipTypes; } $relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId); if (!empty($relationships)) { foreach ($relationships as $relId => $details) { if (in_array($details['relation'], $subTypeGroupTree['rel_' . $contactType . '_' . $subType])) { return false; } else { continue; } } } return true; }
/** * function to add/edit/register contacts through profile. * * @params array $params Array of profile fields to be edited/added. * @params int $contactID contact_id of the contact to be edited/added. * @params array $fields array of fields from UFGroup * @params int $addToGroupID specifies the default group to which contact is added. * @params int $ufGroupId uf group id (profile id) * @param string $ctype contact type * * @return int contact id created/edited * @static * @access public */ static function createProfileContact(&$params, &$fields, $contactID = null, $addToGroupID = null, $ufGroupId = null, $ctype = null, $visibility = false) { // add ufGroupID to params array ( CRM-2012 ) if ($ufGroupId) { $params['uf_group_id'] = $ufGroupId; } require_once 'CRM/Utils/Hook.php'; if ($contactID) { $editHook = true; CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params); } else { $editHook = false; CRM_Utils_Hook::pre('create', 'Profile', null, $params); } $data = $contactDetails = array(); // get the contact details (hier) if ($contactID) { list($details, $options) = self::getHierContactDetails($contactID, $fields); $contactDetails = $details[$contactID]; $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails); } else { //we should get contact type only if contact if ($ufGroupId) { require_once "CRM/Core/BAO/UFField.php"; $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId); //special case to handle profile with only contact fields if ($data['contact_type'] == 'Contact') { $data['contact_type'] = 'Individual'; } else { if (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) { $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']); } } } else { if ($ctype) { $data['contact_type'] = $ctype; } else { $data['contact_type'] = 'Individual'; } } } //fix contact sub type CRM-5125 if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) { $data['contact_sub_type'] = $subType; } else { if ($subType = CRM_Utils_Array::value('contact_sub_type_hidden', $params)) { // if profile was used, and had any subtype, we obtain it from there $data['contact_sub_type'] = $subType; } } if ($ctype == "Organization") { $data["organization_name"] = $contactDetails["organization_name"]; } else { if ($ctype == "Household") { $data["household_name"] = $contactDetails["household_name"]; } } $locationType = array(); $count = 1; if ($contactID) { //add contact id $data['contact_id'] = $contactID; $primaryLocationType = self::getPrimaryLocationType($contactID); } else { require_once "CRM/Core/BAO/LocationType.php"; $defaultLocation =& CRM_Core_BAO_LocationType::getDefault(); $defaultLocationId = $defaultLocation->id; } // get the billing location type $locationTypes =& CRM_Core_PseudoConstant::locationType(); $billingLocationTypeId = array_search('Billing', $locationTypes); $blocks = array('email', 'phone', 'im', 'openid'); // prevent overwritten of formatted array, reset all block from // params if it is not in valid format (since import pass valid format) foreach ($blocks as $blk) { if (array_key_exists($blk, $params) && !is_array($params[$blk])) { unset($params[$blk]); } } $primaryPhoneLoc = null; foreach ($params as $key => $value) { $fieldName = $locTypeId = $typeId = null; list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3); //store original location type id $actualLocTypeId = $locTypeId; if ($locTypeId == 'Primary') { if ($contactID) { $locTypeId = $primaryLocationType; } else { $locTypeId = $defaultLocationId; } } if (is_numeric($locTypeId)) { $index = $locTypeId; if (is_numeric($typeId)) { $index .= '-' . $typeId; } if (!in_array($index, $locationType)) { $locationType[$count] = $index; $count++; } require_once 'CRM/Utils/Array.php'; $loc = CRM_Utils_Array::key($index, $locationType); $blockName = 'address'; if (in_array($fieldName, $blocks)) { $blockName = $fieldName; } $data[$blockName][$loc]['location_type_id'] = $locTypeId; //set is_billing true, for location type "Billing" if ($locTypeId == $billingLocationTypeId) { $data[$blockName][$loc]['is_billing'] = 1; } if ($contactID) { //get the primary location type if ($locTypeId == $primaryLocationType) { $data[$blockName][$loc]['is_primary'] = 1; } } else { if (($locTypeId == $defaultLocationId || $locTypeId == $billingLocationTypeId) && ($loc == 1 || !CRM_Utils_Array::retrieveValueRecursive($data['location'][$loc - 1], 'is_primary'))) { $data[$blockName][$loc]['is_primary'] = 1; } } if ($fieldName == 'phone') { if ($typeId) { $data['phone'][$loc]['phone_type_id'] = $typeId; } else { $data['phone'][$loc]['phone_type_id'] = ''; } $data['phone'][$loc]['phone'] = $value; //special case to handle primary phone with different phone types // in this case we make first phone type as primary if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) { $primaryPhoneLoc = $loc; } if ($loc != $primaryPhoneLoc) { unset($data['phone'][$loc]['is_primary']); } } else { if ($fieldName == 'email') { $data['email'][$loc]['email'] = $value; } else { if ($fieldName == 'im') { if (isset($params[$key . '-provider_id'])) { $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id']; } $data['im'][$loc]['name'] = $value; } else { if ($fieldName == 'openid') { $data['openid'][$loc]['openid'] = $value; } else { if ($fieldName === 'state_province') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['state_province_id'] = $value; } else { $data['address'][$loc]['state_province'] = $value; } } else { if ($fieldName === 'country') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['country_id'] = $value; } else { $data['address'][$loc]['country'] = $value; } } else { if ($fieldName === 'county') { $data['address'][$loc]['address']['county_id'] = $value; } else { if ($fieldName == 'address_name') { $data['address'][$loc]['name'] = $value; } else { $data['address'][$loc][$fieldName] = $value; } } } } } } } } } else { if ($key === 'individual_suffix') { $data['suffix_id'] = $value; } else { if ($key === 'individual_prefix') { $data['prefix_id'] = $value; } else { if ($key === 'gender') { $data['gender_id'] = $value; } else { if ($key === 'email_greeting') { //save email/postal greeting and addressee values if any, CRM-4575 $data['email_greeting_id'] = $value; } else { if ($key === 'postal_greeting') { $data['postal_greeting_id'] = $value; } else { if ($key === 'addressee') { $data['addressee_id'] = $value; } else { if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) { // for autocomplete transfer hidden value instead of label if ($params[$key] && isset($params[$key . '_id'])) { $value = $params[$key . '_id']; } // we need to append time with date if ($params[$key] && isset($params[$key . '_time'])) { $value .= ' ' . $params[$key . '_time']; } $type = CRM_Utils_Array::value('contact_sub_type', $data) ? $data['contact_sub_type'] : $data['contact_type']; CRM_Core_BAO_CustomField::formatCustomField($customFieldId, $data['custom'], $value, $type, null, $contactID); } else { if ($key == 'edit') { continue; } else { if ($key == 'location') { foreach ($value as $locationTypeId => $field) { foreach ($field as $block => $val) { if ($block == 'address' && array_key_exists('address_name', $val)) { $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name']; } } } } $data[$key] = $value; } } } } } } } } } } // FIX ME: need to check if we need this code // //make sure primary location is at first position in location array // if ( isset( $data['location'] ) && count( $data['location'] ) > 1 ) { // // if first location is primary skip manipulation // if ( !isset($data['location'][1]['is_primary']) ) { // //find the key for primary location // foreach ( $data['location'] as $primaryLocationKey => $value ) { // if ( isset( $value['is_primary'] ) ) { // break; // } // } // // // swap first location with primary location // $tempLocation = $data['location'][1]; // $data['location'][1] = $data['location'][$primaryLocationKey]; // $data['location'][$primaryLocationKey] = $tempLocation; // } // } if (!isset($data['contact_type'])) { $data['contact_type'] = 'Individual'; } if (CRM_Core_Permission::access('Quest')) { $studentFieldPresent = 0; foreach ($fields as $name => $field) { // check if student fields present require_once 'CRM/Quest/BAO/Student.php'; if (!$studentFieldPresent && array_key_exists($name, CRM_Quest_BAO_Student::exportableFields())) { $studentFieldPresent = 1; } } } //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone) $privacy = CRM_Core_SelectValues::privacy(); foreach ($privacy as $key => $value) { if (array_key_exists($key, $fields)) { if ($params[$key]) { $data[$key] = $params[$key]; } else { $data[$key] = 0; } } } // manage is_opt_out if (array_key_exists('is_opt_out', $fields)) { $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, false); $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, false); $data['is_opt_out'] = $isOptOut; // on change, create new civicrm_subscription_history entry if ($wasOptOut != $isOptOut && CRM_Utils_Array::value('contact_id', $contactDetails)) { $shParams = array('contact_id' => $contactDetails['contact_id'], 'status' => $isOptOut ? 'Removed' : 'Added', 'method' => 'Web'); CRM_Contact_BAO_SubscriptionHistory::create($shParams); } } require_once 'CRM/Contact/BAO/Contact.php'; if ($data['contact_type'] != 'Student') { $contact =& self::create($data); } // contact is null if the profile does not have any contact fields if ($contact) { $contactID = $contact->id; } if (!$contactID) { CRM_Core_Error::fatal('Cannot proceed without a valid contact id'); } // Process group and tag if (CRM_Utils_Array::value('group', $fields)) { $method = 'Admin'; // this for sure means we are coming in via profile since i added it to fix // removing contacts from user groups -- lobo if ($visibility) { $method = 'Web'; } CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method); } if (CRM_Utils_Array::value('tag', $fields)) { require_once 'CRM/Core/BAO/EntityTag.php'; CRM_Core_BAO_EntityTag::create($params['tag'], $contactID); } // Set status = 'Pending' if profileDoubleOptIn = 1. CRM-5905 require_once 'CRM/Core/Config.php'; $config = CRM_Core_Config::singleton(); if ($config->profileDoubleOptIn) { $groupStatus = 'Pending'; } //to add profile in default group if (is_array($addToGroupID)) { $contactIds = array($contactID); foreach ($addToGroupID as $groupId) { CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId, 'Admin', $groupStatus); } } else { if ($addToGroupID) { $contactIds = array($contactID); CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID, 'Admin', $groupStatus); } } //to update student record if (CRM_Core_Permission::access('Quest') && $studentFieldPresent) { $ids = array(); $dao =& new CRM_Quest_DAO_Student(); $dao->contact_id = $contactID; if ($dao->find(true)) { $ids['id'] = $dao->id; } $ssids = array(); $studentSummary =& new CRM_Quest_DAO_StudentSummary(); $studentSummary->contact_id = $contactID; if ($studentSummary->find(true)) { $ssids['id'] = $studentSummary->id; } $params['contact_id'] = $contactID; //fixed for check boxes $specialFields = array('educational_interest', 'college_type', 'college_interest', 'test_tutoring'); foreach ($specialFields as $field) { if ($params[$field]) { $params[$field] = implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, array_keys($params[$field])); } } CRM_Quest_BAO_Student::create($params, $ids); CRM_Quest_BAO_Student::createStudentSummary($params, $ssids); } // reset the group contact cache for this group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); if ($editHook) { CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params); } else { CRM_Utils_Hook::post('create', 'Profile', $contactID, $params); } return $contactID; }
static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) { $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses); $pendngRefundStatusId = array_search('Pending refund', $contributionStatuses); $fetchCon = array('id' => $contributionId); $contributionObj = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant'); CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems); // get the submitted foreach ($feeBlock as $id => $values) { CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems); $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id'); } $insertLines = $submittedLineItems; $submittedFieldValueIds = array_keys($submittedLineItems); foreach ($previousLineItems as $id => $previousLineItem) { // check through the submitted items if the previousItem exists, // if found in submitted items, do not use it for new item creations if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) { unset($insertLines[$previousLineItem['price_field_value_id']]); } } $submittedFields = implode(', ', $submittedFieldId); $submittedFieldValues = implode(', ', $submittedFieldValueIds); if (!empty($submittedFields) && !empty($submittedFieldValues)) { // if previous line item is not submitted in selection, update the line total and QTY to '0' $updateLineItem = "\nUPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nINNER JOIN civicrm_entity_financial_trxn eft\n ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')\nSET li.qty = 0,\n li.line_total = 0.00,\n fi.amount = 0.00,\n eft.amount = 0.00\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n (price_field_value_id NOT IN ({$submittedFieldValues}) OR price_field_id NOT IN ({$submittedFields}))\n"; CRM_Core_DAO::executeQuery($updateLineItem); } // insert new line items foreach ($insertLines as $valueId => $lineParams) { $lineParams['entity_table'] = 'civicrm_participant'; $lineParams['entity_id'] = $participantId; $lineObj = CRM_Price_BAO_LineItem::create($lineParams); // insert financial items // ensure entity_financial_trxn table has a linking of it. $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $contributionObj); } // insert new 'adjusted amount' transaction entry and update contribution entry. // ensure entity_financial_trxn table has a linking of it. $updatedAmount = $params['amount']; $balanceAmt = $updatedAmount - $paidAmount; if ($balanceAmt) { if ($balanceAmt > 0) { $contributionStatusVal = $partiallyPaidStatusId; } elseif ($balanceAmt < 0) { $contributionStatusVal = $pendngRefundStatusId; } // update contribution status and total amount without trigger financial code // as this is handled in current BAO function used for change selection $updatedContributionDAO = new CRM_Contribute_BAO_Contribution(); $updatedContributionDAO->id = $contributionId; $updatedContributionDAO->contribution_status_id = $contributionStatusVal; $updatedContributionDAO->total_amount = $updatedAmount; $updatedContributionDAO->save(); /* * adjusted amount financial_trxn creation, * adjusted amount line_item creation, * adjusted amount financial_item creations, * adjusted amount enitity_financial_trxn creation */ $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contributionId), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); $prevTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); $fetchPrevTrxn['id'] = $prevTrxnId['financialTrxnId']; $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId); $adjustedTrxnValues = array('from_financial_account_id' => NULL, 'to_financial_account_id' => $toFinancialAccount, 'trxn_date' => date('YmdHis'), 'total_amount' => $balanceAmt, 'currency' => $updatedContribution->currency, 'status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'), 'payment_instrument_id' => $updatedContribution->payment_instrument_id, 'contribution_id' => $updatedContribution->id); $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues); // record line item $adjustPaymentLineParams = array('total_amount' => $updatedAmount, 'financial_type_id' => $updatedContribution->financial_type_id); $setId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name'); CRM_Price_BAO_LineItem::getLineItemArray($adjustPaymentLineParams); $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); $defaultPriceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($setId)); $fieldID = key($defaultPriceSet['fields']); $adjustPaymentLineParams['line_item'][$setId][$fieldID]['entity_id'] = $updatedContribution->id; $adjustPaymentLineParams['line_item'][$setId][$fieldID]['entity_table'] = 'civicrm_contribution'; $adjustPaymentLine = CRM_Price_BAO_LineItem::create($adjustPaymentLineParams['line_item'][$setId][$fieldID]); // record financial item $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); $itemStatus = NULL; if ($updatedContribution->contribution_status_id == array_search('Pending refund', $contributionStatuses)) { $itemStatus = array_search('Paid', $financialItemStatus); } elseif ($updatedContribution->contribution_status_id == array_search('Partially paid', $contributionStatuses)) { $itemStatus = array_search('Partially paid', $financialItemStatus); } $params = array('transaction_date' => CRM_Utils_Date::isoToMysql($updatedContribution->receive_date), 'contact_id' => $updatedContribution->contact_id, 'amount' => $balanceAmt, 'currency' => $updatedContribution->currency, 'entity_table' => 'civicrm_line_item', 'entity_id' => $adjustPaymentLine->id, 'description' => ($adjustPaymentLine->qty != 1 ? $lineItem->qty . ' of ' : '') . ' ' . $adjustPaymentLine->label, 'status_id' => $itemStatus, 'financial_account_id' => $prevItem->financial_account_id); CRM_Financial_BAO_FinancialItem::create($params, NULL, array('id' => $adjustedTrxn->id)); } //activity creation$contributionStatuses self::addActivityForSelection($participantId, 'Change Registration'); }