Example #1
0
 function where()
 {
     $approved = CRM_Core_PseudoConstant::getKey('CRM_Grant_DAO_Grant', 'status_id', 'Approved', array('labelColumn' => 'name'));
     $whereClause = "\nWHERE {$this->_aliases['civicrm_grant']}.amount_total IS NOT NULL\n  AND {$this->_aliases['civicrm_grant']}.amount_total > 0";
     $this->_where = $whereClause . " AND {$this->_aliases['civicrm_grant']}.status_id = {$approved} ";
     foreach ($this->_columns as $tableName => $table) {
         if (array_key_exists('filters', $table)) {
             foreach ($table['filters'] as $fieldName => $field) {
                 $clause = NULL;
                 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
                     $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
                     $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
                     $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
                     if ($relative || $from || $to) {
                         $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
                     }
                 } else {
                     $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
                     if ($fieldName == 'grant_report_received' && CRM_Utils_Array::value("{$fieldName}_value", $this->_params) === 0) {
                         $op = 'nll';
                         $this->_params["{$fieldName}_value"] = NULL;
                     }
                     if ($op) {
                         $clause = $this->whereClause($field, $op, CRM_Utils_Array::value("{$fieldName}_value", $this->_params), CRM_Utils_Array::value("{$fieldName}_min", $this->_params), CRM_Utils_Array::value("{$fieldName}_max", $this->_params));
                     }
                 }
                 if (!empty($clause)) {
                     $clauses[] = $clause;
                     $this->_where .= " AND " . implode(' AND ', $clauses);
                     $this->_whereClause = $whereClause . " AND " . implode(' AND ', $clauses);
                 }
             }
         }
     }
 }
Example #2
0
 /**
  * Setup function.
  */
 public function setUp()
 {
     parent::setUp();
     $this->_apiversion = 3;
     $this->_individualId = $this->individualCreate();
     $this->_params = array('contact_id' => $this->_individualId, 'receive_date' => '20120511', 'total_amount' => 100.0, 'financial_type_id' => $this->_financialTypeId, 'non_deductible_amount' => 10.0, 'fee_amount' => 5.0, 'net_amount' => 95.0, 'source' => 'SSF', 'contribution_status_id' => 1);
     $this->_processorParams = array('domain_id' => 1, 'name' => 'Dummy', 'payment_processor_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'), 'financial_account_id' => 12, 'is_active' => 1, 'user_name' => '', 'url_site' => 'http://dummy.com', 'url_recur' => 'http://dummy.com', 'billing_mode' => 1);
     $this->paymentProcessorID = $this->processorCreate();
     $this->_pageParams = array('title' => 'Test Contribution Page', 'financial_type_id' => 1, 'currency' => 'USD', 'financial_account_id' => 1, 'payment_processor' => $this->paymentProcessorID, 'is_active' => 1, 'is_allow_other_amount' => 1, 'min_amount' => 10, 'max_amount' => 1000);
 }
Example #3
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     $values = $ids = array();
     $params = array('id' => $this->get('id'));
     CRM_Pledge_BAO_Pledge::getValues($params, $values, $ids);
     $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit']));
     if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) {
         $sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"];
         $dao = new CRM_Core_DAO();
         $dao->query($sql);
         if ($dao->fetch()) {
             $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}");
             $values["honor_display"] = "<A href = {$url}>" . $dao->display_name . "</A>";
         }
         $honor = CRM_Core_PseudoConstant::get('CRM_Pledge_DAO_Pledge', 'honor_type_id');
         $values['honor_type'] = $honor[$values['honor_type_id']];
     }
     // handle custom data.
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', $this, $params['id']);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $params['id']);
     if (!empty($values['contribution_page_id'])) {
         $values['contribution_page'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $values['contribution_page_id'], 'title');
     }
     $values['financial_type'] = CRM_Utils_Array::value($values['financial_type_id'], CRM_Contribute_PseudoConstant::financialType());
     if ($values['status_id']) {
         $values['pledge_status'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $values['status_id']);
     }
     $url = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
     $this->assign('displayName', $displayName);
     $title = $displayName . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($values['pledge_amount']) . ' - ' . $values['financial_type'] . ')';
     // add Pledge to Recent Items
     CRM_Utils_Recent::add($title, $url, $values['id'], 'Pledge', $values['contact_id'], NULL, $recentOther);
     // Check if this is default domain contact CRM-10482
     if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) {
         $displayName .= ' (' . ts('default organization') . ')';
     }
     // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
     CRM_Utils_System::setTitle(ts('View Pledge by') . ' ' . $displayName);
     // do check for campaigns
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $values['campaign'] = $campaigns[$campaignId];
     }
     $this->assign($values);
 }
 public function setUp()
 {
     parent::setUp();
     $this->_individualId = $this->individualCreate();
     $this->_orgId = $this->organizationCreate(NULL);
     $this->params = array('title' => "Test Contribution Page" . substr(sha1(rand()), 0, 7), 'financial_type_id' => 1, 'payment_processor' => 1, 'currency' => 'NZD', 'goal_amount' => 350, 'is_pay_later' => 1, 'pay_later_text' => 'I will pay later', 'pay_later_receipt' => "I will pay later", 'is_monetary' => TRUE, 'is_billing_required' => TRUE);
     $this->_priceSetParams = array('name' => 'tax_contribution' . substr(sha1(rand()), 0, 7), 'title' => 'contributiontax' . substr(sha1(rand()), 0, 7), 'is_active' => 1, 'help_pre' => "Where does your goat sleep", 'help_post' => "thank you for your time", 'extends' => 2, 'financial_type_id' => 3, 'is_quick_config' => 0, 'is_reserved' => 0);
     // Financial Account with 20% tax rate
     $financialAccountSetparams = array('name' => 'vat full taxrate account' . substr(sha1(rand()), 0, 7), 'contact_id' => $this->_orgId, 'financial_account_type_id' => 2, 'is_tax' => 1, 'tax_rate' => 20.0, 'is_reserved' => 0, 'is_active' => 1, 'is_default' => 0);
     $financialAccount = $this->callAPISuccess('financial_account', 'create', $financialAccountSetparams);
     $this->financialAccountId = $financialAccount['id'];
     // Financial type having 'Sales Tax Account is' with liability financail account
     $financialType = array('name' => 'grassvariety1' . substr(sha1(rand()), 0, 7), 'is_reserved' => 0, 'is_active' => 1);
     $priceField = $this->callAPISuccess('financial_type', 'create', $financialType);
     $this->financialtypeID = $priceField['id'];
     $financialRelationParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $this->financialtypeID, 'account_relationship' => 10, 'financial_account_id' => $this->financialAccountId);
     $financialRelation = CRM_Financial_BAO_FinancialTypeAccount::add($financialRelationParams);
     // Financial type with 5% tax rate
     $financialAccHalftax = array('name' => 'vat half taxrate account' . substr(sha1(rand()), 0, 7), 'contact_id' => $this->_orgId, 'financial_account_type_id' => 2, 'is_tax' => 1, 'tax_rate' => 5.0, 'is_reserved' => 0, 'is_active' => 1, 'is_default' => 0);
     $halfFinancialAccount = CRM_Financial_BAO_FinancialAccount::add($financialAccHalftax);
     $this->halfFinancialAccId = $halfFinancialAccount->id;
     $halfFinancialtypeHalftax = array('name' => 'grassvariety2' . substr(sha1(rand()), 0, 7), 'is_reserved' => 0, 'is_active' => 1);
     $halfFinancialType = CRM_Financial_BAO_FinancialType::add($halfFinancialtypeHalftax);
     $this->halfFinancialTypeId = $halfFinancialType->id;
     $financialRelationHalftax = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $this->halfFinancialTypeId, 'account_relationship' => 10, 'financial_account_id' => $this->halfFinancialAccId);
     $halfFinancialRelation = CRM_Financial_BAO_FinancialTypeAccount::add($financialRelationHalftax);
     // Enable component contribute setting
     $contributeSetting = array('invoicing' => 1, 'invoice_prefix' => 'INV_', 'credit_notes_prefix' => 'CN_', 'due_date' => 10, 'due_date_period' => 'days', 'notes' => '', 'is_email_pdf' => 1, 'tax_term' => 'Sales Tax', 'tax_display_settings' => 'Inclusive');
     $setInvoiceSettings = Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
     // Payment Processor
     $paymentProceParams = array('domain_id' => 1, 'name' => 'dummy' . substr(sha1(rand()), 0, 7), 'payment_processor_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'), 'financial_account_id' => 12, 'is_active' => 1, 'is_default' => 1, 'user_name' => 'dummy', 'url_site' => 'http://dummy.com', 'url_recur' => 'http://dummyrecur.com', 'class_name' => 'Payment_Dummy', 'billing_mode' => 1, 'is_recur' => 1, 'payment_type' => 1);
     $result = $this->callAPISuccess('payment_processor', 'create', $paymentProceParams);
     $this->_ids['paymentProcessID'] = $result['id'];
     require_once 'api/v3/examples/PaymentProcessor/Create.php';
     $this->assertAPISuccess($result);
 }
Example #5
0
 public function postProcess()
 {
     $formValues = $this->exportValues();
     // 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');
     }
     $formValues['main_details'] = $this->_mainDetails;
     $formValues['other_details'] = $this->_otherDetails;
     CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $formValues);
     $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
     $message = '<ul><li>' . ts('%1 has been updated.', array(1 => $name)) . '</li><li>' . ts('Contact ID %1 has been deleted.', array(1 => $this->_oid)) . '</li></ul>';
     CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
     //create activity for merge
     //To do: this should be refactored into BAO layer at some point.
     $messageActivity = ts('Contact ID %1 has been merged and deleted.', array(1 => $this->_oid));
     $activityParams = array('subject' => $messageActivity, 'source_contact_id' => $session->get('userID'), 'target_contact_id' => $this->_cid, 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Contact Merged'), 'status_id' => 'Completed', 'priority_id' => 'Normal', 'activity_date_time' => date('YmdHis'));
     civicrm_api3('activity', 'create', $activityParams);
     $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
     if (!empty($formValues['_qf_Merge_submit'])) {
         $listParamsURL = "reset=1&action=update&rgid={$this->_rgid}";
         if ($this->_gid) {
             $listParamsURL .= "&gid={$this->_gid}";
         }
         $lisitingURL = CRM_Utils_System::url('civicrm/contact/dedupefind', $listParamsURL);
         CRM_Utils_System::redirect($lisitingURL);
     }
     if (!empty($formValues['_qf_Merge_done'])) {
         CRM_Utils_System::redirect($url);
     }
     if ($this->next && $this->_mergeId) {
         $cacheKey = "merge {$this->_contactType}";
         $cacheKey .= $this->_rgid ? "_{$this->_rgid}" : '_0';
         $cacheKey .= $this->_gid ? "_{$this->_gid}" : '_0';
         $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND\n                                                                 pn.entity_id2 = de.contact_id2 )";
         $where = "de.id IS NULL";
         $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
         if (!empty($pos) && $pos['next']['id1'] && $pos['next']['id2']) {
             $urlParam = "reset=1&cid={$pos['next']['id1']}&oid={$pos['next']['id2']}&mergeId={$pos['next']['mergeId']}&action=update";
             if ($this->_rgid) {
                 $urlParam .= "&rgid={$this->_rgid}";
             }
             if ($this->_gid) {
                 $urlParam .= "&gid={$this->_gid}";
             }
             $url = CRM_Utils_System::url('civicrm/contact/merge', $urlParam);
         }
     }
     CRM_Utils_System::redirect($url);
 }
Example #6
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     // process url params
     if ($this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive')) {
         $this->assign('contactID', $this->_contactID);
     }
     if ($this->_caseID = CRM_Utils_Request::retrieve('case_id', 'Positive')) {
         $this->assign('case_id', $this->_caseID);
         // get Vacancy ID
         $vacancyID = CRM_HRRecruitment_BAO_HRVacancy::getVacancyIDByCase($this->_caseID);
         //Get application and evaluaiton profile IDs
         foreach (array('application_profile', 'evaluation_profile') as $profileName) {
             $dao = new CRM_Core_DAO_UFJoin();
             $dao->module = 'Vacancy';
             $dao->entity_id = $vacancyID;
             $dao->module_data = $profileName;
             $dao->find(TRUE);
             $profile[$profileName] = $dao->uf_group_id;
         }
         //Check for existing Evaluation activity type and assign variables to tpl
         $this->assign('actions', 'add');
         $params = array('activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Evaluation'));
         $caseActivity = CRM_Case_BAO_Case::getCaseActivity($this->_caseID, $params, $this->_contactID);
         foreach ($caseActivity as $caseActivity) {
             $evalID = $caseActivity['id'];
             $this->assign('id', $evalID);
             $this->assign('actions', 'update');
         }
         $this->_profileID = $profile['application_profile'];
         $this->_evalProfileID = $profile['evaluation_profile'];
     }
 }
Example #7
0
 /**
  * Get the list the export fields.
  *
  * @param int $selectAll
  *   User preference while export.
  * @param array $ids
  *   Contact ids.
  * @param array $params
  *   Associated array of fields.
  * @param string $order
  *   Order by clause.
  * @param array $fields
  *   Associated array of fields.
  * @param array $moreReturnProperties
  *   Additional return fields.
  * @param int $exportMode
  *   Export mode.
  * @param string $componentClause
  *   Component clause.
  * @param string $componentTable
  *   Component table.
  * @param bool $mergeSameAddress
  *   Merge records if they have same address.
  * @param bool $mergeSameHousehold
  *   Merge records if they belong to the same household.
  *
  * @param array $exportParams
  * @param string $queryOperator
  *
  */
 public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND')
 {
     $headerRows = $returnProperties = array();
     $primary = $paymentFields = $selectedPaymentFields = FALSE;
     $origFields = $fields;
     $relationField = NULL;
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE);
     $queryMode = self::getQueryMode($exportMode);
     if ($fields) {
         //construct return properties
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = $imProviderId = NULL;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id separately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } elseif ($fieldName == 'im') {
                 $imProviderId = CRM_Utils_Array::value(3, $value);
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (!empty($value[2])) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 'Primary';
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(4, $value);
                     }
                 } elseif (!empty($value[4])) {
                     $relationField = CRM_Utils_Array::value(4, $value);
                     $relLocTypeId = CRM_Utils_Array::value(5, $value);
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(6, $value);
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } elseif ($relIMProviderId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                     } else {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                     }
                     $relPhoneTypeId = $relIMProviderId = NULL;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } elseif (is_numeric($locTypeId)) {
                 if ($phoneTypeId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                 } elseif ($imProviderId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                 } else {
                     $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                 }
             } else {
                 //hack to fix component fields
                 //revert mix of event_id and title
                 if ($fieldName == 'event_id') {
                     $returnProperties['event_id'] = 1;
                 } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT && array_key_exists($fieldName, self::componentPaymentFields())) {
                     $selectedPaymentFields = TRUE;
                     $paymentTableId = 'participant_id';
                     $returnProperties[$fieldName] = 1;
                 } else {
                     $returnProperties[$fieldName] = 1;
                 }
             }
         }
         $returnProperties[self::defaultReturnProperty($exportMode)] = 1;
     } else {
         $primary = TRUE;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = FALSE;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = TRUE;
                 $paymentTableId = 'participant_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = TRUE;
                 $paymentTableId = 'membership_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = TRUE;
                 $paymentTableId = 'pledge_payment_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
                 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
                 $componentReturnProperties = array_merge($componentReturnProperties, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
             }
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset non exportable fields for components
             $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id');
             foreach ($nonExpoFields as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($mergeSameAddress) {
         //make sure the addressee fields are selected
         //while using merge same address feature
         $returnProperties['addressee'] = 1;
         $returnProperties['postal_greeting'] = 1;
         $returnProperties['email_greeting'] = 1;
         $returnProperties['street_name'] = 1;
         $returnProperties['household_name'] = 1;
         $returnProperties['street_address'] = 1;
         $returnProperties['city'] = 1;
         $returnProperties['state_province'] = 1;
         // some columns are required for assistance incase they are not already present
         $exportParams['merge_same_address']['temp_columns'] = array();
         $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
         foreach ($tempColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
                 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
             }
         }
     }
     if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
         // If an Additional Group is selected, then all contacts in that group are
         // added to the export set (filtering out duplicates).
         $query = "\nINSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id";
         CRM_Core_DAO::executeQuery($query);
     }
     if ($moreReturnProperties) {
         // fix for CRM-7066
         if (!empty($moreReturnProperties['group'])) {
             unset($moreReturnProperties['group']);
             $moreReturnProperties['groups'] = 1;
         }
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $exportParams['postal_mailing_export']['temp_columns'] = array();
     if ($exportParams['exportOption'] == 2 && isset($exportParams['postal_mailing_export']) && CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1) {
         $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
         foreach ($postalColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
             }
         }
     }
     // rectify params to what proximity search expects if there is a value for prox_distance
     // CRM-7021
     if (!empty($params)) {
         CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
     }
     $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, $queryMode, FALSE, TRUE, TRUE, NULL, $queryOperator);
     //sort by state
     //CRM-15301
     $query->_sort = $order;
     list($select, $from, $where, $having) = $query->query();
     if ($mergeSameHousehold == 1) {
         if (!$returnProperties['id']) {
             $returnProperties['id'] = 1;
         }
         //also merge Head of Household
         $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
         $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
         foreach ($returnProperties as $key => $value) {
             if (!array_key_exists($key, $contactRelationshipTypes)) {
                 $returnProperties[$relationKeyMOH][$key] = $value;
                 $returnProperties[$relationKeyHOH][$key] = $value;
             }
         }
         unset($returnProperties[$relationKeyMOH]['location_type']);
         unset($returnProperties[$relationKeyMOH]['im_provider']);
         unset($returnProperties[$relationKeyHOH]['location_type']);
         unset($returnProperties[$relationKeyHOH]['im_provider']);
     }
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, NULL, FALSE, FALSE, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
                 $relIDs = $ids;
             } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
                 $query = "SELECT contact_id FROM civicrm_activity_contact\n                              WHERE activity_id IN ( " . implode(',', $ids) . ") AND\n                              record_type_id = {$sourceID}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 while ($dao->fetch()) {
                     $relIDs[] = $dao->contact_id;
                 }
             } else {
                 $component = self::exportComponent($exportMode);
                 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                     $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
                 } else {
                     $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
                 }
             }
             $relationshipJoin = $relationshipClause = '';
             if (!$selectAll && $componentTable) {
                 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
             } elseif (!empty($relIDs)) {
                 $relID = implode(',', $relIDs);
                 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
             }
             $relationFrom = " {$relationFrom}\n                INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}\n                {$relationshipJoin} ";
             //check for active relationship status only
             $today = date('Ymd');
             $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
             $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
             $relationGroupBy = " GROUP BY crel.{$contactA}";
             $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
             $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationHaving} {$relationGroupBy}";
             $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
             while ($allRelContactDAO->fetch()) {
                 //FIX Me: Migrate this to table rather than array
                 // build the array of all related contacts
                 $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO;
             }
             $allRelContactDAO->free();
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (!empty($returnProperties['groups'])) {
         $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
         $newClause = " ( {$oldClause} AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if (!$selectAll && $componentTable) {
         $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id ";
     } elseif ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     // CRM-13982 - check if is deleted
     $excludeTrashed = TRUE;
     foreach ($params as $value) {
         if ($value[0] == 'contact_is_deleted') {
             $excludeTrashed = FALSE;
         }
     }
     $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )";
     if (empty($where)) {
         $where = "WHERE {$trashClause}";
     } else {
         $where .= " AND {$trashClause}";
     }
     $queryString = "{$select} {$from} {$where} {$having}";
     $groupBy = "";
     if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || CRM_Utils_Array::value('notes', $returnProperties) || $queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) {
         $groupBy = " GROUP BY contact_a.id";
     }
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $groupBy = 'GROUP BY civicrm_contribution.id';
             if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
                 // especial group by  when soft credit columns are included
                 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
             }
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $groupBy = 'GROUP BY civicrm_participant.id';
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $groupBy = " GROUP BY civicrm_membership.id";
             break;
     }
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
         $groupBy = " GROUP BY civicrm_activity.id ";
     }
     $queryString .= $groupBy;
     // always add contact_a.id to the ORDER clause
     // so the order is deterministic
     //CRM-15301
     if (strpos('contact_a.id', $order) === FALSE) {
         $order .= ", contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (!empty($returnProperties[$field])) {
             //CRM-15301
             $queryString .= " ORDER BY {$order}";
         }
     }
     $multipleSelectFields = array('preferred_communication_method' => 1);
     $addPaymentHeader = FALSE;
     $paymentDetails = array();
     if ($paymentFields || $selectedPaymentFields) {
         // get payment related in for event and members
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
         //get all payment headers.
         // If we haven't selected specific payment fields, load in all the
         // payment headers.
         if (!$selectedPaymentFields) {
             $paymentHeaders = self::componentPaymentFields();
             if (!empty($paymentDetails)) {
                 $addPaymentHeader = TRUE;
             }
         } else {
             $paymentHeaders = array();
         }
         $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
     }
     $componentDetails = $headerRows = $sqlColumns = array();
     $setHeader = TRUE;
     $rowCount = self::EXPORT_ROW_COUNT;
     $offset = 0;
     // we write to temp table often to avoid using too much memory
     $tempRowCount = 100;
     $count = -1;
     // for CRM-3157 purposes
     $i18n = CRM_Core_I18n::singleton();
     $outputColumns = array();
     //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point
     // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing
     foreach ($returnProperties as $key => $value) {
         $outputColumns[$key] = $value;
     }
     while (1) {
         $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
         $dao = CRM_Core_DAO::executeQuery($limitQuery);
         if ($dao->N <= 0) {
             break;
         }
         while ($dao->fetch()) {
             $count++;
             $row = array();
             //convert the pseudo constants
             // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
             // temporary iterationDAO object to get around it.
             // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
             // these additional properties are NOT reset when the $dao cycles through the while loop
             // nor are they overwritten as they are not in the loop
             // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
             // relevant property is set.
             // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
             // export class before tackling a better architectural fix
             $iterationDAO = clone $dao;
             $query->convertToPseudoNames($iterationDAO);
             //first loop through output columns so that we return what is required, and in same order.
             $relationshipField = 0;
             foreach ($outputColumns as $field => $value) {
                 //we should set header only once
                 if ($setHeader) {
                     $sqlDone = FALSE;
                     // Split campaign into 2 fields for id and title
                     if (substr($field, -14) == 'campaign_title') {
                         $headerRows[] = ts('Campaign Title');
                     } elseif (substr($field, -11) == 'campaign_id') {
                         $headerRows[] = ts('Campaign ID');
                     } elseif (isset($query->_fields[$field]['title'])) {
                         $headerRows[] = $query->_fields[$field]['title'];
                     } elseif ($field == 'phone_type_id') {
                         $headerRows[] = ts('Phone Type');
                     } elseif ($field == 'provider_id') {
                         $headerRows[] = ts('IM Service Provider');
                     } elseif (is_array($value) && $field == 'location') {
                         // fix header for location type case
                         foreach ($value as $ltype => $val) {
                             foreach (array_keys($val) as $fld) {
                                 $type = explode('-', $fld);
                                 $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                 if (!empty($type[1])) {
                                     if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                     } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                     }
                                 }
                                 $headerRows[] = $hdr;
                                 self::sqlColumnDefn($query, $sqlColumns, $hdr);
                             }
                             $sqlDone = TRUE;
                         }
                     } elseif (substr($field, 0, 5) == 'case_') {
                         if ($query->_fields['case'][$field]['title']) {
                             $headerRows[] = $query->_fields['case'][$field]['title'];
                         } elseif ($query->_fields['activity'][$field]['title']) {
                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                         }
                     } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                         $relName = $field;
                         foreach ($value as $relationField => $relationValue) {
                             // below block is same as primary block (duplicate)
                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
                                     $headerName = $field . '-' . $relationField;
                                 } else {
                                     if ($relationField == 'current_employer') {
                                         $headerName = $field . '-' . 'current_employer';
                                     } else {
                                         $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
                                     }
                                 }
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'phone_type_id') {
                                 $headerName = $field . '-' . 'Phone Type';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'provider_id') {
                                 $headerName = $field . '-' . 'Im Service Provider';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'state_province_id') {
                                 $headerName = $field . '-' . 'state_province_id';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif (is_array($relationValue) && $relationField == 'location') {
                                 // fix header for location type case
                                 foreach ($relationValue as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                         if (!empty($type[1])) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                             }
                                         }
                                         $headerName = $field . '-' . $hdr;
                                         $headerRows[] = $headerName;
                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                     }
                                 }
                             }
                         }
                     } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                         $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
                     } else {
                         $headerRows[] = $field;
                     }
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $field);
                     }
                 }
                 // add im_provider to $dao object
                 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
                     $iterationDAO->im_provider = $iterationDAO->provider_id;
                 }
                 //build row values (data)
                 $fieldValue = NULL;
                 if (property_exists($iterationDAO, $field)) {
                     $fieldValue = $iterationDAO->{$field};
                     // to get phone type from phone type id
                     if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
                         $fieldValue = $phoneTypes[$fieldValue];
                     } elseif ($field == 'provider_id' || $field == 'im_provider') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     } elseif ($field == 'master_id') {
                         $masterAddressId = NULL;
                         if (isset($iterationDAO->master_id)) {
                             $masterAddressId = $iterationDAO->master_id;
                         }
                         // get display name of contact that address is shared.
                         $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id);
                     }
                 }
                 if ($field == 'id') {
                     $row[$field] = $iterationDAO->contact_id;
                     // special case for calculated field
                 } elseif ($field == 'source_contact_id') {
                     $row[$field] = $iterationDAO->contact_id;
                 } elseif ($field == 'pledge_balance_amount') {
                     $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
                     // special case for calculated field
                 } elseif ($field == 'pledge_next_pay_amount') {
                     $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
                 } elseif (is_array($value) && $field == 'location') {
                     // fix header for location type case
                     foreach ($value as $ltype => $val) {
                         foreach (array_keys($val) as $fld) {
                             $type = explode('-', $fld);
                             $fldValue = "{$ltype}-" . $type[0];
                             // CRM-14076 - fix label to work as the query object expects
                             // FIXME: We should not be using labels as keys!
                             $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0];
                             if (!empty($type[1])) {
                                 $fldValue .= "-" . $type[1];
                                 $daoField .= "-" . $type[1];
                             }
                             // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                             switch ($fld) {
                                 case 'country':
                                 case 'world_region':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'country'));
                                     break;
                                 case 'state_province':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'province'));
                                     break;
                                 case 'im_provider':
                                     $imFieldvalue = $daoField . "-provider_id";
                                     $row[$fldValue] = CRM_Utils_Array::value($iterationDAO->{$imFieldvalue}, $imProviders);
                                     break;
                                 default:
                                     $row[$fldValue] = $iterationDAO->{$daoField};
                                     break;
                             }
                         }
                     }
                 } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                     $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]);
                     $relationQuery[$field]->convertToPseudoNames($relDAO);
                     foreach ($value as $relationField => $relationValue) {
                         if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                             $fieldValue = $relDAO->{$relationField};
                             if ($relationField == 'phone_type_id') {
                                 $fieldValue = $phoneTypes[$relationValue];
                             } elseif ($relationField == 'provider_id') {
                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                             } elseif (is_object($relDAO) && in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                 //special case for greeting replacement
                                 $fldValue = "{$relationField}_display";
                                 $fieldValue = $relDAO->{$fldValue};
                             }
                         } elseif (is_object($relDAO) && $relationField == 'state_province') {
                             $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
                         } elseif (is_object($relDAO) && $relationField == 'country') {
                             $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
                         } else {
                             $fieldValue = '';
                         }
                         $field = $field . '_';
                         if (array_key_exists($relationField, $multipleSelectFields)) {
                             $param = array($relationField => $fieldValue);
                             $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
                             CRM_Core_OptionGroup::lookupValues($param, $names, FALSE);
                             $fieldValue = $param[$relationField];
                         }
                         if (is_object($relDAO) && $relationField == 'id') {
                             $row[$field . $relationField] = $relDAO->contact_id;
                         } elseif (is_array($relationValue) && $relationField == 'location') {
                             foreach ($relationValue as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (!empty($type[1])) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     // CRM-3157: localise country, region (both have ‘country’ context)
                                     // and state_province (‘province’ context)
                                     switch (TRUE) {
                                         case !is_object($relDAO):
                                             $row[$field . '_' . $fldValue] = '';
                                             break;
                                         case in_array('country', $type):
                                         case in_array('world_region', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country'));
                                             break;
                                         case in_array('state_province', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province'));
                                             break;
                                         default:
                                             $row[$field . '_' . $fldValue] = $relDAO->{$fldValue};
                                             break;
                                     }
                                 }
                             }
                         } elseif (isset($fieldValue) && $fieldValue != '') {
                             //check for custom data
                             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                 $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                             } else {
                                 //normal relationship fields
                                 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                 switch ($relationField) {
                                     case 'country':
                                     case 'world_region':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                         break;
                                     case 'state_province':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                         break;
                                     default:
                                         $row[$field . $relationField] = $fieldValue;
                                         break;
                                 }
                             }
                         } else {
                             // if relation field is empty or null
                             $row[$field . $relationField] = '';
                         }
                     }
                 } elseif (isset($fieldValue) && $fieldValue != '') {
                     //check for custom data
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                     } elseif (array_key_exists($field, $multipleSelectFields)) {
                         //option group fixes
                         $paramsNew = array($field => $fieldValue);
                         if ($field == 'test_tutoring') {
                             $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                             // for  readers group
                         } elseif (substr($field, 0, 4) == 'cmr_') {
                             $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                         } else {
                             $name = array($field => array('newName' => $field, 'groupName' => $field));
                         }
                         CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                         $row[$field] = $paramsNew[$field];
                     } elseif (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                         //special case for greeting replacement
                         $fldValue = "{$field}_display";
                         $row[$field] = $iterationDAO->{$fldValue};
                     } else {
                         //normal fields with a touch of CRM-3157
                         switch ($field) {
                             case 'country':
                             case 'world_region':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                 break;
                             case 'state_province':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                 break;
                             case 'gender':
                             case 'preferred_communication_method':
                             case 'preferred_mail_format':
                             case 'communication_style':
                                 $row[$field] = $i18n->crm_translate($fieldValue);
                                 break;
                             default:
                                 $row[$field] = $fieldValue;
                                 break;
                         }
                     }
                 } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                     $paymentData = CRM_Utils_Array::value($iterationDAO->{$paymentTableId}, $paymentDetails);
                     $payFieldMapper = array('componentPaymentField_total_amount' => 'total_amount', 'componentPaymentField_contribution_status' => 'contribution_status', 'componentPaymentField_payment_instrument' => 'pay_instru', 'componentPaymentField_transaction_id' => 'trxn_id', 'componentPaymentField_received_date' => 'receive_date');
                     $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
                 } else {
                     // if field is empty or null
                     $row[$field] = '';
                 }
             }
             // add payment headers if required
             if ($addPaymentHeader && $paymentFields) {
                 $headerRows = array_merge($headerRows, $paymentHeaders);
                 foreach (array_keys($paymentHeaders) as $paymentHdr) {
                     self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
                 }
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = FALSE;
             // If specific payment fields have been selected for export, payment
             // data will already be in $row. Otherwise, add payment related
             // information, if appropriate.
             if ($addPaymentHeader) {
                 if (!$selectedPaymentFields) {
                     if ($paymentFields) {
                         $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
                         if (!is_array($paymentData) || empty($paymentData)) {
                             $paymentData = $nullContributionDetails;
                         }
                         $row = array_merge($row, $paymentData);
                     } elseif (!empty($paymentDetails)) {
                         $row = array_merge($row, $nullContributionDetails);
                     }
                 }
             }
             //remove organization name for individuals if it is set for current employer
             if (!empty($row['contact_type']) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) {
                 $row['organization_name'] = '';
             }
             // add component info
             // write the row to a file
             $componentDetails[] = $row;
             // output every $tempRowCount rows
             if ($count % $tempRowCount == 0) {
                 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
                 $componentDetails = array();
             }
         }
         $dao->free();
         $offset += $rowCount;
     }
     if ($exportTempTable) {
         self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
         // do merge same address and merge same household processing
         if ($mergeSameAddress) {
             self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
         }
         // merge the records if they have corresponding households
         if ($mergeSameHousehold) {
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
         }
         // fix the headers for rows with relationship type
         if (!empty($relName)) {
             self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
         }
         // if postalMailing option is checked, exclude contacts who are deceased, have
         // "Do not mail" privacy setting, or have no street address
         if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && $exportParams['postal_mailing_export']['postal_mailing_export'] == 1) {
             self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         }
         // call export hook
         CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // now write the CSV file
         self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // delete the export temp table and component table
         $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
         CRM_Core_DAO::executeQuery($sql);
         CRM_Utils_System::civiExit();
     } else {
         CRM_Core_Error::fatal(ts('No records to export'));
     }
 }
Example #8
0
 /**
  * Get the transaction id for the (latest) refund associated with a contribution.
  *
  * @param int $contributionID
  * @return string
  */
 public static function getRefundTransactionIDs($contributionID)
 {
     $refundStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
     return self::getFinancialTrxnId($contributionID, 'DESC', FALSE, " AND cft.status_id = {$refundStatusID}");
 }
Example #9
0
 /**
  * Get the result of the payment.
  *
  * Usually this will be pending but the calling layer has a chance to set the result.
  *
  * This would apply in particular when the form accepts status id.
  *
  * Note that currently this payment class is only being used to manage the 'billing block' aspect
  * of pay later. However, a longer term idea is that by treating 'pay-later' as 'just another processor'
  * will allow code simplification.
  *
  * @return int
  */
 protected function getResult()
 {
     if (!$this->result) {
         $this->setResult(CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'status_id', 'Pending'));
     }
     return $this->result;
 }
 /**
  * Test the submit function of the membership form.
  */
 public function testSubmitRecurCompleteInstant()
 {
     $form = $this->getForm();
     $processor = Civi\Payment\System::singleton()->getById($this->_paymentProcessorID);
     $processor->setDoDirectPaymentResult(array('payment_status_id' => 1, 'trxn_id' => 'kettles boil water', 'fee_amount' => 0.29));
     $this->callAPISuccess('MembershipType', 'create', array('id' => $this->membershipTypeAnnualFixedID, 'duration_unit' => 'month', 'duration_interval' => 1, 'auto_renew' => TRUE));
     $this->createLoggedInUser();
     $form->preProcess();
     $form->_contactID = $this->_individualId;
     $params = $this->getBaseSubmitParams();
     $form->_mode = 'test';
     $form->testSubmit($params);
     $membership = $this->callAPISuccessGetSingle('Membership', array('contact_id' => $this->_individualId));
     $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', array('contact_id' => $this->_individualId));
     $this->assertEquals($contributionRecur['id'], $membership['contribution_recur_id']);
     $this->assertEquals(0, $contributionRecur['is_email_receipt']);
     $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contributionRecur['modified_date'])));
     $this->assertNotEmpty($contributionRecur['invoice_id']);
     print_r($contributionRecur);
     // @todo fix this part!
     /*
         $this->assertEquals(CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id',
         'In Progress'), $contributionRecur['contribution_status_id']);
         $this->assertNotEmpty($contributionRecur['next_sched_contribution_date']);
     */
     $this->assertEquals(CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Credit Card'), $contributionRecur['payment_instrument_id']);
     $contribution = $this->callAPISuccess('Contribution', 'getsingle', array('contact_id' => $this->_individualId, 'is_test' => TRUE));
     $this->assertEquals(CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Credit Card'), $contribution['payment_instrument_id']);
     $this->assertEquals('kettles boil water', $contribution['trxn_id']);
     $this->assertEquals(0.29, $contribution['fee_amount']);
     $this->assertEquals(78, $contribution['total_amount']);
     $this->assertEquals(77.70999999999999, $contribution['net_amount']);
     $this->callAPISuccessGetCount('LineItem', array('entity_id' => $membership['id'], 'entity_table' => 'civicrm_membership', 'contribution_id' => $contribution['id']), 1);
 }
Example #11
0
 /**
  * Adjust query for the activity_contact table.
  *
  * As this is just a join table the ID we REALLY care about is the activity id.
  *
  * @param string $tableName
  * @param string $tableKey
  * @param string $fieldName
  * @param string $field
  *
  * @return string
  */
 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field)
 {
     if ($this->currentLogTable == 'log_civicrm_activity_contact' && $fieldName == 'id') {
         $alias = "{$tableName}_{$fieldName}";
         $select[] = "{$tableName}.activity_id as {$alias}";
         $this->_selectAliases[] = $alias;
         return "activity_id";
     }
     if ($fieldName == 'log_grouping') {
         if ($this->currentLogTable != 'log_civicrm_activity_contact') {
             return 1;
         }
         $mergeActivityID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Contact Merged');
         return " IF (entity_log_civireport.log_action = 'Insert' AND extra_table.activity_type_id = {$mergeActivityID} , GROUP_CONCAT(entity_log_civireport.contact_id), 1) ";
     }
 }
 /**
  * Fetch activity type id of custom Activity
  * @return integer
  */
 public static function getActivityTypeId()
 {
     return CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', static::CUSTOM_ACTIVITY_TYPE);
 }
Example #13
0
 /**
  * Process payment after confirmation.
  *
  * @param CRM_Core_Form $form
  *   Form object.
  * @param array $paymentParams
  *   Array with payment related key.
  *   value pairs
  * @param int $contactID
  *   Contact id.
  * @param int $contributionTypeId
  *   Financial type id.
  * @param int|string $component component id
  * @param bool $isTest
  * @param bool $isRecur
  *
  * @throws CRM_Core_Exception
  * @throws Exception
  * @return array
  *   associated array
  *
  */
 public static function processConfirm(&$form, &$paymentParams, $contactID, $contributionTypeId, $component = 'contribution', $isTest, $isRecur)
 {
     CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
     $lineItems = $form->_lineItem;
     $isPaymentTransaction = self::isPaymentTransaction($form);
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->id = $contributionTypeId;
     $financialType->find(TRUE);
     if ($financialType->is_deductible) {
         $form->assign('is_deductible', TRUE);
         $form->set('is_deductible', TRUE);
     }
     // add some financial type details to the params list
     // if folks need to use it
     //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
     $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
     //CRM-11456
     $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($contributionTypeId);
     $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
     $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
     //fix for CRM-16317
     $form->_params['receive_date'] = date('YmdHis');
     $form->assign('receive_date', CRM_Utils_Date::mysqlToIso($form->_params['receive_date']));
     if ($isPaymentTransaction) {
         $contributionParams = array('id' => CRM_Utils_Array::value('contribution_id', $paymentParams), 'contact_id' => $contactID, 'line_item' => $lineItems, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values)), 'contribution_page_id' => $form->_id, 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)));
         $isMonetary = !empty($form->_values['is_monetary']);
         if ($isMonetary) {
             if (empty($paymentParams['is_pay_later'])) {
                 // @todo look up payment_instrument_id on payment processor table.
                 $contributionParams['payment_instrument_id'] = 1;
             }
         }
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form, $paymentParams, NULL, $contributionParams, $financialType, TRUE, $form->_bltID, $isRecur);
         $paymentParams['contributionTypeID'] = $contributionTypeId;
         $paymentParams['item_name'] = $form->_params['description'];
         $paymentParams['qfKey'] = $form->controller->_key;
         if ($component == 'membership') {
             return array('contribution' => $contribution);
         }
         $paymentParams['contributionID'] = $contribution->id;
         //CRM-15297 deprecate contributionTypeID
         $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
         $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
         if (isset($paymentParams['contribution_source'])) {
             $paymentParams['source'] = $paymentParams['contribution_source'];
         }
         if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         if (isset($paymentParams['contribution_source'])) {
             $form->_params['source'] = $paymentParams['contribution_source'];
         }
         // get the price set values for receipt.
         if ($form->_priceSetId && $form->_lineItem) {
             $form->_values['lineItem'] = $form->_lineItem;
             $form->_values['priceSetID'] = $form->_priceSetId;
         }
         $form->_values['contribution_id'] = $contribution->id;
         $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
         if (!empty($form->_paymentProcessor)) {
             try {
                 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
                 if ($form->_contributeMode == 'notify') {
                     // We want to get rid of this & make it generic - eg. by making payment processing the last thing
                     // and always calling it first.
                     $form->postProcessHook();
                 }
                 $result = $payment->doPayment($paymentParams);
                 $form->_params = array_merge($form->_params, $result);
                 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
                 if (!empty($result['trxn_id'])) {
                     $contribution->trxn_id = $result['trxn_id'];
                 }
                 if (!empty($result['payment_status_id'])) {
                     $contribution->payment_status_id = $result['payment_status_id'];
                 }
                 $result['contribution'] = $contribution;
                 if ($result['payment_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'status_id', 'Pending') && $payment->isSendReceiptForPending()) {
                     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
                 }
                 return $result;
             } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
                 // Clean up DB as appropriate.
                 if (!empty($paymentParams['contributionID'])) {
                     CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $paymentParams['contactID'], $e->getMessage());
                 }
                 if (!empty($paymentParams['contributionRecurID'])) {
                     CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
                 }
                 $result['is_payment_failure'] = TRUE;
                 $result['error'] = $e;
                 return $result;
             }
         }
     }
     // Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
     // manual processor, so it's unclear what this set is for and whether the following send ever fires.
     $form->set('params', $form->_params);
     if ($form->_params['amount'] == 0) {
         // This is kind of a back-up for pay-later $0 transactions.
         // In other flows they pick up the manual processor & get dealt with above (I
         // think that might be better...).
         return array('payment_status_id' => 1, 'contribution' => $contribution, 'payment_processor_id' => 0);
     } elseif (empty($form->_values['amount'])) {
         // If the amount is not in _values[], set it
         $form->_values['amount'] = $form->_params['amount'];
     }
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
 }
Example #14
0
 /**
  * Function to build the form
  *
  * @return void
  * @access public
  */
 function buildQuickForm()
 {
     $attributes = CRM_Core_DAO::getAttribute('CRM_HRRecruitment_DAO_HRVacancy');
     $this->add('text', 'position', ts('Job Position'), $attributes['position'], TRUE);
     $this->addSelect('location', array('label' => ts('Location'), 'entity' => 'HRJobDetails', 'field' => 'location'));
     $this->add('text', 'salary', ts('Salary'), $attributes['salary']);
     $this->addWysiwyg('description', ts('Description'), array('rows' => 2, 'cols' => 40));
     $this->addWysiwyg('benefits', ts('Benefits'), array('rows' => 2, 'cols' => 40));
     $this->addWysiwyg('requirements', ts('Requirements'), array('rows' => 2, 'cols' => 40));
     $this->addDateTime('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDateTime'));
     $this->addDateTime('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDateTime'));
     $include =& $this->addElement('advmultiselect', 'stages', '', CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, " AND grouping = 'Vacancy'"), array('size' => 5, 'style' => 'width:150px', 'class' => 'advmultiselect'));
     $include->setButtonAttributes('add', array('value' => ts('Enable >>')));
     $include->setButtonAttributes('remove', array('value' => ts('<< Disable')));
     $templates = $vacancyPermissions = array();
     if (!$this->_isTemplate) {
         $this->addSelect('status_id', array(), TRUE);
         $result = civicrm_api3('HRVacancy', 'get', array('is_template' => 1, 'return' => 'position'));
         foreach ($result['values'] as $id => $vacancy) {
             $templates[$id] = $vacancy['position'];
         }
         //hide 'From Template' on edit screen
         if (empty($this->_id)) {
             $this->add('select', 'template_id', ts('From Template'), array('' => ts('- select -')) + $templates, FALSE, array('class' => 'crm-select2 huge'));
         }
     }
     $caseTypes = CRM_Case_PseudoConstant::caseType('name');
     $application = array_search('Application', $caseTypes);
     $evalID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Evaluation');
     $evalEntity[] = array('entity_name' => 'activity_1', 'entity_type' => 'ActivityModel', 'entity_sub_type' => "{$evalID}");
     $appEntities = array();
     $appEntities[] = array('entity_name' => 'contact_1', 'entity_type' => 'IndividualModel');
     $appEntities[] = array('entity_name' => 'case_1', 'entity_type' => 'CaseModel', 'entity_sub_type' => "{$application}");
     $this->addProfileSelector('application_profile', '', array('Individual', 'Contact', 'Case'), array('CaseType' => array($application)), $appEntities);
     $this->addProfileSelector('evaluation_profile', '', array('Activity'), array('ActivityType' => array($evalID)), $evalEntity);
     $permissionClass = new CRM_Core_Permission_Base();
     $permissions = $permissionClass->getAllModulePermissions();
     foreach (array('view Applicants', 'manage Applicants', 'evaluate Applicants', 'administer Vacancy') as $permission) {
         $explodedPerms = explode(':', $permissions[$permission]);
         $vacancyPermissions[$permission] = array_pop($explodedPerms);
     }
     $rowCount = 5;
     for ($rowNumber = 1; $rowNumber <= $rowCount; $rowNumber++) {
         $this->add('select', "permission[{$rowNumber}]", '', array('' => ts('- select -')) + $vacancyPermissions, FALSE, array('class' => 'crm-select2 huge'));
         $this->addEntityRef("permission_contact_id[{$rowNumber}]", NULL, array('api' => array('params' => array('contact_type' => 'Individual'))));
     }
     $this->assign('rowCount', $rowCount);
     $this->assign('showPermissionRow', 1);
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $session = CRM_Core_Session::singleton();
     if ($this->_isTemplate) {
         $this->_cancelURL = CRM_Utils_System::url('civicrm/vacancy/find', 'reset=1&template=1');
     } else {
         $this->_cancelURL = CRM_Utils_System::url('civicrm/vacancy/find', 'reset=1');
     }
     $this->addFormRule(array('CRM_HRRecruitment_Form_HRVacancy', 'formRule'));
     $session->replaceUserContext($this->_cancelURL);
 }
Example #15
0
 /**
  * @param int $contributionId
  *
  * @return array
  */
 public static function getTotalPayments($contributionId)
 {
     $statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
     $sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft\n      INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')\n      WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id = %2";
     $params = array(1 => array($contributionId, 'Integer'), 2 => array($statusId, 'Integer'));
     return CRM_Core_DAO::singleValueQuery($sql, $params);
 }
 public function createSimpleContribution($contactID, $params, $isTest, $creditInfo)
 {
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
     $bltID = array_search('Billing', $locationTypes);
     $settings = civicrm_api3('Setting', 'get', array('domain_id' => $domainID, 'return' => "simple_donation_page"));
     $donatePageID = $settings['values'][$domainID]['simple_donation_page'];
     $donateConfig = $donatePage = civicrm_api3('ContributionPage', 'getsingle', array('id' => $donatePageID));
     $contributionparams = array();
     $isrecur = $params['recur'];
     $contributionparams = array("billing_first_name" => $params['first_name'], "first_name" => $params['first_name'], "billing_middle_name" => $params['middle_name'], "middle_name" => $params['middle_name'], "billing_last_name" => $params['last_name'], "last_name" => $params['last_name'], "billing_street_address-{$bltID}" => $params['address'], "street_address" => $params['address'], "billing_city-{$bltID}" => $params['city'], "city" => $params['city'], "billing_country_id-{$bltID}" => $params['country'], "country_id" => $params['country'], "billing_state_province_id-{$bltID}" => $params['state'], "state_province_id" => $params['state'], "state_province" => CRM_Core_PseudoConstant::stateProvince($params['state']), "billing_postal_code-{$bltID}" => $params['zip'], "postal_code" => $params['zip'], "year" => "20" . substr($params['cardExpiry'], 2, 3), "month" => substr($params['cardExpiry'], 0, 2), "email" => $params['email'], "contribution_page_id" => $donatePageID, "payment_processor_id" => CRM_Utils_Array::value('payment_processor', $params), "is_test" => $isTest, "is_pay_later" => $params['is_pay_later'], "total_amount" => $params['amount'], "financial_type_id" => $donateConfig['financial_type_id'], "currencyID" => $donateConfig['currency'], "currency" => $donateConfig['currency'], "skipLineItem" => 0, "skipRecentView" => 1, 'is_email_receipt' => 1, "contact_id" => $contactID, "source" => "Online Contribution: {$donateConfig['title']}");
     if ($params['is_pay_later']) {
         $contributionparams["contribution_status_id"] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
         $contributionparams["payment_processor_id"] = 1;
     }
     if (!empty($params['creditType'])) {
         $contributionparams['credit_card_number'] = $creditInfo['credit_card_number'];
         $contributionparams['cvv2'] = $creditInfo['cvv2'];
         $contributionparams['credit_card_type'] = $creditInfo['credit_card_type'];
     }
     if (!empty($params['debitType'])) {
         $contributionparams['bank_identification_number'] = $creditInfo['bank_identification_number'];
         $contributionparams['bank_name'] = $creditInfo['bank_name'];
         $contributionparams['bank_account_number'] = $creditInfo['bank_account_number'];
         $contributionparams['payment_type'] = $creditInfo['payment_type'];
         $contributionparams['account_holder'] = $creditInfo['account_holder'];
     }
     //unset the billing parameters if it is pay later mode
     //to avoid creation of billing location
     if ($params['is_pay_later']) {
         $billingFields = array('billing_first_name', 'billing_middle_name', 'billing_last_name', "billing_street_address-{$bltID}", "billing_city-{$bltID}", "billing_state_province-{$bltID}", "billing_state_province_id-{$bltID}", "billing_postal_code-{$bltID}", "billing_country-{$bltID}", "billing_country_id-{$bltID}");
         foreach ($billingFields as $value) {
             unset($contributionparams[$value]);
         }
     }
     //check for recurring contribution
     if ($isrecur) {
         $recurParams = array('contact_id' => $contactID);
         $recurParams['amount'] = $params['amount'];
         $recurParams['auto_renew'] = 1;
         $recurParams['frequency_unit'] = 'month';
         $recurParams['frequency_interval'] = 1;
         $recurParams['financial_type_id'] = $donateConfig['financial_type_id'];
         $recurParams['is_test'] = $isTest;
         $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
         $recurParams['invoice_id'] = $recurParams['trxn_id'] = md5(uniqid(rand(), TRUE));
         $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
         $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $contributionparams);
         $recurParams['is_email_receipt'] = 1;
         //create recurring contribution record
         $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
         $recurContriID = $recurring->id;
         $contributionparams['contributionRecurID'] = $recurContriID;
         //$contribution->id;
         $contributionparams['contribution_recur_id'] = $recurContriID;
         //$contribution->id;
     }
     //call transact api
     try {
         $result = civicrm_api3('Contribution', 'transact', $contributionparams);
     } catch (CiviCRM_API3_Exception $e) {
         $error = $e->getMessage();
         $errorList['error'] = $error;
         return $errorList;
     }
     if ($result['error']) {
         //make sure to cleanup db for recurring case.
         if ($recurContriID) {
             CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($recurContriID);
         }
         return $result['error'];
     } else {
         if ($result) {
             $contributionID = $result['id'];
             // Send receipt
             // send recurring Notification email for user
             if ($recurContriID) {
                 CRM_Contribute_BAO_ContributionPage::recurringNotify(CRM_Core_Payment::RECURRING_PAYMENT_START, $contactID, $donatePageID, $recurring);
             }
             civicrm_api3('contribution', 'sendconfirmation', array('id' => $contributionID) + $donateConfig);
             return $result;
         }
     }
 }
Example #17
0
 /**
  * View a particular stage in a tab
  */
 function viewStage()
 {
     // Data needed for contact list
     $contacts = CRM_HRRecruitment_BAO_HRVacancyStage::getCasesAtStage($this->_vid, $this->_statusId);
     $this->assign('contacts', $contacts);
     $this->ajaxResponse['tabCount'] = count($contacts);
     // Data needed for activity buttons/menu
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $activities = $xmlProcessor->get('Application', 'ActivityTypes', TRUE);
     // Special activities we don't want in the action menu
     foreach (array('Open Case', 'Comment', 'Email', 'Evaluation', 'Change Case Status', 'Link Cases', 'Assign Case Role') as $remove) {
         $type = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $remove);
         if ($type) {
             // Assign to the tpl as camelCase
             $this->assign(str_replace(' ', '', lcfirst($remove . 'Activity')), $type);
             // And remove from the list
             unset($activities[$type]);
         }
     }
     $this->assign('activities', $activities);
     // Data needed for status menu
     $this->assign('statusId', $this->_statusId);
     $caseStatus = array();
     foreach (CRM_HRRecruitment_BAO_HRVacancyStage::caseStage($this->_vid) as $id => $stage) {
         $caseStatus[$stage['weight']] = $stage + array('id' => $id);
     }
     ksort($caseStatus);
     $this->assign('caseStatus', $caseStatus);
 }
Example #18
0
 /**
  * Function returns associated array of elements, that will be passed for search
  *
  * @param array $params
  *   Associated array of submitted values.
  * @param bool $row
  *   Row no of the fields.
  *
  *
  * @return array
  *   formatted associated array of elements
  */
 public static function formattedFields(&$params, $row = FALSE)
 {
     $fields = array();
     if (empty($params) || !isset($params['mapper'])) {
         return $fields;
     }
     $types = array('Individual', 'Organization', 'Household');
     foreach ($params['mapper'] as $key => $value) {
         $contactType = NULL;
         foreach ($value as $k => $v) {
             if (in_array($v[0], $types)) {
                 if ($contactType && $contactType != $v[0]) {
                     CRM_Core_Error::fatal(ts("Cannot have two clauses with different types: %1, %2", array(1 => $contactType, 2 => $v[0])));
                 }
                 $contactType = $v[0];
             }
             if (!empty($v['1'])) {
                 $fldName = $v[1];
                 $v2 = CRM_Utils_Array::value('2', $v);
                 if ($v2 && trim($v2)) {
                     $fldName .= "-{$v[2]}";
                 }
                 $v3 = CRM_Utils_Array::value('3', $v);
                 if ($v3 && trim($v3)) {
                     $fldName .= "-{$v[3]}";
                 }
                 $value = $params['value'][$key][$k];
                 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_' && substr($fldName, 0, 10) != 'financial_' && substr($fldName, 0, 8) != 'payment_') {
                     if (substr($fldName, 0, 13) != 'contribution_') {
                         $fldName = 'contribution_' . $fldName;
                     }
                 }
                 // CRM-14983: verify if values are comma separated convert to array
                 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
                     $value = explode(',', $value);
                     $value = array($params['operator'][$key][$k] => $value);
                 }
                 // CRM-19081 Fix legacy StateProvince Field Values.
                 // These derive from smart groups created using search builder under older
                 // CiviCRM versions.
                 if (!is_numeric($value) && $fldName == 'state_province') {
                     $value = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
                 }
                 if ($row) {
                     $fields[] = array($fldName, $params['operator'][$key][$k], $value, $key, $k);
                 } else {
                     $fields[] = array($fldName, $params['operator'][$key][$k], $value, $key, 0);
                 }
             }
         }
         if ($contactType) {
             $fields[] = array('contact_type', '=', $contactType, $key, 0);
         }
     }
     //add sortByCharacter values
     if (isset($params['sortByCharacter'])) {
         $fields[] = array('sortByCharacter', '=', $params['sortByCharacter'], 0, 0);
     }
     return $fields;
 }
Example #19
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if ($this->_context == 'standalone') {
         $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
     }
     $showAdditionalInfo = FALSE;
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     $defaults = array();
     $paneNames = array('Payment Reminders' => 'PaymentReminders');
     foreach ($paneNames as $name => $type) {
         $urlParams = "snippet=4&formType={$type}";
         $allPanes[$name] = array('url' => CRM_Utils_System::url('civicrm/contact/view/pledge', $urlParams), 'open' => 'false', 'id' => $type);
         // see if we need to include this paneName in the current form
         if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) || CRM_Utils_Array::value("hidden_{$type}", $defaults)) {
             $showAdditionalInfo = TRUE;
             $allPanes[$name]['open'] = 'true';
         }
         $fnName = "build{$type}";
         CRM_Contribute_Form_AdditionalInfo::$fnName($this);
     }
     $this->assign('allPanes', $allPanes);
     $this->assign('showAdditionalInfo', $showAdditionalInfo);
     if ($this->_formType) {
         $this->assign('formType', $this->_formType);
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     // pledge fields.
     $attributes = CRM_Core_DAO::getAttribute('CRM_Pledge_DAO_Pledge');
     $this->assign('isPending', $this->_isPending);
     $js = array('onblur' => "calculatedPaymentAmount( );", 'onkeyup' => "calculatedPaymentAmount( );");
     $currencyFreeze = FALSE;
     if ($this->_id && !$this->_isPending) {
         $currencyFreeze = TRUE;
     }
     $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE, array_merge($attributes['pledge_amount'], $js), TRUE, 'currency', NULL, $currencyFreeze);
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'installments', ts('To be paid in'), array_merge($attributes['installments'], $js), TRUE);
     $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_interval', ts('every'), $attributes['pledge_frequency_interval'], TRUE);
     $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     // Fix frequency unit display for use with frequency_interval
     $freqUnitsDisplay = array();
     foreach ($this->_freqUnits as $val => $label) {
         $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
     }
     $element =& $this->add('select', 'frequency_unit', ts('Frequency'), array('' => ts('- select -')) + $freqUnitsDisplay, TRUE);
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
     $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 0 => 'READONLY'));
     // add various dates
     if (!$this->_id || $this->_isPending) {
         $this->addDate('create_date', ts('Pledge Made'), TRUE);
         $this->addDate('start_date', ts('Payments Start'), TRUE);
     }
     if ($this->_id && !$this->_isPending) {
         $eachPaymentAmount = $this->_values['original_installment_amount'];
         $this->assign('currency', $this->_values['currency']);
         $this->assign('eachPaymentAmount', $eachPaymentAmount);
         $this->assign('hideCalender', TRUE);
     }
     if (CRM_Utils_Array::value('status_id', $this->_values) != CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled')) {
         $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL, array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );"));
         $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
     }
     $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
     $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), TRUE);
     // CRM-7362 --add campaigns.
     CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
     $pageIds = array();
     CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table', 'civicrm_contribution_page', $pageIds, array('entity_id'));
     $pages = CRM_Contribute_PseudoConstant::contributionPage();
     $pledgePages = array();
     foreach ($pageIds as $key => $value) {
         $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
     }
     $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'), array('' => ts('- select -')) + $pledgePages);
     $mailingInfo = Civi::settings()->get('mailing_backend');
     $this->assign('outBound_option', $mailingInfo['outBound_option']);
     // build custom data
     CRM_Custom_Form_CustomData::buildQuickForm($this);
     // make this form an upload since we dont know if the custom data injected dynamically
     // is of type file etc $uploadNames = $this->get( 'uploadNames' );
     $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save'), 'js' => array('onclick' => "return verify( );"), 'isDefault' => TRUE), array('type' => 'upload', 'name' => ts('Save and New'), 'js' => array('onclick' => "return verify( );"), 'subName' => 'new'), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->freeze();
     }
 }
 /**
  * Delete a need, reassign its activities to the project's default flexible need
  * @param $id
  * @return bool
  */
 static function del($id)
 {
     $need = civicrm_api3('volunteer_need', 'getsingle', array('id' => $id));
     // TODO: What do we do with associated activities when deleting a flexible need?
     if (empty($need['is_flexible'])) {
         // Lookup the flexible need
         $flexibleNeedId = CRM_Volunteer_BAO_Project::getFlexibleNeedID($need['project_id']);
         // Reassign any activities back to the flexible need
         $acts = civicrm_api3('volunteer_assignment', 'get', array('volunteer_need_id' => $id));
         $status = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Available');
         foreach ($acts['values'] as $act) {
             civicrm_api3('volunteer_assignment', 'create', array('id' => $act['id'], 'volunteer_need_id' => $flexibleNeedId, 'status_id' => $status, 'time_scheduled_minutes' => 0));
         }
     }
     $dao = new CRM_Volunteer_DAO_Need();
     $dao->id = $id;
     if ($dao->find()) {
         while ($dao->fetch()) {
             $dao->delete();
         }
     } else {
         return FALSE;
     }
     return TRUE;
 }
Example #21
0
 /**
  * Fetch activity type id of 'volunteer' type activity
  * @return integer
  */
 public static function volunteerActivityTypeId()
 {
     return CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', CRM_Volunteer_Upgrader::customActivityTypeName);
 }
Example #22
0
 /**
  * Create the recurring contribution record.
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param int $contactID
  * @param string $contributionType
  *
  * @return int|null
  */
 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType)
 {
     if (empty($params['is_recur'])) {
         return NULL;
     }
     $recurParams = array('contact_id' => $contactID);
     $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
     $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
     $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
     $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
     $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
     $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
     $recurParams['currency'] = CRM_Utils_Array::value('currency', $params);
     // CRM-14354: For an auto-renewing membership with an additional contribution,
     // if separate payments is not enabled, make sure only the membership fee recurs
     if (!empty($form->_membershipBlock) && $form->_membershipBlock['is_separate_payment'] === '0' && isset($params['selectMembership']) && $form->_values['is_allow_other_amount'] == '1' && !empty($form->_membershipTypeValues) && !empty($form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'])) {
         $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
     }
     $recurParams['is_test'] = 0;
     if ($form->_action & CRM_Core_Action::PREVIEW || isset($form->_mode) && $form->_mode == 'test') {
         $recurParams['is_test'] = 1;
     }
     $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
     if (!empty($params['receive_date'])) {
         $recurParams['start_date'] = $params['receive_date'];
     }
     $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
     $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
     $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
     $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
     // we need to add a unique trxn_id to avoid a unique key error
     // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
     $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
     $recurParams['financial_type_id'] = $contributionType->id;
     if ($form->_values['is_monetary']) {
         $recurParams['payment_instrument_id'] = 1;
     }
     $campaignId = CRM_Utils_Array::value('campaign_id', $params, CRM_Utils_Array::value('campaign_id', $form->_values));
     $recurParams['campaign_id'] = $campaignId;
     $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
     if (is_a($recurring, 'CRM_Core_Error')) {
         CRM_Core_Error::displaySessionError($recurring);
         $urlString = 'civicrm/contribute/transact';
         $urlParams = '_qf_Main_display=true';
         if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
             $urlString = 'civicrm/contact/view/contribution';
             $urlParams = "action=add&cid={$form->_contactID}";
             if ($form->_mode) {
                 $urlParams .= "&mode={$form->_mode}";
             }
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
     }
     return $recurring->id;
 }
Example #23
0
 /**
  * Set default values.
  *
  * @return array
  */
 public function setDefaultValues()
 {
     $defaults = $this->_values;
     // Set defaults for pledge payment.
     if ($this->_ppID) {
         $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
         $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
         $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
         $defaults['option_type'] = 1;
     }
     if ($this->_action & CRM_Core_Action::DELETE) {
         return $defaults;
     }
     $defaults['frequency_interval'] = 1;
     $defaults['frequency_unit'] = 'month';
     // Set soft credit defaults.
     CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
     if ($this->_mode) {
         // @todo - remove this function as the parent does it too.
         $config = CRM_Core_Config::singleton();
         // Set default country from config if no country set.
         if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
             $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
         }
         if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
             $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
         }
         $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
         $defaults = array_merge($defaults, $billingDefaults);
     }
     if ($this->_id) {
         $this->_contactID = $defaults['contact_id'];
     }
     // Set $newCredit variable in template to control whether link to credit card mode is included.
     $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
     // Fix the display of the monetary value, CRM-4038.
     if (isset($defaults['total_amount'])) {
         if (!empty($defaults['tax_amount'])) {
             $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
                 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
             }
         } else {
             $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
         }
     }
     if (isset($defaults['non_deductible_amount'])) {
         $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
     }
     if (isset($defaults['fee_amount'])) {
         $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
     }
     if (isset($defaults['net_amount'])) {
         $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
     }
     if ($this->_contributionType) {
         $defaults['financial_type_id'] = $this->_contributionType;
     }
     if (empty($defaults['payment_instrument_id'])) {
         $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
     }
     if (!empty($defaults['is_test'])) {
         $this->assign('is_test', TRUE);
     }
     $this->assign('showOption', TRUE);
     // For Premium section.
     if ($this->_premiumID) {
         $this->assign('showOption', FALSE);
         $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
         if (!$options) {
             $this->assign('showOption', TRUE);
         }
         $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
         if ($options_key) {
             $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
         } else {
             $defaults['product_name'] = array($this->_productDAO->product_id);
         }
         if ($this->_productDAO->fulfilled_date) {
             list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
         }
     }
     if (isset($this->userEmail)) {
         $this->assign('email', $this->userEmail);
     }
     if (!empty($defaults['is_pay_later'])) {
         $this->assign('is_pay_later', TRUE);
     }
     $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
     if (CRM_Utils_Array::value('contribution_status_id', $defaults) == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded')) {
         $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($this->_id);
     } else {
         $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ? $defaults['trxn_id'] : NULL;
     }
     $dates = array('receive_date', 'receipt_date', 'cancel_date', 'thankyou_date');
     foreach ($dates as $key) {
         if (!empty($defaults[$key])) {
             list($defaults[$key], $defaults[$key . '_time']) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults), 'activityDateTime');
         }
     }
     if (!$this->_id && empty($defaults['receive_date'])) {
         list($defaults['receive_date'], $defaults['receive_date_time']) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
     }
     $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults), CRM_Utils_Array::value('receive_date_time', $defaults)));
     $currency = CRM_Utils_Array::value('currency', $defaults);
     $this->assign('currency', $currency);
     // Hack to get currency info to the js layer. CRM-11440.
     CRM_Utils_Money::format(1);
     $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
     $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
     // Inherit campaign from pledge.
     if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
         $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
     }
     $this->_defaults = $defaults;
     return $defaults;
 }
 /**
  * Alter display of rows.
  *
  * Iterate through the rows retrieved via SQL and make changes for display purposes,
  * such as rendering contacts as links.
  *
  * @param array $rows
  *   Rows generated by SQL, with an array for each row.
  */
 public function alterDisplay(&$rows)
 {
     // cache for id → is_deleted mapping
     $isDeleted = array();
     $newRows = array();
     foreach ($rows as $key => &$row) {
         $isMerge = 0;
         $baseQueryCriteria = "reset=1&log_conn_id={$row['log_civicrm_entity_log_conn_id']}";
         if (!CRM_Logging_Differ::checkLogCanBeUsedWithNoLogDate($row['log_civicrm_entity_log_date'])) {
             $baseQueryCriteria .= '&log_date=' . CRM_Utils_Date::isoToMysql($row['log_civicrm_entity_log_date']);
         }
         if ($this->cid) {
             $baseQueryCriteria .= '&cid=' . $this->cid;
         }
         if (!isset($isDeleted[$row['log_civicrm_entity_altered_contact_id']])) {
             $isDeleted[$row['log_civicrm_entity_altered_contact_id']] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['log_civicrm_entity_altered_contact_id'], 'is_deleted') !== '0';
         }
         if (!empty($row['log_civicrm_entity_altered_contact']) && !$isDeleted[$row['log_civicrm_entity_altered_contact_id']]) {
             $row['log_civicrm_entity_altered_contact_link'] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $row['log_civicrm_entity_altered_contact_id']);
             $row['log_civicrm_entity_altered_contact_hover'] = ts("Go to contact summary");
             $entity = $this->getEntityValue($row['log_civicrm_entity_id'], $row['log_civicrm_entity_log_type'], $row['log_civicrm_entity_log_date']);
             if ($entity) {
                 $row['log_civicrm_entity_altered_contact'] = $row['log_civicrm_entity_altered_contact'] . " [{$entity}]";
             }
             if ($entity == 'Contact Merged') {
                 $deletedID = CRM_Core_DAO::singleValueQuery('
         SELECT GROUP_CONCAT(contact_id) FROM civicrm_activity_contact ac
         INNER JOIN civicrm_activity a
         ON a.id = ac.activity_id AND a.parent_id = ' . $row['log_civicrm_entity_id'] . ' AND ac.record_type_id =
         ' . CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets'));
                 if ($deletedID && !stristr($deletedID, ',')) {
                     $baseQueryCriteria .= '&oid=' . $deletedID;
                 }
                 $row['log_civicrm_entity_log_action'] = ts('Contact Merge');
                 $row = $this->addDetailReportLinksToRow($baseQueryCriteria, $row);
                 $isMerge = 1;
             }
         }
         $row['altered_by_contact_display_name_link'] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $row['log_civicrm_entity_log_user_id']);
         $row['altered_by_contact_display_name_hover'] = ts("Go to contact summary");
         if ($row['log_civicrm_entity_is_deleted'] and 'Update' == CRM_Utils_Array::value('log_civicrm_entity_log_action', $row)) {
             $row['log_civicrm_entity_log_action'] = ts('Delete (to trash)');
         }
         if ('Contact' == CRM_Utils_Array::value('log_type', $this->_logTables[$row['log_civicrm_entity_log_type']]) && CRM_Utils_Array::value('log_civicrm_entity_log_action', $row) == ts('Insert')) {
             $row['log_civicrm_entity_log_action'] = ts('Update');
         }
         if ($newAction = $this->getEntityAction($row['log_civicrm_entity_id'], $row['log_civicrm_entity_log_conn_id'], $row['log_civicrm_entity_log_type'], CRM_Utils_Array::value('log_civicrm_entity_log_action', $row))) {
             $row['log_civicrm_entity_log_action'] = $newAction;
         }
         $row['log_civicrm_entity_log_type'] = $this->getLogType($row['log_civicrm_entity_log_type']);
         $date = CRM_Utils_Date::isoToMysql($row['log_civicrm_entity_log_date']);
         if ('Update' == CRM_Utils_Array::value('log_civicrm_entity_log_action', $row)) {
             $row = $this->addDetailReportLinksToRow($baseQueryCriteria, $row);
         }
         $key = $date . '_' . $row['log_civicrm_entity_log_type'] . '_' . $isMerge . $row['log_civicrm_entity_log_conn_id'] . '_' . $row['log_civicrm_entity_log_user_id'] . '_' . $row['log_civicrm_entity_altered_contact_id'];
         $newRows[$key] = $row;
         unset($row['log_civicrm_entity_log_user_id']);
         unset($row['log_civicrm_entity_log_conn_id']);
     }
     krsort($newRows);
     $rows = $newRows;
 }
Example #25
0
 /**
  * Get the amount details date wise.
  *
  * @param string $status
  * @param string $startDate
  * @param string $endDate
  *
  * @return array|null
  */
 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL)
 {
     $where = array();
     $select = $from = $queryDate = NULL;
     $statusId = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
     switch ($status) {
         case 'Completed':
             $where[] = 'status_id != ' . CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
             break;
         case 'Cancelled':
         case 'In Progress':
         case 'Pending':
         case 'Overdue':
             $where[] = 'status_id = ' . $statusId;
             break;
     }
     if ($startDate) {
         $where[] = "create_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
     }
     if ($endDate) {
         $where[] = "create_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
     }
     $whereCond = implode(' AND ', $where);
     $query = "\nSELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency\nFROM   civicrm_pledge\nWHERE  {$whereCond} AND is_test=0\nGROUP BY  currency\n";
     $start = substr($startDate, 0, 8);
     $end = substr($endDate, 0, 8);
     $pCount = 0;
     $pamount = array();
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $pCount += $dao->pledge_count;
         $pamount[] = CRM_Utils_Money::format($dao->pledge_amount, $dao->currency);
     }
     $pledge_amount = array('pledge_amount' => implode(', ', $pamount), 'pledge_count' => $pCount, 'purl' => CRM_Utils_System::url('civicrm/pledge/search', "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"));
     $where = array();
     switch ($status) {
         case 'Completed':
             $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
             $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
             $queryDate = 'receive_date';
             $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
             break;
         case 'Cancelled':
             $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
             $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
             $queryDate = 'receive_date';
             $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
             break;
         case 'Pending':
             $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
             $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
             $queryDate = 'scheduled_date';
             $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
             break;
         case 'Overdue':
             $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
             $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
             $queryDate = 'scheduled_date';
             $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
             break;
     }
     if ($startDate) {
         $where[] = " {$queryDate} >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
     }
     if ($endDate) {
         $where[] = " {$queryDate} <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
     }
     $whereCond = implode(' AND ', $where);
     $query = "\n SELECT {$select}, cp.currency\n FROM {$from}\n WHERE  {$whereCond}\n GROUP BY  cp.currency\n";
     if ($select) {
         $dao = CRM_Core_DAO::executeQuery($query);
         $amount = array();
         $count = 0;
         while ($dao->fetch()) {
             $count += $dao->received_count;
             $amount[] = CRM_Utils_Money::format($dao->received_pledge, $dao->currency);
         }
         if ($count) {
             return array_merge($pledge_amount, array('received_amount' => implode(', ', $amount), 'received_count' => $count, 'url' => CRM_Utils_System::url('civicrm/pledge/search', "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0")));
         }
     } else {
         return $pledge_amount;
     }
     return NULL;
 }
Example #26
0
 /**
  * This function is to get Vacancy ID from Application ID
  *
  * @param int $caseID - Case ID of type Application
  *
  * @return int
  * @access public
  */
 public static function getVacancyIDByCase($caseID)
 {
     $vacancyID = NULL;
     $applCaseID = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_CustomField', 'custom_group_id', 'application_case');
     $cgID = array('custom_group_id' => $applCaseID);
     CRM_Core_BAO_CustomField::retrieve($cgID, $cfID);
     $params = array("entityID" => $caseID, "custom_{$cfID['id']}" => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($params);
     if (array_key_exists("custom_{$cfID['id']}", $result)) {
         $vacancyID = $result["custom_{$cfID['id']}"];
     }
     return $vacancyID;
 }
Example #27
0
 /**
  * Generate where for a single parameter.
  *
  * @param array $values
  * @param CRM_Contact_BAO_Query $query
  */
 public static function whereClauseSingle(&$values, &$query)
 {
     list($name, $op, $value, $grouping) = $values;
     switch ($name) {
         case 'member_join_date_low':
         case 'member_join_date_high':
             $query->dateQueryBuilder($values, 'civicrm_membership', 'member_join_date', 'join_date', 'Member Since');
             return;
         case 'member_start_date_low':
         case 'member_start_date_high':
             $query->dateQueryBuilder($values, 'civicrm_membership', 'member_start_date', 'start_date', 'Start Date');
             return;
         case 'member_end_date_low':
         case 'member_end_date_high':
             $query->dateQueryBuilder($values, 'civicrm_membership', 'member_end_date', 'end_date', 'End Date');
             return;
         case 'member_join_date':
             $op = '>=';
             $date = CRM_Utils_Date::format($value);
             if ($date) {
                 $query->_where[$grouping][] = "civicrm_membership.join_date {$op} {$date}";
                 $format = CRM_Utils_Date::customFormat(CRM_Utils_Date::format(array_reverse($value), '-'));
                 $query->_qill[$grouping][] = ts('Member Since %2 %1', array(1 => $format, 2 => $op));
             }
             return;
         case 'member_source':
             $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
             $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
             $query->_where[$grouping][] = "civicrm_membership.source {$op} '{$value}'";
             $query->_qill[$grouping][] = ts('Source %2 %1', array(1 => $value, 2 => $op));
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
             // CRM-17011 These 2 variants appear in some smart groups saved at some time prior to 4.6.6.
         // CRM-17011 These 2 variants appear in some smart groups saved at some time prior to 4.6.6.
         case 'member_status_id':
         case 'member_membership_type_id':
             if (is_array($value)) {
                 $op = 'IN';
                 $value = array_keys($value);
             }
         case 'membership_type_id':
             // CRM-17075 we are specifically handling the possibility we are dealing with the entity reference field
             // for membership_type_id here (although status would be handled if converted). The unhandled pathway at the moment
             // is from groupContactCache::load and this is a small fix to get the entity reference field to work.
             // However, it would seem the larger fix would be to NOT invoke the form formValues for
             // the load function. The where clause and the whereTables are saved so they should suffice to generate the query
             // to get a contact list. But, better to deal with in 4.8 now...
             if (is_string($value) && strpos($value, ',') && $op == '=') {
                 $value = array('IN' => explode(',', $value));
             }
         case 'membership_status':
         case 'membership_status_id':
         case 'membership_type':
         case 'member_id':
             if (strstr($name, 'status') && is_string($value) && !is_numeric($value)) {
                 $value = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', $value);
             }
             if (strpos($name, 'status') !== FALSE) {
                 $name = 'status_id';
                 $qillName = 'Membership Status(s)';
             } elseif ($name == 'member_id') {
                 $name = 'id';
                 $qillName = 'Membership ID';
             } else {
                 $name = 'membership_type_id';
                 $qillName = 'Membership Type(s)';
             }
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.{$name}", $op, $value, "Integer");
             list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Member_DAO_Membership', $name, $value, $op);
             $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $qillName, 2 => $op, 3 => $value));
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_test':
             // We dont want to include all tests for sql OR CRM-7827
             if (!$value || $query->getOperator() != 'OR') {
                 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_test", $op, $value, "Boolean");
                 if ($value) {
                     $query->_qill[$grouping][] = ts('Membership is a Test');
                 }
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_auto_renew':
             $op = "!=";
             if ($value) {
                 $query->_where[$grouping][] = " civicrm_membership.contribution_recur_id IS NOT NULL";
                 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("ccr.contribution_status_id", $op, array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')), "Integer");
                 $query->_qill[$grouping][] = ts("Membership is Auto-Renew");
             } else {
                 $query->_where[$grouping][] = " civicrm_membership.contribution_recur_id IS NULL";
                 $query->_qill[$grouping][] = ts("Membership is NOT Auto-Renew");
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_pay_later':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_pay_later", $op, $value, "Integer");
             if ($value) {
                 $query->_qill[$grouping][] = ts("Membership is Pay Later");
             } else {
                 $query->_qill[$grouping][] = ts("Membership is NOT Pay Later");
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_is_primary':
             if ($value) {
                 $query->_where[$grouping][] = " civicrm_membership.owner_membership_id IS NULL";
                 $query->_qill[$grouping][] = ts("Primary Members Only");
             } else {
                 $query->_where[$grouping][] = " civicrm_membership.owner_membership_id IS NOT NULL";
                 $query->_qill[$grouping][] = ts("Related Members Only");
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_is_override':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_override", $op, $value, "Boolean");
             $query->_qill[$grouping][] = $value ? ts("Is Membership Status overriden? Yes") : ts("Is Membership Status overriden? No");
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_campaign_id':
             if (CRM_Utils_Array::value($op, $value)) {
                 $value = $value[$op];
             }
             $campParams = array('op' => $op, 'campaign' => $value, 'grouping' => $grouping, 'tableName' => 'civicrm_membership');
             CRM_Campaign_BAO_Query::componentSearchClause($campParams, $query);
             return;
     }
 }
Example #28
0
 /**
  * Complete an order.
  *
  * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
  *
  * Currently overloaded to complete a transaction & repeat a transaction - fix!
  *
  * Moving it out of the BaseIPN class is just the first step.
  *
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param CRM_Core_Transaction $transaction
  * @param int $recur
  * @param CRM_Contribute_BAO_Contribution $contribution
  * @param bool $isRecurring
  *   Duplication of param needs review. Only used by AuthorizeNetIPN
  * @param int $isFirstOrLastRecurringPayment
  *   Deprecated param only used by AuthorizeNetIPN.
  */
 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment)
 {
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     // The previous details are used when calculating line items so keep it before any code that 'does something'
     if (!empty($contribution->id)) {
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date', 'receipt_date', 'contribution_status_id');
     if (self::isSingleLineItem($primaryContributionID)) {
         $inputContributionWhiteList[] = 'financial_type_id';
     }
     $participant = CRM_Utils_Array::value('participant', $objects);
     $memberships = CRM_Utils_Array::value('membership', $objects);
     $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
     $event = CRM_Utils_Array::value('event', $objects);
     $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
     $contributionParams = array_merge(array('contribution_status_id' => $completedContributionStatusID, 'source' => self::getRecurringContributionDescription($contribution, $event)), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)));
     if (!empty($recurContrib->id)) {
         $contributionParams['contribution_recur_id'] = $recurContrib->id;
     }
     $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
     if (empty($contributionParams['receive_date']) && $changeDate) {
         $contributionParams['receive_date'] = $changeDate;
     }
     self::repeatTransaction($contribution, $input, $contributionParams);
     $contributionParams['financial_type_id'] = $contribution->financial_type_id;
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             // Figure out what we gain from this.
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
         } elseif ($recurContrib && $recurContrib->id) {
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id);
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membershipParams['id']}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = CRM_Core_DAO::executeQuery($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membershipParams['membership_type_id'] = $dao->membership_type_id;
                         }
                     }
                     $dao->free();
                     $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID);
                     $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']);
                         $dates['join_date'] = $currentMembership['join_date'];
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams);
                     $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
                     //we might be renewing membership,
                     //so make status override false.
                     $membershipParams['is_override'] = FALSE;
                     //CRM-17723 - reset static $relatedContactIds array()
                     $var = TRUE;
                     CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
                     civicrm_api3('Membership', 'create', $membershipParams);
                 }
             }
         }
     } else {
         if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
             if ($event->is_email_confirm) {
                 // @todo this should be set by the function that sends the mail after sending.
                 $contributionParams['receipt_date'] = $changeDate;
             }
             $participantParams['id'] = $participant->id;
             $participantParams['status_id'] = 'Registered';
             civicrm_api3('Participant', 'create', $participantParams);
         }
     }
     $contributionParams['id'] = $contribution->id;
     civicrm_api3('Contribution', 'create', $contributionParams);
     // Add new soft credit against current $contribution.
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
     }
     $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending']) {
         $input['payment_processor'] = $paymentProcessorId;
     }
     if (!empty($contribution->_relatedObjects['participant'])) {
         $input['contribution_mode'] = 'participant';
         $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
         $input['skipLineItem'] = 1;
     } elseif (!empty($contribution->_relatedObjects['membership'])) {
         $input['skipLineItem'] = TRUE;
         $input['contribution_mode'] = 'membership';
         $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
         $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $input);
         $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     }
     $input['contribution_status_id'] = $contributionParams['contribution_status_id'];
     $input['total_amount'] = $input['amount'];
     $input['contribution'] = $contribution;
     $input['financial_type_id'] = $contribution->financial_type_id;
     //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
     // and subsequent payments. In this case the line items are created at
     // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
     // and since the contribution is saved prior to this line there is always a contribution-id,
     // however there is never a prevContribution (which appears to mean original contribution not previous
     // contribution - or preUpdateContributionObject most accurately)
     // so, this is always called & only appears to succeed when prevContribution exists - which appears
     // to mean "are we updating an exisitng pending contribution"
     //I was able to make the unit test complete as fataling here doesn't prevent
     // the contribution being created - but activities would not be created or emails sent
     CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (!empty($ids['related_contact'])) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
     if ($isRecurring) {
         CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment);
     }
 }
Example #29
0
 /**
  * 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 CRM_Member_BAO_Membership
  */
 public static function add(&$params, $ids = array())
 {
     $oldStatus = $oldType = NULL;
     $params['id'] = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('membership', $ids));
     if ($params['id']) {
         CRM_Utils_Hook::pre('edit', 'Membership', $params['id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Membership', NULL, $params);
     }
     $id = $params['id'];
     // we do this after the hooks are called in case it has been altered
     if ($id) {
         $membershipObj = new CRM_Member_DAO_Membership();
         $membershipObj->id = $id;
         $membershipObj->find();
         while ($membershipObj->fetch()) {
             $oldStatus = $membershipObj->status_id;
             $oldType = $membershipObj->membership_type_id;
         }
     }
     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 = $id;
     $membership->save();
     $membership->free();
     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 don't 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), 'modified_date' => date('Ymd'), 'membership_type_id' => $values[$membership->id]['membership_type_id'], 'max_related' => $membership->max_related);
     $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 ($id) {
         if ($membership->status_id != $oldStatus) {
             $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
             $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' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'), 'status_id' => 2, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s'));
             civicrm_api3('activity', 'create', $activityParam);
         }
         if (isset($membership->membership_type_id) && $membership->membership_type_id != $oldType) {
             $membershipTypes = CRM_Member_BAO_Membership::buildOptions('membership_type_id', 'get');
             $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' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'), 'status_id' => 2, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s'));
             civicrm_api3('activity', 'create', $activityParam);
         }
         CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
     } else {
         CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership);
     }
     return $membership;
 }
Example #30
0
/**
 * Implementation of hook_civicrm_alterContent
 *
 * @return void
 */
function hrrecruitment_civicrm_alterContent(&$content, $context, $tplName, &$object)
{
    /* HR-372, HR-373 -- To hide unwanted fields from view/edit screen for Evaluation and Comment activity */
    $requiredAct = FALSE;
    $activityTypes = array(CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Evaluation'), CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Comment'));
    $smarty = CRM_Core_Smarty::singleton();
    //Get activity Type
    if ($tplName == "CRM/Case/Form/ActivityView.tpl") {
        $activityID = $smarty->_tpl_vars['activityID'];
        $aType = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityID, 'activity_type_id');
        $requiredAct = TRUE;
    } elseif ($tplName == "CRM/Case/Form/Activity.tpl") {
        $aType = $object->_activityTypeId;
        $requiredAct = TRUE;
    }
    if ($context == "form" && $tplName == "CRM/HRRecruitment/Form/CaseProfile.tpl") {
        $formName = $smarty->_tpl_vars['form']['formName'];
        $content .= "<script type=\"text/javascript\">\n      CRM.\$(function(\$) {\n        var {$context} = \$('form#{$formName} .hr-case-application-profile');\n        \$('div#application_case',{$context}).remove();\n      });\n    </script>";
    }
    if ($requiredAct && $context == "form" && in_array($aType, $activityTypes)) {
        $completeStatus = CRM_Core_OptionGroup::getValue('activity_status', 'Completed');
        $formname = $smarty->_tpl_vars['form']['formName'];
        $hideFields = '';
        //Array for the unwanted fields
        $hide = array('client_name' => 'Client', 'activityTypeName' => 'Activity.Type', 'source_contact_id' => 'Created.By', 'duration' => 'Location', 'priority_id' => 'Priority', 'medium_id' => 'Medium');
        if ($aType == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Comment')) {
            $hide['assignee_contact_id'] = 'Assigned.To';
            $hide['status_id'] = 'Status';
            $hide['activity_date_time'] = 'Date.and.Time';
        }
        foreach ($hide as $hideForm => $hideView) {
            $hideFields .= "\$('.crm-case-activity-form-block-{$hideForm}', context).hide();";
            $hideFields .= "\$('.crm-case-activity-view-{$hideView}', context).hide();";
        }
        //Add script to the content to hide the above fields and show Evaluation profile for Completed status
        $content .= "<script type=\"text/javascript\">\n      CRM.\$(function(\$) {\n        var context = \$('form#{$formname}');\n        toggleEvaluation(\$('#status_id', context).val());\n        \$('#customData', context).hide();\n        \$('#sendcopy', context).hide();\n        \$('#follow-up', context).hide();\n        \$('.crm-accordion-wrapper', context).hide();\n        {$hideFields}\n        \$('#status_id', context).bind('change', function(){\n          toggleEvaluation(this.value);\n        });\n        function toggleEvaluation(val) {\n          if(val == {$completeStatus}) {\n            \$('.crm-profile-name-evaluation_profile', context).show();\n          }\n          else {\n            \$('.crm-profile-name-evaluation_profile', context).hide();\n          }\n        }\n      });\n    </script>";
    }
}