Exemplo n.º 1
0
 function validateData(&$input, &$ids, &$objects, $required = true)
 {
     // make sure contact exists and is valid
     require_once 'CRM/Contact/DAO/Contact.php';
     $contact = new CRM_Contact_DAO_Contact();
     $contact->id = $ids['contact'];
     if (!$contact->find(true)) {
         CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']}");
         echo "Failure: Could not find contact record: {$ids['contact']}<p>";
         return false;
     }
     // make sure contribution exists and is valid
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->id = $ids['contribution'];
     if (!$contribution->find(true)) {
         CRM_Core_Error::debug_log_message("Could not find contribution record: {$contributionID}");
         echo "Failure: Could not find contribution record for {$contributionID}<p>";
         return false;
     }
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $objects['contact'] =& $contact;
     $objects['contribution'] =& $contribution;
     if (!$this->loadObjects($input, $ids, $objects, $required)) {
         return false;
     }
     return true;
 }
Exemplo n.º 2
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     //Check if there are contributions related to Contribution Page
     parent::preProcess();
     //check for delete
     if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
     }
     $dao = new CRM_Contribute_DAO_Contribution();
     $dao->contribution_page_id = $this->_id;
     if ($dao->find(TRUE)) {
         $this->_relatedContributions = TRUE;
         $this->assign('relatedContributions', TRUE);
     }
 }
Exemplo n.º 3
0
 /**
  * Set variables up before form is built.
  *
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 public static function preProcess(&$form)
 {
     $contriDAO = new CRM_Contribute_DAO_Contribution();
     $contriDAO->id = $form->_id;
     $contriDAO->find(TRUE);
     if ($contriDAO->contribution_page_id) {
         $ufJoinParams = array('module' => 'soft_credit', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $contriDAO->contribution_page_id);
         $profileId = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         //check if any honree profile is enabled if yes then assign its profile type to $_honoreeProfileType
         // which will be used to constraint soft-credit contact type in formRule, CRM-13981
         if ($profileId[0]) {
             $form->_honoreeProfileType = CRM_Core_BAO_UFGroup::getContactType($profileId[0]);
         }
     }
 }
Exemplo n.º 4
0
 /**
  * Checks to see if invoice_id already exists in db
  * @param  int     $invoiceId   The ID to check
  * @return bool                  True if ID exists, else false
  */
 function _checkDupe($invoiceId)
 {
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->invoice_id = $invoiceId;
     return $contribution->find();
 }
Exemplo n.º 5
0
 /**
  *
  * /**
  * The function returns the component(Event/Contribute..)and whether it is Test or not
  *
  * @param array $privateData
  *   Contains the name-value pairs of transaction related data.
  * @param int $orderNo
  *   <order-total> send by google.
  *
  * @return array
  *   context of this call (test, component, payment processor id)
  */
 public static function getContext($privateData, $orderNo)
 {
     $component = NULL;
     $isTest = NULL;
     $contributionID = $privateData['contributionID'];
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->id = $contributionID;
     if (!$contribution->find(TRUE)) {
         CRM_Core_Error::debug_log_message("Could not find contribution record: {$contributionID}");
         echo "Failure: Could not find contribution record for {$contributionID}<p>";
         exit;
     }
     if (stristr($contribution->source, 'Online Contribution')) {
         $component = 'contribute';
     } elseif (stristr($contribution->source, 'Online Event Registration')) {
         $component = 'event';
     }
     $isTest = $contribution->is_test;
     $duplicateTransaction = 0;
     if ($contribution->contribution_status_id == 1) {
         //contribution already handled. (some processors do two notifications so this could be valid)
         $duplicateTransaction = 1;
     }
     if ($component == 'contribute') {
         if (!$contribution->contribution_page_id) {
             CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: {$contributionID}");
             echo "Failure: Could not find contribution page for contribution record: {$contributionID}<p>";
             exit;
         }
     } else {
         $eventID = $privateData['eventID'];
         if (!$eventID) {
             CRM_Core_Error::debug_log_message("Could not find event ID");
             echo "Failure: Could not find eventID<p>";
             exit;
         }
         // we are in event mode
         // make sure event exists and is valid
         $event = new CRM_Event_DAO_Event();
         $event->id = $eventID;
         if (!$event->find(TRUE)) {
             CRM_Core_Error::debug_log_message("Could not find event: {$eventID}");
             echo "Failure: Could not find event: {$eventID}<p>";
             exit;
         }
     }
     return array($isTest, $component, $duplicateTransaction);
 }
Exemplo n.º 6
0
 /**
  * Function to get list of contribution In Honor of contact Ids
  *
  * @param int $honorId In Honor of Contact ID
  *
  * @return return the list of contribution fields
  * 
  * @access public
  * @static
  */
 static function getHonorContacts($honorId)
 {
     $params = array();
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $honorDAO = new CRM_Contribute_DAO_Contribution();
     $honorDAO->honor_contact_id = $honorId;
     $honorDAO->find();
     require_once 'CRM/Contribute/PseudoConstant.php';
     $status = CRM_Contribute_Pseudoconstant::contributionStatus($honorDAO->contribution_status_id);
     $type = CRM_Contribute_Pseudoconstant::contributionType();
     while ($honorDAO->fetch()) {
         $params[$honorDAO->id]['honorId'] = $honorDAO->contact_id;
         $params[$honorDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $honorDAO->contact_id, 'display_name');
         $params[$honorDAO->id]['type'] = $type[$honorDAO->contribution_type_id];
         $params[$honorDAO->id]['type_id'] = $honorDAO->contribution_type_id;
         $params[$honorDAO->id]['amount'] = CRM_Utils_Money::format($honorDAO->total_amount, $honorDAO->currency);
         $params[$honorDAO->id]['source'] = $honorDAO->source;
         $params[$honorDAO->id]['receive_date'] = $honorDAO->receive_date;
         $params[$honorDAO->id]['contribution_status'] = CRM_Utils_Array::value($honorDAO->contribution_status_id, $status);
     }
     return $params;
 }
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     $mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, true);
     if (!CRM_Core_Permission::check('edit memberships')) {
         require_once 'CRM/Contact/BAO/Contact/Utils.php';
         $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, false);
         $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $mid, "contact_id");
         if (!CRM_Contact_BAO_Contact_Utils::validChecksum($contactID, $userChecksum)) {
             CRM_Core_Error::fatal(ts('You do not have permission to cancel subscription.'));
         }
     }
     $cid = CRM_Utils_Request::retrieve('cid', 'Integer', $this, false);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this, false);
     $selectedChild = CRM_Utils_Request::retrieve('selectedChild', 'String', $this, false);
     if (!$context) {
         $context = CRM_Utils_Request::retrieve('compContext', 'String', $this, false);
     }
     $qfkey = CRM_Utils_Request::retrieve('key', 'String', $this, false);
     if ($cid) {
         $this->_userContext = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&selectedChild={$selectedChild}&cid={$cid}");
     } else {
         if ($mid) {
             $this->_userContext = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
             if ($context == 'dashboard') {
                 $this->_userContext = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
             }
         }
     }
     $session = CRM_Core_Session::singleton();
     if ($session->get('userID')) {
         $session->pushUserContext($this->_userContext);
     }
     if ($mid) {
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $mid, 'membership_type_id');
         $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
         require_once 'CRM/Member/BAO/Membership.php';
         if (CRM_Member_BAO_Membership::isSubscriptionCancelled($mid)) {
             CRM_Core_Error::fatal(ts('The auto renew membership looks to have been cancelled already.'));
         }
         $isCancelSupported = CRM_Member_BAO_Membership::isCancelSubscriptionSupported($mid, false);
     }
     if ($isCancelSupported) {
         $sql = " \n    SELECT mp.contribution_id, rec.id as recur_id, rec.processor_id \n      FROM civicrm_membership_payment mp \nINNER JOIN civicrm_membership         mem ON ( mp.membership_id = mem.id ) \nINNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )\nINNER JOIN civicrm_contribution       con ON ( con.id = mp.contribution_id )\n     WHERE mp.membership_id = {$mid}";
         $dao = CRM_Core_DAO::executeQuery($sql);
         if ($dao->fetch()) {
             $this->_contributionRecurId = $dao->recur_id;
             $this->_subscriptionId = $dao->processor_id;
             $contributionId = $dao->contribution_id;
         }
         if ($contributionId) {
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contribution = new CRM_Contribute_DAO_Contribution();
             $contribution->id = $contributionId;
             $contribution->find(true);
             $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
             $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
             $this->_objects['contribution'] = $contribution;
             $this->_paymentObject = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($mid, 'membership', 'obj');
         }
     } else {
         CRM_Core_Error::fatal(ts('Could not detect payment processor OR the processor does not support cancellation of auto renew.'));
     }
 }
 public function moveRecurringRecord($submittedValues)
 {
     // Move recurring record to another contact
     if (!empty($submittedValues['contact_id']) && $submittedValues['contact_id'] != $this->_contactID) {
         $selected_cid = $submittedValues['contact_id'];
         // FIXME: Not getting the below value in $submittedValues
         // So taking the value from $_POST
         if (isset($_POST['membership_record'])) {
             $membership_record = $_POST['membership_record'];
         }
         // Update contact id in civicrm_contribution_recur table
         $recurring = new CRM_Contribute_BAO_ContributionRecur();
         $recurring->id = $this->_id;
         if ($recurring->find(TRUE)) {
             $recurParams = (array) $recurring;
             $recurParams['contact_id'] = $selected_cid;
             CRM_Contribute_BAO_ContributionRecur::create($recurParams);
         }
         // Update contact id in civicrm_contribution table, if 'Move Existing Contributions?' is ticked
         if (isset($submittedValues['move_existing_contributions']) && $submittedValues['move_existing_contributions'] == 1) {
             $contribution = new CRM_Contribute_DAO_Contribution();
             $contribution->contribution_recur_id = $this->_id;
             $contribution->find();
             while ($contribution->fetch()) {
                 $contributionParams = (array) $contribution;
                 $contributionParams['contact_id'] = $selected_cid;
                 // Update contact_id of contributions
                 // related to the recurring contribution
                 CRM_Contribute_BAO_Contribution::create($contributionParams);
             }
         }
     }
     if (!empty($membership_record)) {
         // Remove the contribution_recur_id from existing membership
         if (!empty($this->_membershipID)) {
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_membershipID;
             if ($membership->find(TRUE)) {
                 $membershipParams = (array) $membership;
                 $membershipParams['contribution_recur_id'] = 'NULL';
                 CRM_Member_BAO_Membership::add($membershipParams);
             }
         }
         // Update contribution_recur_id to the new membership
         $membership = new CRM_Member_DAO_Membership();
         $membership->id = $membership_record;
         if ($membership->find(TRUE)) {
             $membershipParams = (array) $membership;
             $membershipParams['contribution_recur_id'] = $this->_id;
             CRM_Member_BAO_Membership::add($membershipParams);
         }
     }
 }
Exemplo n.º 9
0
 /**
  * Gives required details of contribuion in an indexed array format so we
  * can iterate in a nice loop and do token evaluation
  *
  * @param array $contributionIDs
  * @param array $returnProperties
  *   Of required properties.
  * @param array $extraParams
  *   Extra params.
  * @param array $tokens
  *   The list of tokens we've extracted from the content.
  * @param string $className
  *
  * @return array
  */
 public static function getContributionTokenDetails($contributionIDs, $returnProperties = NULL, $extraParams = NULL, $tokens = array(), $className = NULL)
 {
     // @todo this function basically replicates calling
     // civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
     if (empty($contributionIDs)) {
         // putting a fatal here so we can track if/when this happens
         CRM_Core_Error::fatal();
     }
     $details = array();
     // no apiQuery helper yet, so do a loop and find contribution by id
     foreach ($contributionIDs as $contributionID) {
         $dao = new CRM_Contribute_DAO_Contribution();
         $dao->id = $contributionID;
         if ($dao->find(TRUE)) {
             $details[$dao->id] = array();
             CRM_Core_DAO::storeValues($dao, $details[$dao->id]);
             // do the necessary transformation
             if (!empty($details[$dao->id]['payment_instrument_id'])) {
                 $piId = $details[$dao->id]['payment_instrument_id'];
                 $pis = CRM_Contribute_PseudoConstant::paymentInstrument();
                 $details[$dao->id]['payment_instrument'] = $pis[$piId];
             }
             if (!empty($details[$dao->id]['campaign_id'])) {
                 $campaignId = $details[$dao->id]['campaign_id'];
                 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
                 $details[$dao->id]['campaign'] = $campaigns[$campaignId];
             }
             if (!empty($details[$dao->id]['financial_type_id'])) {
                 $financialtypeId = $details[$dao->id]['financial_type_id'];
                 $ftis = CRM_Contribute_PseudoConstant::financialType();
                 $details[$dao->id]['financial_type'] = $ftis[$financialtypeId];
             }
             // @todo call a hook to get token contribution details
         }
     }
     return $details;
 }
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return None
  */
 function postProcess()
 {
     // lets get around the time limit issue if possible
     if (!ini_get('safe_mode')) {
         set_time_limit(0);
     }
     // Issue 1895204: Turn off geocoding to avoid hitting Google API limits
     $config =& CRM_Core_Config::singleton();
     $oldGeocode = $config->geocodeMethod;
     unset($config->geocodeMethod);
     $params = $this->controller->exportValues($this->_name);
     $originalOnly = FALSE;
     if ($params['receipt_option'] == 'original_only') {
         $originalOnly = TRUE;
     }
     $previewMode = FALSE;
     if (isset($params['is_preview']) && $params['is_preview'] == 1) {
         $previewMode = TRUE;
     }
     /**
      * Drupal module include
      */
     //module_load_include('.inc','civicrm_cdntaxreceipts','civicrm_cdntaxreceipts');
     //module_load_include('.module','civicrm_cdntaxreceipts','civicrm_cdntaxreceipts');
     // start a PDF to collect receipts that cannot be emailed
     $receiptsForPrinting = cdntaxreceipts_openCollectedPDF();
     $emailCount = 0;
     $printCount = 0;
     $failCount = 0;
     foreach ($this->_contributionIds as $item => $contributionId) {
         if ($emailCount + $printCount + $failCount >= self::MAX_RECEIPT_COUNT) {
             $status = ts('Maximum of %1 tax receipt(s) were sent. Please repeat to continue processing.', array(1 => self::MAX_RECEIPT_COUNT, 'domain' => 'org.civicrm.cdntaxreceipts'));
             CRM_Core_Session::setStatus($status, '', 'info');
             break;
         }
         // 1. Load Contribution information
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->id = $contributionId;
         if (!$contribution->find(TRUE)) {
             CRM_Core_Error::fatal("CDNTaxReceipts: Could not find corresponding contribution id.");
         }
         // 2. If Contribution is eligible for receipting, issue the tax receipt.  Otherwise ignore.
         if (cdntaxreceipts_eligibleForReceipt($contribution->id)) {
             list($issued_on, $receipt_id) = cdntaxreceipts_issued_on($contribution->id);
             if (empty($issued_on) || !$originalOnly) {
                 list($ret, $method) = cdntaxreceipts_issueTaxReceipt($contribution, $receiptsForPrinting, $previewMode);
                 if ($ret == 0) {
                     $failCount++;
                 } elseif ($method == 'email') {
                     $emailCount++;
                 } else {
                     $printCount++;
                 }
             }
         }
     }
     // 3. Set session status
     if ($previewMode) {
         $status = ts('%1 tax receipt(s) have been previewed.  No receipts have been issued.', array(1 => $printCount, 'domain' => 'org.civicrm.cdntaxreceipts'));
         CRM_Core_Session::setStatus($status, '', 'success');
     } else {
         $status = ts('%1 tax receipt(s) were sent by email.', array(1 => $emailCount, 'domain' => 'org.civicrm.cdntaxreceipts'));
         CRM_Core_Session::setStatus($status, '', 'success');
         $status = ts('%1 tax receipt(s) need to be printed.', array(1 => $printCount, 'domain' => 'org.civicrm.cdntaxreceipts'));
         CRM_Core_Session::setStatus($status, '', 'success');
     }
     if ($failCount > 0) {
         $status = ts('%1 tax receipt(s) failed to process.', array(1 => $failCount, 'domain' => 'org.civicrm.cdntaxreceipts'));
         CRM_Core_Session::setStatus($status, '', 'error');
     }
     // Issue 1895204: Reset geocoding
     $config->geocodeMethod = $oldGeocode;
     // 4. send the collected PDF for download
     // NB: This exits if a file is sent.
     cdntaxreceipts_sendCollectedPDF($receiptsForPrinting, 'Receipts-To-Print-' . (int) $_SERVER['REQUEST_TIME'] . '.pdf');
     // EXITS.
 }
Exemplo n.º 11
0
 static function _fillCommonParams(&$params, $type = 'paypal')
 {
     if (array_key_exists('transaction', $params)) {
         $transaction =& $params['transaction'];
     } else {
         $transaction =& $params;
     }
     $params['contact_type'] = 'Individual';
     $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
     if (!$billingLocTypeId) {
         $billingLocTypeId = 1;
     }
     if (!CRM_Utils_System::isNull($params['address'])) {
         $params['address'][1]['is_primary'] = 1;
         $params['address'][1]['location_type_id'] = $billingLocTypeId;
     }
     if (!CRM_Utils_System::isNull($params['email'])) {
         $params['email'] = array(1 => array('email' => $params['email'], 'location_type_id' => $billingLocTypeId));
     }
     if (isset($transaction['trxn_id'])) {
         // set error message if transaction has already been processed.
         require_once 'CRM/Contribute/DAO/Contribution.php';
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->trxn_id = $transaction['trxn_id'];
         if ($contribution->find(true)) {
             $params['error'][] = ts('transaction already processed.');
         }
     } else {
         // generate a new transaction id, if not already exist
         $transaction['trxn_id'] = md5(uniqid(rand(), true));
     }
     if (!isset($transaction['contribution_type_id'])) {
         require_once 'CRM/Contribute/PseudoConstant.php';
         $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::contributionType());
         $transaction['contribution_type_id'] = $contributionTypes[0];
     }
     if ($type == 'paypal' && !isset($transaction['net_amount'])) {
         $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
     }
     if (!isset($transaction['invoice_id'])) {
         $transaction['invoice_id'] = $transaction['trxn_id'];
     }
     $source = ts('ContributionProcessor: %1 API', array(1 => ucfirst($type)));
     if (isset($transaction['source'])) {
         $transaction['source'] = $source . ':: ' . $transaction['source'];
     } else {
         $transaction['source'] = $source;
     }
     return true;
 }
Exemplo n.º 12
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::del($this->_id);
         return;
     }
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $this->convertDateFieldsToMySQL($formValues);
     $params = $softParams = $ids = array();
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($this->_params['auto_renew'])) {
         $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
         // unset send-receipt option, since receipt will be sent when ipn is received.
         unset($this->_params['send_receipt'], $formValues['send_receipt']);
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = NULL;
     if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) {
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     $termsByType = array();
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
         if (!empty($lineItem[$priceSetId])) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 if (!empty($li['membership_type_id'])) {
                     if (!empty($li['membership_num_terms'])) {
                         $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                     }
                 }
                 ///CRM-11529 for quick config backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if ($isQuickConfig && $submittedFinancialType) {
                     $li['financial_type_id'] = $submittedFinancialType;
                 }
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $num_terms = CRM_Utils_Array::value('num_terms', $formValues, 1);
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, $num_terms);
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
             //$params[$d] = CRM_Utils_Date::processDate( $date );
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     foreach ($this->_memTypeSelected as $memType) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     }
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-10223 - allow contribution to be recorded against different contact
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($this->_params['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             $softParams['contact_id'] = $params['contact_id'];
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $allStatus = CRM_Member_PseudoConstant::membershipStatus();
             $params['status_id'] = array_search('Pending', $allStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         if (empty($formValues['total_amount']) && !$priceSetId) {
             // if total amount not provided minimum for membership type is used
             $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee');
         } else {
             $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         }
         if ($priceSetId && !$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $fields["email-{$this->_bltID}"] = 1;
         }
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         }
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         $this->_params['financial_type_id'] = $params['financial_type_id'];
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             }
         }
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recuring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $allStatus = CRM_Member_PseudoConstant::membershipStatus();
             $contributionType = new CRM_Financial_DAO_FinancialType();
             $contributionType->id = $params['financial_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, FALSE, TRUE, FALSE);
             //create new soft-credit record, CRM-13981
             $softParams['contribution_id'] = $contribution->id;
             $softParams['currency'] = $contribution->currency;
             $softParams['amount'] = $contribution->total_amount;
             CRM_Contribute_BAO_ContributionSoft::add($softParams);
             $paymentParams['contactID'] = $contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
             $params['status_id'] = array_search('Pending', $allStatus);
             $params['skipStatusCal'] = TRUE;
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dp => $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         if ($params['total_amount'] > 0.0) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $result =& $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (!empty($paymentParams['contributionID'])) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (!empty($paymentParams['contributionRecurID'])) {
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
             //assign amount to template if payment was successful
             $this->assign('amount', $params['total_amount']);
         }
         $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1;
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($this->_params['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution');
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $fieldType = NULL;
                 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
                     $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
                 }
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem);
                 //create new soft-credit record, CRM-13981
                 $softParams['contribution_id'] = $params['contribution_id'];
                 $dao = new CRM_Contribute_DAO_Contribution();
                 $dao->id = $params['contribution_id'];
                 $dao->find();
                 while ($dao->fetch()) {
                     $softParams['currency'] = $dao->currency;
                     $softParams['amount'] = $dao->total_amount;
                 }
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 $membershipStatues = CRM_Member_PseudoConstant::membershipStatus();
                 if (!in_array($membership->status_id, array(array_search('Cancelled', $membershipStatues), array_search('Expired', $membershipStatues)))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             // FIX ME: need to recheck this
             // here we might updated dates, so get from object.
             foreach ($calcDates[$membership->membership_type_id] as $date => &$val) {
                 if ($membership->{$date}) {
                     $val = $membership->{$date};
                 }
             }
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$priceSetId])) {
         foreach ($lineItem[$priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%d%f %b, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%d%f %b, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     if (!empty($formValues['send_receipt'])) {
         $receiptSend = TRUE;
         $formValues['contact_id'] = $this->_contactID;
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         //end date can be modified by hooks, so if end date is set then use it.
         $endDate = $membership->end_date ? $membership->end_date : $endDate;
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
         if ($endDate && $endDate !== 'null') {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // FIX ME: fix status messages
         $statusMsg = array();
         foreach ($membershipTypes as $memType => $membershipType) {
             $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName));
             $membership = $createdMemberships[$memType];
             $memEndDate = $membership->end_date ? $membership->end_date : $endDate;
             //get the end date from calculated dates.
             if (!$memEndDate && empty($params['is_recur'])) {
                 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
             }
             if ($memEndDate && $memEndDate !== 'null') {
                 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
                 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
             }
         }
         $statusMsg = implode('<br/>', $statusMsg);
         if ($receiptSend && $mailSend) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
     }
 }
Exemplo n.º 13
0
 /**
  * @param $form
  * @param array $params Parameters from the form.
  */
 public static function postProcess($form, $params)
 {
     if (!empty($form->_honor_block_is_active) && !empty($params['soft_credit_type_id'])) {
         $honorId = NULL;
         //check if there is any duplicate contact
         $profileContactType = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']);
         $dedupeParams = CRM_Dedupe_Finder::formatParams($params['honor'], $profileContactType);
         $dedupeParams['check_permission'] = FALSE;
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $profileContactType);
         if (count($ids)) {
             $honorId = CRM_Utils_Array::value(0, $ids);
         }
         $honorId = CRM_Contact_BAO_Contact::createProfileContact($params['honor'], CRM_Core_DAO::$_nullArray, $honorId, NULL, $params['honoree_profile_id']);
         $softParams = array();
         $softParams['contribution_id'] = $form->_contributionID;
         $softParams['contact_id'] = $honorId;
         $softParams['soft_credit_type_id'] = $params['soft_credit_type_id'];
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->id = $form->_contributionID;
         $contribution->find();
         while ($contribution->fetch()) {
             $softParams['currency'] = $contribution->currency;
             $softParams['amount'] = $contribution->total_amount;
         }
         CRM_Contribute_BAO_ContributionSoft::add($softParams);
         if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
             $form->_values['honor'] = array('soft_credit_type' => CRM_Utils_Array::value($params['soft_credit_type_id'], CRM_Core_OptionGroup::values("soft_credit_type")), 'honor_id' => $honorId, 'honor_profile_id' => $params['honoree_profile_id'], 'honor_profile_values' => $params['honor']);
         }
     }
 }
Exemplo n.º 14
0
 /**  
 
 /**  
 * The function returns the component(Event/Contribute..)and whether it is Test or not
 *  
 * @param array   $privateData    contains the name-value pairs of transaction related data
 * @param int     $orderNo        <order-total> send by google
 *  
 * @return array context of this call (test, component, payment processor id)
 * @static  
 */
 static function getContext($privateData, $orderNo)
 {
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $component = null;
     $isTest = null;
     $contributionID = $privateData['contributionID'];
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->id = $contributionID;
     if (!$contribution->find(true)) {
         CRM_Core_Error::debug_log_message("Could not find contribution record: {$contributionID}");
         echo "Failure: Could not find contribution record for {$contributionID}<p>";
         exit;
     }
     if (stristr($contribution->source, 'Online Contribution')) {
         $component = 'contribute';
     } elseif (stristr($contribution->source, 'Online Event Registration')) {
         $component = 'event';
     }
     $isTest = $contribution->is_test;
     $duplicateTransaction = 0;
     if ($contribution->contribution_status_id == 1) {
         //contribution already handled. (some processors do two notifications so this could be valid)
         $duplicateTransaction = 1;
     }
     if ($component == 'contribute') {
         if (!$contribution->contribution_page_id) {
             CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: {$contributionID}");
             echo "Failure: Could not find contribution page for contribution record: {$contributionID}<p>";
             exit;
         }
         // get the payment processor id from contribution page
         $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $contribution->contribution_page_id, 'payment_processor_id');
     } else {
         $eventID = $privateData['eventID'];
         if (!$eventID) {
             CRM_Core_Error::debug_log_message("Could not find event ID");
             echo "Failure: Could not find eventID<p>";
             exit;
         }
         // we are in event mode
         // make sure event exists and is valid
         require_once 'CRM/Event/DAO/Event.php';
         $event = new CRM_Event_DAO_Event();
         $event->id = $eventID;
         if (!$event->find(true)) {
             CRM_Core_Error::debug_log_message("Could not find event: {$eventID}");
             echo "Failure: Could not find event: {$eventID}<p>";
             exit;
         }
         // get the payment processor id from contribution page
         $paymentProcessorID = $event->payment_processor_id;
     }
     if (!$paymentProcessorID) {
         CRM_Core_Error::debug_log_message("Could not find payment processor for contribution record: {$contributionID}");
         echo "Failure: Could not find payment processor for contribution record: {$contributionID}<p>";
         exit;
     }
     return array($isTest, $component, $paymentProcessorID, $duplicateTransaction);
 }
 /**
  * Checks to see if invoice_id already exists in db
  *
  * @param  int     $invoiceId   The ID to check
  *
  * @return bool                  True if ID exists, else false
  */
 function _checkDupe($invoiceId)
 {
     //copied from Eway but not working and not really sure it should!
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->invoice_id = $invoiceId;
     return $contribution->find();
 }
 /**
  * This function sets the default values for the form in edit/view mode
  * the default values are retrieved from the database
  *
  * @access public
  *
  * @return None
  */
 static function setDefaultValues(&$form)
 {
     $defaults = array();
     if ($form->_eventId) {
         //get receipt text and contribution type
         $returnProperities = array('confirm_email_text', 'contribution_type_id', 'campaign_id');
         $details = array();
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
         if (CRM_Utils_Array::value('contribution_type_id', $details[$form->_eventId])) {
             $defaults[$form->_pId]['contribution_type_id'] = $details[$form->_eventId]['contribution_type_id'];
         }
     }
     if ($form->_pId) {
         $ids = array();
         $params = array('id' => $form->_pId);
         CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
         if ($form->_action == CRM_Core_Action::UPDATE) {
             $discounts = array();
             if (!empty($form->_values['discount'])) {
                 foreach ($form->_values['discount'] as $key => $value) {
                     $discounts[$key] = $value['name'];
                 }
             }
             if ($form->_discountId) {
                 $form->assign('discount', $discounts[$defaults[$form->_pId]['discount_id']]);
             }
             $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
             $form->assign('fee_level', CRM_Utils_Array::value('fee_level', $defaults[$form->_pId]));
         }
         $defaults[$form->_pId]['send_receipt'] = 0;
     } else {
         $defaults[$form->_pId]['send_receipt'] = 1;
         if ($form->_eventId && CRM_Utils_Array::value('confirm_email_text', $details[$form->_eventId])) {
             //set receipt text
             $defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
         }
         list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults();
     }
     if ($form->_mode) {
         $fields = array();
         foreach ($form->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         $names = array('first_name', 'middle_name', 'last_name', "street_address-{$form->_bltID}", "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "country_id-{$form->_bltID}", "state_province_id-{$form->_bltID}");
         foreach ($names as $name) {
             $fields[$name] = 1;
         }
         $fields["state_province-{$form->_bltID}"] = 1;
         $fields["country-{$form->_bltID}"] = 1;
         $fields["email-{$form->_bltID}"] = 1;
         $fields['email-Primary'] = 1;
         if ($form->_contactId) {
             CRM_Core_BAO_UFGroup::setProfileDefaults($form->_contactId, $fields, $form->_defaults);
         }
         // use primary email address if billing email address is empty
         if (empty($form->_defaults["email-{$form->_bltID}"]) && !empty($form->_defaults['email-Primary'])) {
             $defaults[$form->_pId]["email-{$form->_bltID}"] = $form->_defaults['email-Primary'];
         }
         foreach ($names as $name) {
             if (!empty($form->_defaults[$name])) {
                 $defaults[$form->_pId]['billing_' . $name] = $form->_defaults[$name];
             }
         }
         $config = CRM_Core_Config::singleton();
         // set default country from config if no country set
         if (!CRM_Utils_Array::value("billing_country_id-{$form->_bltID}", $defaults[$form->_pId])) {
             $defaults[$form->_pId]["billing_country_id-{$form->_bltID}"] = $config->defaultContactCountry;
         }
         //             // hack to simplify credit card entry for testing
         //             $defaults[$form->_pId]['credit_card_type']     = 'Visa';
         //             $defaults[$form->_pId]['credit_card_number']   = '4807731747657838';
         //             $defaults[$form->_pId]['cvv2']                 = '000';
         //             $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
     }
     if ($priceSetId = CRM_Price_BAO_Set::getFor('civicrm_event', $form->_eventId)) {
         // get price set default values, CRM-4090
         if (in_array(get_class($form), array('CRM_Event_Form_Participant', 'CRM_Event_Form_Registration_Register', 'CRM_Event_Form_Registration_AdditionalParticipant'))) {
             $priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
             if (!empty($priceSetValues)) {
                 $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $priceSetValues);
             }
         }
         if ($form->_action == CRM_Core_Action::ADD && CRM_Utils_Array::value('fields', $form->_priceSet)) {
             foreach ($form->_priceSet['fields'] as $key => $val) {
                 foreach ($val['options'] as $keys => $values) {
                     if ($values['is_default']) {
                         if (get_class($form) != 'CRM_Event_Form_Participant' && CRM_Utils_Array::value('is_full', $values)) {
                             continue;
                         }
                         if ($val['html_type'] == 'CheckBox') {
                             $defaults[$form->_pId]["price_{$key}"][$keys] = 1;
                         } else {
                             $defaults[$form->_pId]["price_{$key}"] = $keys;
                         }
                     }
                 }
             }
         }
         $form->assign('totalAmount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
         if ($form->_action == CRM_Core_Action::UPDATE) {
             $fee_level = $defaults[$form->_pId]['fee_level'];
             CRM_Event_BAO_Participant::fixEventLevel($fee_level);
             $form->assign('fee_level', $fee_level);
             $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
         }
     } else {
         $optionGroupId = NULL;
         // if user has selected discount use that to set default
         if (isset($form->_discountId)) {
             $defaults[$form->_pId]['discount_id'] = $form->_discountId;
             //hack to set defaults for already selected discount value
             if ($form->_action == CRM_Core_Action::UPDATE && !$form->_originalDiscountId) {
                 $form->_originalDiscountId = $defaults[$form->_pId]['discount_id'];
                 if ($form->_originalDiscountId) {
                     $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $form->_originalDiscountId, 'option_group_id');
                     $defaults[$form->_pId]['discount_id'] = $form->_originalDiscountId;
                 }
             }
         }
         if ($form->_action == CRM_Core_Action::ADD) {
             // this case is for add mode, where we show discount automatically
             if (!isset($form->_discountId)) {
                 $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
             } else {
                 $discountId = $form->_discountId;
             }
             if ($form->_eventId && $discountId) {
                 $defaultDiscountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'default_discount_fee_id');
                 if ($defaultDiscountId) {
                     $discountKey = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $defaultDiscountId, 'weight');
                 }
                 $defaults[$form->_pId]['discount_id'] = $discountId;
                 $defaults[$form->_pId]['amount'] = key(array_slice($form->_values['discount'][$discountId], $discountKey - 1, $discountKey, TRUE));
                 $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $discountId, 'option_group_id');
             } else {
                 if ($form->_eventId) {
                     $defaults[$form->_pId]['amount'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'default_fee_id');
                 }
             }
         }
         if (CRM_Utils_Array::value('event_id', $defaults[$form->_pId]) && ($form->_action == CRM_Core_Action::UPDATE || $form->_allowConfirmation)) {
             if (!empty($form->_feeBlock)) {
                 $feeLevel = CRM_Utils_Array::value('fee_level', $defaults[$form->_pId]);
                 $feeAmount = CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]);
                 foreach ($form->_feeBlock as $amountId => $amountInfo) {
                     if ($amountInfo['label'] == $feeLevel && $amountInfo['value'] == $feeAmount) {
                         $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
                     }
                     // if amount is not set do fuzzy matching
                     if (!isset($defaults[$form->_pId]['amount'])) {
                         // if only level use that
                         if ($amountInfo['label'] == $feeLevel) {
                             $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
                         } elseif (strpos($feeLevel, $amountInfo['label']) !== FALSE) {
                             $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
                         } elseif ($amountInfo['value'] == $feeAmount) {
                             // if amount matches use that
                             $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
                         }
                     }
                 }
             }
         }
         $form->assign('amountId', CRM_Utils_Array::value('amount', $defaults[$form->_pId]));
     }
     //CRM-4453
     if (CRM_Utils_Array::value('participant_fee_currency', $defaults[$form->_pId])) {
         $form->assign('fee_currency', $defaults[$form->_pId]['participant_fee_currency']);
     }
     // CRM-4395
     if ($contriId = $form->get('onlinePendingContributionId')) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->id = $contriId;
         $contribution->find(TRUE);
         foreach (array('contribution_type_id', 'payment_instrument_id', 'contribution_status_id', 'receive_date', 'total_amount') as $f) {
             if ($f == 'receive_date') {
                 list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->{$f});
             } else {
                 $defaults[$form->_pId][$f] = $contribution->{$f};
             }
         }
     }
     return $defaults[$form->_pId];
 }
Exemplo n.º 17
0
/**
 * take the input parameter list as specified in the data model and
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array $params
 *   Associative array of property name/value.
 *                             pairs to insert in new contact.
 * @param array $values
 *   The reformatted properties that we can use internally.
 *                            '
 *
 * @param bool $create
 * @param null $onDuplicate
 *
 * @return array|CRM_Error
 */
function _civicrm_api3_deprecated_formatted_param($params, &$values, $create = FALSE, $onDuplicate = NULL)
{
    // copy all the contribution fields as is
    $fields = CRM_Contribute_DAO_Contribution::fields();
    _civicrm_api3_store_values($fields, $params, $values);
    require_once 'CRM/Core/OptionGroup.php';
    $customFields = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        // Handling Custom Data
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            $values[$key] = $value;
            $type = $customFields[$customFieldID]['html_type'];
            if ($type == 'CheckBox' || $type == 'Multi-Select') {
                $mulValues = explode(',', $value);
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                $values[$key] = array();
                foreach ($mulValues as $v1) {
                    foreach ($customOption as $customValueID => $customLabel) {
                        $customValue = $customLabel['value'];
                        if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            if ($type == 'CheckBox') {
                                $values[$key][$customValue] = 1;
                            } else {
                                $values[$key][] = $customValue;
                            }
                        }
                    }
                }
            } elseif ($type == 'Select' || $type == 'Radio' || $type == 'Autocomplete-Select' && $customFields[$customFieldID]['data_type'] == 'String') {
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                foreach ($customOption as $customFldID => $customValue) {
                    $val = CRM_Utils_Array::value('value', $customValue);
                    $label = CRM_Utils_Array::value('label', $customValue);
                    $label = strtolower($label);
                    $value = strtolower(trim($value));
                    if ($value == $label || $value == strtolower($val)) {
                        $values[$key] = $val;
                    }
                }
            }
        }
        switch ($key) {
            case 'contribution_contact_id':
                if (!CRM_Utils_Rule::integer($value)) {
                    return civicrm_api3_create_error("contact_id not valid: {$value}");
                }
                $dao = new CRM_Core_DAO();
                $qParams = array();
                $svq = $dao->singleValueQuery("SELECT is_deleted FROM civicrm_contact WHERE id = {$value}", $qParams);
                if (!isset($svq)) {
                    return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                } elseif ($svq == 1) {
                    return civicrm_api3_create_error("Invalid Contact ID: contact_id {$value} is a soft-deleted contact.");
                }
                $values['contact_id'] = $values['contribution_contact_id'];
                unset($values['contribution_contact_id']);
                break;
            case 'contact_type':
                // import contribution record according to select contact type
                require_once 'CRM/Contact/DAO/Contact.php';
                $contactType = new CRM_Contact_DAO_Contact();
                // when insert mode check contact id or external identifier
                if (!empty($params['contribution_contact_id']) || !empty($params['external_identifier'])) {
                    if (!empty($params['contribution_contact_id'])) {
                        $contactType->id = CRM_Utils_Array::value('contribution_contact_id', $params);
                    } elseif (!empty($params['external_identifier'])) {
                        $contactType->external_identifier = $params['external_identifier'];
                    }
                    if ($contactType->find(TRUE)) {
                        if ($params['contact_type'] != $contactType->contact_type) {
                            return civicrm_api3_create_error("Contact Type is wrong: {$contactType->contact_type}");
                        }
                    }
                } elseif (!empty($params['contribution_id']) || !empty($params['trxn_id']) || !empty($params['invoice_id'])) {
                    // when update mode check contribution id or trxn id or
                    // invoice id
                    $contactId = new CRM_Contribute_DAO_Contribution();
                    if (!empty($params['contribution_id'])) {
                        $contactId->id = $params['contribution_id'];
                    } elseif (!empty($params['trxn_id'])) {
                        $contactId->trxn_id = $params['trxn_id'];
                    } elseif (!empty($params['invoice_id'])) {
                        $contactId->invoice_id = $params['invoice_id'];
                    }
                    if ($contactId->find(TRUE)) {
                        $contactType->id = $contactId->contact_id;
                        if ($contactType->find(TRUE)) {
                            if ($params['contact_type'] != $contactType->contact_type) {
                                return civicrm_api3_create_error("Contact Type is wrong: {$contactType->contact_type}");
                            }
                        }
                    }
                } else {
                    if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
                        return civicrm_api3_create_error("Empty Contribution and Invoice and Transaction ID. Row was skipped.");
                    } else {
                        return civicrm_api3_create_error("Empty Contact and External ID. Row was skipped.");
                    }
                }
                break;
            case 'receive_date':
            case 'cancel_date':
            case 'receipt_date':
            case 'thankyou_date':
                if (!CRM_Utils_Rule::dateTime($value)) {
                    return civicrm_api3_create_error("{$key} not a valid date: {$value}");
                }
                break;
            case 'non_deductible_amount':
            case 'total_amount':
            case 'fee_amount':
            case 'net_amount':
                if (!CRM_Utils_Rule::money($value)) {
                    return civicrm_api3_create_error("{$key} not a valid amount: {$value}");
                }
                break;
            case 'currency':
                if (!CRM_Utils_Rule::currencyCode($value)) {
                    return civicrm_api3_create_error("currency not a valid code: {$value}");
                }
                break;
            case 'financial_type':
                require_once 'CRM/Contribute/PseudoConstant.php';
                $contriTypes = CRM_Contribute_PseudoConstant::financialType();
                foreach ($contriTypes as $val => $type) {
                    if (strtolower($value) == strtolower($type)) {
                        $values['financial_type_id'] = $val;
                        break;
                    }
                }
                if (empty($values['financial_type_id'])) {
                    return civicrm_api3_create_error("Financial Type is not valid: {$value}");
                }
                break;
            case 'payment_instrument':
                require_once 'CRM/Core/OptionGroup.php';
                $values['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', $value);
                if (empty($values['payment_instrument_id'])) {
                    return civicrm_api3_create_error("Payment Instrument is not valid: {$value}");
                }
                break;
            case 'contribution_status_id':
                require_once 'CRM/Core/OptionGroup.php';
                if (!($values['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', $value))) {
                    return civicrm_api3_create_error("Contribution Status is not valid: {$value}");
                }
                break;
            case 'soft_credit':
                // import contribution record according to select contact type
                // validate contact id and external identifier.
                $value[$key] = $mismatchContactType = $softCreditContactIds = '';
                if (isset($params[$key]) && is_array($params[$key])) {
                    foreach ($params[$key] as $softKey => $softParam) {
                        $contactId = CRM_Utils_Array::value('contact_id', $softParam);
                        $externalId = CRM_Utils_Array::value('external_identifier', $softParam);
                        $email = CRM_Utils_Array::value('email', $softParam);
                        if ($contactId || $externalId) {
                            require_once 'CRM/Contact/DAO/Contact.php';
                            $contact = new CRM_Contact_DAO_Contact();
                            $contact->id = $contactId;
                            $contact->external_identifier = $externalId;
                            $errorMsg = NULL;
                            if (!$contact->find(TRUE)) {
                                $field = $contactId ? ts('Contact ID') : ts('External ID');
                                $errorMsg = ts("Soft Credit %1 - %2 doesn't exist. Row was skipped.", array(1 => $field, 2 => $contactId ? $contactId : $externalId));
                            }
                            if ($errorMsg) {
                                return civicrm_api3_create_error($errorMsg, $value[$key]);
                            }
                            // finally get soft credit contact id.
                            $values[$key][$softKey] = $softParam;
                            $values[$key][$softKey]['contact_id'] = $contact->id;
                        } elseif ($email) {
                            if (!CRM_Utils_Rule::email($email)) {
                                return civicrm_api3_create_error("Invalid email address {$email} provided for Soft Credit. Row was skipped");
                            }
                            // get the contact id from duplicate contact rule, if more than one contact is returned
                            // we should return error, since current interface allows only one-one mapping
                            $emailParams = array('email' => $email, 'contact_type' => $params['contact_type']);
                            $checkDedupe = _civicrm_api3_deprecated_duplicate_formatted_contact($emailParams);
                            if (!$checkDedupe['is_error']) {
                                return civicrm_api3_create_error("Invalid email address(doesn't exist) {$email} for Soft Credit. Row was skipped");
                            } else {
                                $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
                                if (count($matchingContactIds) > 1) {
                                    return civicrm_api3_create_error("Invalid email address(duplicate) {$email} for Soft Credit. Row was skipped");
                                } elseif (count($matchingContactIds) == 1) {
                                    $contactId = $matchingContactIds[0];
                                    unset($softParam['email']);
                                    $values[$key][$softKey] = $softParam + array('contact_id' => $contactId);
                                }
                            }
                        }
                    }
                }
                break;
            case 'pledge_payment':
            case 'pledge_id':
                // giving respect to pledge_payment flag.
                if (empty($params['pledge_payment'])) {
                    continue;
                }
                // get total amount of from import fields
                $totalAmount = CRM_Utils_Array::value('total_amount', $params);
                $onDuplicate = CRM_Utils_Array::value('onDuplicate', $params);
                // we need to get contact id $contributionContactID to
                // retrieve pledge details as well as to validate pledge ID
                // first need to check for update mode
                if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && ($params['contribution_id'] || $params['trxn_id'] || $params['invoice_id'])) {
                    $contribution = new CRM_Contribute_DAO_Contribution();
                    if ($params['contribution_id']) {
                        $contribution->id = $params['contribution_id'];
                    } elseif ($params['trxn_id']) {
                        $contribution->trxn_id = $params['trxn_id'];
                    } elseif ($params['invoice_id']) {
                        $contribution->invoice_id = $params['invoice_id'];
                    }
                    if ($contribution->find(TRUE)) {
                        $contributionContactID = $contribution->contact_id;
                        if (!$totalAmount) {
                            $totalAmount = $contribution->total_amount;
                        }
                    } else {
                        return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                    }
                } else {
                    // first get the contact id for given contribution record.
                    if (!empty($params['contribution_contact_id'])) {
                        $contributionContactID = $params['contribution_contact_id'];
                    } elseif (!empty($params['external_identifier'])) {
                        require_once 'CRM/Contact/DAO/Contact.php';
                        $contact = new CRM_Contact_DAO_Contact();
                        $contact->external_identifier = $params['external_identifier'];
                        if ($contact->find(TRUE)) {
                            $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $contact->id;
                        } else {
                            return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                        }
                    } else {
                        // we need to get contribution contact using de dupe
                        $error = _civicrm_api3_deprecated_check_contact_dedupe($params);
                        if (isset($error['error_message']['params'][0])) {
                            $matchedIDs = explode(',', $error['error_message']['params'][0]);
                            // check if only one contact is found
                            if (count($matchedIDs) > 1) {
                                return civicrm_api3_create_error($error['error_message']['message'], 'pledge_payment');
                            } else {
                                $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $matchedIDs[0];
                            }
                        } else {
                            return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                        }
                    }
                }
                if (!empty($params['pledge_id'])) {
                    if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $params['pledge_id'], 'contact_id') != $contributionContactID) {
                        return civicrm_api3_create_error('Invalid Pledge ID provided. Contribution row was skipped.', 'pledge_payment');
                    }
                    $values['pledge_id'] = $params['pledge_id'];
                } else {
                    // check if there are any pledge related to this contact, with payments pending or in progress
                    require_once 'CRM/Pledge/BAO/Pledge.php';
                    $pledgeDetails = CRM_Pledge_BAO_Pledge::getContactPledges($contributionContactID);
                    if (empty($pledgeDetails)) {
                        return civicrm_api3_create_error('No open pledges found for this contact. Contribution row was skipped.', 'pledge_payment');
                    } elseif (count($pledgeDetails) > 1) {
                        return civicrm_api3_create_error('This contact has more than one open pledge. Unable to determine which pledge to apply the contribution to. Contribution row was skipped.', 'pledge_payment');
                    }
                    // this mean we have only one pending / in progress pledge
                    $values['pledge_id'] = $pledgeDetails[0];
                }
                // we need to check if oldest payment amount equal to contribution amount
                require_once 'CRM/Pledge/BAO/PledgePayment.php';
                $pledgePaymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($values['pledge_id']);
                if ($pledgePaymentDetails['amount'] == $totalAmount) {
                    $values['pledge_payment_id'] = $pledgePaymentDetails['id'];
                } else {
                    return civicrm_api3_create_error('Contribution and Pledge Payment amount mismatch for this record. Contribution row was skipped.', 'pledge_payment');
                }
                break;
            default:
                break;
        }
    }
    if (array_key_exists('note', $params)) {
        $values['note'] = $params['note'];
    }
    if ($create) {
        // CRM_Contribute_BAO_Contribution::add() handles contribution_source
        // So, if $values contains contribution_source, convert it to source
        $changes = array('contribution_source' => 'source');
        foreach ($changes as $orgVal => $changeVal) {
            if (isset($values[$orgVal])) {
                $values[$changeVal] = $values[$orgVal];
                unset($values[$orgVal]);
            }
        }
    }
    return NULL;
}
Exemplo n.º 18
0
 /**
  * Delete contribution of contact.
  *
  * CRM-12155
  *
  * @param int $contactId
  *   Contact id.
  *
  */
 public static function deleteContactContribution($contactId)
 {
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->contact_id = $contactId;
     $contribution->find();
     while ($contribution->fetch()) {
         self::deleteContribution($contribution->id);
     }
 }
Exemplo n.º 19
0
 /**
  * Checks to see if invoice_id already exists in db
  *
  * @param  int     $invoiceId   The ID to check
  *
  * @return bool                  True if ID exists, else false
  */
 function _checkDupe($invoiceId)
 {
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->invoice_id = $invoiceId;
     return $contribution->find();
 }
 /**
  * Checks to see if invoice_id already exists in db.
  *
  * @param int $invoiceId The ID to check.
  *
  * @param null $contributionID
  *   If a contribution exists pass in the contribution ID.
  *
  * @return bool True if ID exists, else false
  * True if ID exists, else false
  */
 protected function checkDupe($invoiceId, $contributionID = NULL)
 {
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->invoice_id = $invoiceId;
     $contribution->contribution_status_id = 1;
     if ($contributionID) {
         $contribution->whereAdd("id <> {$contributionID}");
     }
     return $contribution->find();
 }
 /**
  * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
  *
  * @param xml     $xml_response   response send by google in xml format
  * @param array   $privateData    contains the name value pair of <merchant-private-data>
  * @param int     $orderNo        <order-total> send by google
  * @param string  $root           root of xml-response
  *
  * @return array context of this call (test, module, payment processor id)
  * @static
  */
 function getContext($privateData, $orderNo, $root, $response, $serial)
 {
     $contributionID = CRM_Utils_Array::value('contributionID', $privateData);
     $contribution = new CRM_Contribute_DAO_Contribution();
     if ($root == 'new-order-notification') {
         $contribution->id = $contributionID;
     } else {
         $contribution->invoice_id = $orderNo;
     }
     if (!$contribution->find(TRUE)) {
         CRM_Core_Error::debug_log_message("getContext: Could not find contribution record with invoice id: {$orderNo}");
         $response->SendAck($serial);
     }
     $module = 'Contribute';
     if (stristr($contribution->source, ts('Online Contribution'))) {
         $module = 'Contribute';
     } elseif (stristr($contribution->source, ts('Online Event Registration'))) {
         $module = 'Event';
     }
     $isTest = $contribution->is_test;
     $ids = $input = $objects = array();
     $objects['contribution'] =& $contribution;
     $ids['contributionRecur'] = self::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
     $input['component'] = strtolower($module);
     if (!$ids['contributionRecur'] && $contribution->contribution_status_id == 1) {
         CRM_Core_Error::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
         // There is no point in going further. Return ack so we don't receive the same ipn.
         $response->SendAck($serial);
     }
     if ($input['component'] == 'event') {
         if ($root == 'new-order-notification') {
             $ids['event'] = $privateData['eventID'];
         } else {
             list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contribution->trxn_id);
         }
     }
     $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PaymentProcessor', 'Google_Checkout', 'id', 'payment_processor_type');
     $this->loadObjects($input, $ids, $objects, FALSE, $paymentProcessorID);
     if (!$ids['paymentProcessor']) {
         CRM_Core_Error::debug_log_message("Payment processor could not be retrieved.");
         // There is no point in going further. Return ack so we don't receive the same ipn.
         $response->SendAck($serial);
     }
     return array($isTest, $input['component'], $ids['paymentProcessor']);
 }
Exemplo n.º 22
0
 /**
  * Rule set for the rebooking forms
  */
 static function rebookRules($values)
 {
     $errors = array();
     $contactId = trim($values['contactId']);
     $contributionIds = $values['contributionIds'];
     if (!preg_match('/^\\d+$/', $contactId)) {
         // check if is int
         $errors['contactId'] = ts('Please enter a CiviCRM ID!', array('domain' => 'de.systopia.donrec'));
         return empty($errors) ? TRUE : $errors;
     }
     // validation for contact
     $contact = new CRM_Contact_BAO_Contact();
     $contact->id = (int) $contactId;
     if (!$contact->find(true)) {
         $errors['contactId'] = ts('A contact with CiviCRM ID %1 doesn\'t exist!', array(1 => $contactId, 'domain' => 'de.systopia.donrec'));
         return empty($errors) ? TRUE : $errors;
     }
     // Der Kontakt, auf den umgebucht wird, darf kein Haushalt sein.
     $contactType = $contact->getContactType($contactId);
     if (!empty($contactType) && $contactType == 'Household') {
         $errors['contactId'] = ts('The target contact can not be a household!', array('domain' => 'de.systopia.donrec'));
         return empty($errors) ? TRUE : $errors;
     }
     // Der Kontakt, auf den umgebucht wird, darf nicht im Papierkorb sein.
     $contactIsDeleted = $contact->is_deleted;
     if ($contactIsDeleted == 1) {
         $errors['contactId'] = ts('The target contact can not be in trash!', array('domain' => 'de.systopia.donrec'));
         return empty($errors) ? TRUE : $errors;
     }
     // Check contributions
     $completed = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
     $arr = explode(",", $contributionIds);
     foreach ($arr as $contributionId) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->id = $contributionId;
         if ($contribution->find(true)) {
             // only 'completed' contributions can be rebooked
             if ($contribution->contribution_status_id != $completed) {
                 $errors['contactId'] = ts('The contribution with ID %1 is not completed!', array(1 => $contributionId, 'domain' => 'de.systopia.donrec'));
                 return empty($errors) ? TRUE : $errors;
             }
             // receipted contributions can NOT be rebooked
             if (CRM_Donrec_Logic_Receipt::isContributionLocked($contributionId)) {
                 $errors['contactId'] = ts('The contribution with ID %1 cannot be rebooked, because it has a valid contribution receipt.', array(1 => $contributionId, 'domain' => 'de.systopia.donrec'));
                 return empty($errors) ? TRUE : $errors;
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
Exemplo n.º 23
0
 /**
  * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
  *
  * @param xml     $xml_response   response send by google in xml format
  * @param array   $privateData    contains the name value pair of <merchant-private-data>
  * @param int     $orderNo        <order-total> send by google
  * @param string  $root           root of xml-response
  *
  * @return array context of this call (test, module, payment processor id)
  * @static
  */
 static function getContext($xml_response, $privateData, $orderNo, $root)
 {
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $isTest = NULL;
     $module = NULL;
     if ($root == 'new-order-notification') {
         $contributionID = $privateData['contributionID'];
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->id = $contributionID;
         if (!$contribution->find(TRUE)) {
             CRM_Core_Error::debug_log_message("Could not find contribution record: {$contributionID}");
             echo "Failure: Could not find contribution record for {$contributionID}<p>";
             exit;
         }
         if (stristr($contribution->source, ts('Online Contribution'))) {
             $module = 'Contribute';
         } elseif (stristr($contribution->source, ts('Online Event Registration'))) {
             $module = 'Event';
         }
         $isTest = $contribution->is_test;
     } else {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->invoice_id = $orderNo;
         if (!$contribution->find(TRUE)) {
             CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: {$orderNo}");
             echo "Failure: Could not find contribution record with invoice id: {$orderNo} <p>";
             exit;
         }
         if (stristr($contribution->source, ts('Online Contribution'))) {
             $module = 'Contribute';
         } elseif (stristr($contribution->source, ts('Online Event Registration'))) {
             $module = 'Event';
         }
         $isTest = $contribution->is_test;
     }
     if ($contribution->contribution_status_id == 1) {
         //contribution already handled.
         exit;
     }
     if ($module == 'Contribute') {
         if (!$contribution->contribution_page_id) {
             CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: {$contributionID}");
             echo "Failure: Could not find contribution page for contribution record: {$contributionID}<p>";
             exit;
         }
         // get the payment processor id from contribution page
         $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $contribution->contribution_page_id, 'payment_processor_id');
     } else {
         if ($root == 'new-order-notification') {
             $eventID = $privateData['eventID'];
         } else {
             list($eventID, $participantID) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contribution->trxn_id);
         }
         if (!$eventID) {
             CRM_Core_Error::debug_log_message("Could not find event ID");
             echo "Failure: Could not find eventID<p>";
             exit;
         }
         // we are in event mode
         // make sure event exists and is valid
         require_once 'CRM/Event/DAO/Event.php';
         $event = new CRM_Event_DAO_Event();
         $event->id = $eventID;
         if (!$event->find(TRUE)) {
             CRM_Core_Error::debug_log_message("Could not find event: {$eventID}");
             echo "Failure: Could not find event: {$eventID}<p>";
             exit;
         }
         // get the payment processor id from contribution page
         $paymentProcessorID = $event->payment_processor_id;
     }
     if (!$paymentProcessorID) {
         CRM_Core_Error::debug_log_message("Could not find payment processor for contribution record: {$contributionID}");
         echo "Failure: Could not find payment processor for contribution record: {$contributionID}<p>";
         exit;
     }
     return array($isTest, $module, $paymentProcessorID);
 }
 /**
  * The function returns whether this transaction has already been handled.
  *
  * @param string @component
  *   event/contribute
  * @param array $post_data_exp
  *   Contains the name-value pairs of transaction response data.
  * @param string $dt_trxn_id
  *   Transaction ID from DT response.
  *
  * @return boolean
  *   Has this transaction been handled?  TRUE/FALSE.
  * @static
  */
 static function getContext($component, $post_data_exp, $dt_trxn_id)
 {
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $contributionID = $post_data_exp['contributionID'];
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->id = $contributionID;
     /*
      * @TODO For recurring?
      * if(new contrib)
      * $contribution->invoice_id = $dt_trxn_id;
      */
     if (!$contribution->find(TRUE)) {
         CRM_Core_Error::debug_log_message("Could not find contribution record: {$contributionID}");
         print "Failure: Could not find contribution record for {$contributionID}<p>";
         exit;
     }
     $duplicate_transaction = FALSE;
     if ($contribution->contribution_status_id == 1) {
         //  Contribution already handled.
         $duplicate_transaction = TRUE;
     }
     if ($component == 'contribute') {
         if (empty($contribution->contribution_page_id)) {
             CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: {$contributionID}");
             print "Failure: Could not find contribution page for contribution record: {$contributionID}<p>";
             exit;
         }
     } else {
         if (!empty($post_data_exp['eventID'])) {
             require_once 'CRM/Event/DAO/Event.php';
             $eventID = $post_data_exp['eventID'];
             // Make sure event exists and is valid.
             $event = new CRM_Event_DAO_Event();
             $event->id = $eventID;
             if (!$event->find(TRUE)) {
                 CRM_Core_Error::debug_log_message("Could not find event: {$eventID}");
                 print "Failure: Could not find event: {$eventID}<p>";
                 exit;
             }
         } else {
             CRM_Core_Error::debug_log_message("Could not find event ID");
             print "Failure: Could not find eventID<p>";
             exit;
         }
     }
     return $duplicate_transaction;
 }
Exemplo n.º 25
0
 /**
  * This function sets the default values for the form in edit/view mode
  * the default values are retrieved from the database
  *
  *
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 public static function setDefaultValues(&$form)
 {
     $defaults = array();
     if ($form->_eventId) {
         //get receipt text and financial type
         $returnProperities = array('confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date');
         $details = array();
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
         if (!empty($details[$form->_eventId]['financial_type_id'])) {
             $defaults[$form->_pId]['financial_type_id'] = $details[$form->_eventId]['financial_type_id'];
         }
     }
     if ($form->_pId) {
         $ids = array();
         $params = array('id' => $form->_pId);
         CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
         if ($form->_action == CRM_Core_Action::UPDATE) {
             $discounts = array();
             if (!empty($form->_values['discount'])) {
                 foreach ($form->_values['discount'] as $key => $value) {
                     $value = current($value);
                     $discounts[$key] = $value['name'];
                 }
             }
             if ($form->_discountId && !empty($discounts[$defaults[$form->_pId]['discount_id']])) {
                 $form->assign('discount', $discounts[$defaults[$form->_pId]['discount_id']]);
             }
             $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
             $form->assign('fee_level', CRM_Utils_Array::value('fee_level', $defaults[$form->_pId]));
         }
         $defaults[$form->_pId]['send_receipt'] = 0;
     } else {
         $defaults[$form->_pId]['send_receipt'] = strtotime(CRM_Utils_Array::value('start_date', $details[$form->_eventId])) >= time() ? 1 : 0;
         if ($form->_eventId && !empty($details[$form->_eventId]['confirm_email_text'])) {
             //set receipt text
             $defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
         }
         list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults();
     }
     //CRM-11601 we should keep the record contribution
     //true by default while adding participant
     if ($form->_action == CRM_Core_Action::ADD && !$form->_mode && $form->_isPaidEvent) {
         $defaults[$form->_pId]['record_contribution'] = 1;
     }
     //CRM-13420
     if (empty($defaults['payment_instrument_id'])) {
         $defaults[$form->_pId]['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
     }
     if ($form->_mode) {
         $config = CRM_Core_Config::singleton();
         // set default country from config if no country set
         if (empty($defaults[$form->_pId]["billing_country_id-{$form->_bltID}"])) {
             $defaults[$form->_pId]["billing_country_id-{$form->_bltID}"] = $config->defaultContactCountry;
         }
         if (empty($defaults["billing_state_province_id-{$form->_bltID}"])) {
             $defaults[$form->_pId]["billing_state_province_id-{$form->_bltID}"] = $config->defaultContactStateProvince;
         }
         $billingDefaults = $form->getProfileDefaults('Billing', $form->_contactId);
         $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $billingDefaults);
         //             // hack to simplify credit card entry for testing
         //             $defaults[$form->_pId]['credit_card_type']     = 'Visa';
         //             $defaults[$form->_pId]['credit_card_number']   = '4807731747657838';
         //             $defaults[$form->_pId]['cvv2']                 = '000';
         //             $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
     }
     // if user has selected discount use that to set default
     if (isset($form->_discountId)) {
         $defaults[$form->_pId]['discount_id'] = $form->_discountId;
         //hack to set defaults for already selected discount value
         if ($form->_action == CRM_Core_Action::UPDATE && !$form->_originalDiscountId) {
             $form->_originalDiscountId = $defaults[$form->_pId]['discount_id'];
             if ($form->_originalDiscountId) {
                 $defaults[$form->_pId]['discount_id'] = $form->_originalDiscountId;
             }
         }
         $discountId = $form->_discountId;
     } else {
         $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
     }
     if ($discountId) {
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
     } else {
         $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $form->_eventId);
     }
     if ($form->_action == CRM_Core_Action::ADD && $form->_eventId && $discountId) {
         // this case is for add mode, where we show discount automatically
         $defaults[$form->_pId]['discount_id'] = $discountId;
     }
     if ($priceSetId) {
         // get price set default values, CRM-4090
         if (in_array(get_class($form), array('CRM_Event_Form_Participant', 'CRM_Event_Form_Registration_Register', 'CRM_Event_Form_Registration_AdditionalParticipant'))) {
             $priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
             if (!empty($priceSetValues)) {
                 $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $priceSetValues);
             }
         }
         if ($form->_action == CRM_Core_Action::ADD && !empty($form->_priceSet['fields'])) {
             foreach ($form->_priceSet['fields'] as $key => $val) {
                 foreach ($val['options'] as $keys => $values) {
                     if ($values['is_default']) {
                         if (get_class($form) != 'CRM_Event_Form_Participant' && !empty($values['is_full'])) {
                             continue;
                         }
                         if ($val['html_type'] == 'CheckBox') {
                             $defaults[$form->_pId]["price_{$key}"][$keys] = 1;
                         } else {
                             $defaults[$form->_pId]["price_{$key}"] = $keys;
                         }
                     }
                 }
             }
         }
         $form->assign('totalAmount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
         if ($form->_action == CRM_Core_Action::UPDATE) {
             $fee_level = $defaults[$form->_pId]['fee_level'];
             CRM_Event_BAO_Participant::fixEventLevel($fee_level);
             $form->assign('fee_level', $fee_level);
             $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
         }
     }
     //CRM-4453
     if (!empty($defaults[$form->_pId]['participant_fee_currency'])) {
         $form->assign('fee_currency', $defaults[$form->_pId]['participant_fee_currency']);
     }
     // CRM-4395
     if ($contriId = $form->get('onlinePendingContributionId')) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->id = $contriId;
         $contribution->find(TRUE);
         foreach (array('financial_type_id', 'payment_instrument_id', 'contribution_status_id', 'receive_date', 'total_amount') as $f) {
             if ($f == 'receive_date') {
                 list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->{$f});
             } else {
                 $defaults[$form->_pId][$f] = $contribution->{$f};
             }
         }
     }
     return $defaults[$form->_pId];
 }
 static function civicrm_direct_debit_civicrm_pageRun_produceSetUpLetter($mandate_id, $contact_id, $default_template, $return_content = false, $contribution_id, $first_collectionDate)
 {
     //$sql = "SELECT * FROM civicrm_value_bank_details WHERE id = %1";
     //$params  = array( 1 => array( $entity_id , 'Integer' ));
     //$dao = CRM_Core_DAO::executeQuery( $sql, $params );
     //$dao->fetch( )
     //$contribution_id = $dao->entity_id;
     ## Get the contribution details
     //require_once 'CRM/Contribute/DAO/Contribution.php';
     //$contribution_dao =& new CRM_Contribute_DAO_Contribution( );
     //$contribution_dao->get($contribution_id);
     //$contribution_date = $contribution_dao->receive_date;
     //$contribution_date = strtotime(date("d/m/Y", strtotime($contribution_date)));
     //$contribution_date = date('mdY', $contribution_date);
     //require_once 'CRM/Core/DAO';
     $fiscal_template = $default_template;
     $date = date('d/m/y');
     //$amount = $dao->amount;
     require_once 'CRM/Contribute/DAO/Contribution.php';
     $contrib_dao = new CRM_Contribute_DAO_Contribution();
     $contrib_dao->id = $contribution_id;
     $contrib_dao->find(true);
     require_once "api/v2/Contact.php";
     $contactParams = array('id' => $contact_id);
     $contact =& civicrm_contact_get($contactParams);
     require_once "CRM/Mailing/BAO/Mailing.php";
     $mailing = new CRM_Mailing_BAO_Mailing();
     $mailing->body_text = $fiscal_template;
     $mailing->body_html = $fiscal_template;
     $tokens = $mailing->getTokens();
     //print_r ($tokens);exit;
     require_once "CRM/Utils/Token.php";
     if ($contact_id) {
         $fiscal_template = CRM_Utils_Token::replaceContactTokens($fiscal_template, $contact, false, $tokens['html']);
     }
     //$address = preg_replace("/\n/","<br>",$dao->address);
     $mandate_sql = "SELECT * FROM civicrm_value_bank_details bd WHERE bd.id = %1";
     $mandate_params = array(1 => array($mandate_id, 'Integer'));
     $mandate_dao = CRM_Core_DAO::executeQuery($mandate_sql, $mandate_params);
     $mandate_dao->fetch();
     $day_of_collection = $_ENV['collectionDayArray'][$mandate_dao->collection_day] . " of every month";
     $fiscal_template = str_replace('{invoice_number}', $receipt_number, $fiscal_template);
     $fiscal_template = str_replace('{invoice_date}', $date, $fiscal_template);
     $fiscal_template = str_replace('{amount}', $contrib_dao->total_amount, $fiscal_template);
     $fiscal_template = str_replace('{first_collection_date}', $first_collectionDate, $fiscal_template);
     $fiscal_template = str_replace('{day_of_collection}', $day_of_collection, $fiscal_template);
     $fiscal_template = str_replace('{account_name}', $mandate_dao->account_name, $fiscal_template);
     $fiscal_template = str_replace('{account_number}', $mandate_dao->account_number, $fiscal_template);
     $fiscal_template = str_replace('{sort_code}', $mandate_dao->sort_code, $fiscal_template);
     $final_template = $fiscal_template;
     //$final_template .= "<div STYLE='page-break-after: always'></div>";
     //echo $final_template;exit;
     $file_name = "SetUp_Letter_" . $contact_id . ".pdf";
     $fileContent = self::civicrm_direct_debit_civicrm_pageRun_html2pdf($final_template, $file_name, "external");
     require_once "CRM/Core/Config.php";
     $config =& CRM_Core_Config::singleton();
     $csv_path = $config->customFileUploadDir;
     //$csv_path = "sites/default/files/civicrm/custom";
     $filePathName = "{$csv_path}/{$file_name}";
     $handle = fopen($filePathName, 'w');
     file_put_contents($filePathName, $fileContent);
     fclose($handle);
     return array('content' => $final_template, 'file_name' => $file_name);
     /*if ($return_content)
           return $final_template;  
       else
           return $file_name;*/
 }
Exemplo n.º 27
0
 /**
  * Updates contacts affected by the option value passed.
  *
  * @param int $optionValueId
  *   The option value id.
  * @param int $action
  *   The action describing whether prefix/suffix was UPDATED or DELETED.
  *
  * @return bool
  */
 public static function updateRecords(&$optionValueId, $action)
 {
     //finding group name
     $optionValue = new CRM_Core_DAO_OptionValue();
     $optionValue->id = $optionValueId;
     $optionValue->find(TRUE);
     $optionGroup = new CRM_Core_DAO_OptionGroup();
     $optionGroup->id = $optionValue->option_group_id;
     $optionGroup->find(TRUE);
     // group name
     $gName = $optionGroup->name;
     // value
     $value = $optionValue->value;
     // get the proper group name & affected field name
     // todo: this may no longer be needed for individuals - check inputs
     $individuals = array('gender' => 'gender_id', 'individual_prefix' => 'prefix_id', 'individual_suffix' => 'suffix_id', 'communication_style' => 'communication_style_id');
     $contributions = array('payment_instrument' => 'payment_instrument_id');
     $activities = array('activity_type' => 'activity_type_id');
     $participant = array('participant_role' => 'role_id');
     $eventType = array('event_type' => 'event_type_id');
     $aclRole = array('acl_role' => 'acl_role_id');
     $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
     $fieldName = '';
     foreach ($all as $name => $id) {
         if ($gName == $name) {
             $fieldName = $id;
         }
     }
     if ($fieldName == '') {
         return TRUE;
     }
     if (array_key_exists($gName, $individuals)) {
         $contactDAO = new CRM_Contact_DAO_Contact();
         $contactDAO->{$fieldName} = $value;
         $contactDAO->find();
         while ($contactDAO->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contact = new CRM_Contact_DAO_Contact();
                 $contact->id = $contactDAO->id;
                 $contact->find(TRUE);
                 // make sure dates doesn't get reset
                 $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
                 $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
                 $contact->{$fieldName} = 'NULL';
                 $contact->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $contributions)) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->{$fieldName} = $value;
         $contribution->find();
         while ($contribution->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contribution->{$fieldName} = 'NULL';
                 $contribution->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $activities)) {
         $activity = new CRM_Activity_DAO_Activity();
         $activity->{$fieldName} = $value;
         $activity->find();
         while ($activity->fetch()) {
             $activity->delete();
         }
         return TRUE;
     }
     //delete participant role, type and event type option value
     if (array_key_exists($gName, $participant)) {
         $participantValue = new CRM_Event_DAO_Participant();
         $participantValue->{$fieldName} = $value;
         if ($participantValue->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete event type option value
     if (array_key_exists($gName, $eventType)) {
         $event = new CRM_Event_DAO_Event();
         $event->{$fieldName} = $value;
         if ($event->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete acl_role option value
     if (array_key_exists($gName, $aclRole)) {
         $entityRole = new CRM_ACL_DAO_EntityRole();
         $entityRole->{$fieldName} = $value;
         $aclDAO = new CRM_ACL_DAO_ACL();
         $aclDAO->entity_id = $value;
         if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
 }
Exemplo n.º 28
0
 /**
  * @param $paymentProcessor
  * @param $paymentMode
  * @param $start
  * @param $end
  */
 public static function paypal($paymentProcessor, $paymentMode, $start, $end)
 {
     $url = "{$paymentProcessor['url_api']}nvp";
     $keyArgs = array('user' => $paymentProcessor['user_name'], 'pwd' => $paymentProcessor['password'], 'signature' => $paymentProcessor['signature'], 'version' => 3.0);
     $args = $keyArgs;
     $args += array('method' => 'TransactionSearch', 'startdate' => $start, 'enddate' => $end);
     require_once 'CRM/Core/Payment/PayPalImpl.php';
     // as invokeAPI fetch only last 100 transactions.
     // we should require recursive calls to process more than 100.
     // first fetch transactions w/ give date intervals.
     // if we get error code w/ result, which means we do have more than 100
     // manipulate date interval accordingly and fetch again.
     do {
         $result = CRM_Core_Payment_PayPalImpl::invokeAPI($args, $url);
         require_once "CRM/Contribute/BAO/Contribution/Utils.php";
         $keyArgs['method'] = 'GetTransactionDetails';
         foreach ($result as $name => $value) {
             if (substr($name, 0, 15) == 'l_transactionid') {
                 // We don't/can't process subscription notifications, which appear
                 // to be identified by transaction ids beginning with S-
                 if (substr($value, 0, 2) == 'S-') {
                     continue;
                 }
                 // Before we bother making a remote API call to PayPal to lookup
                 // details about a transaction, let's make sure that it doesn't
                 // already exist in the database.
                 require_once 'CRM/Contribute/DAO/Contribution.php';
                 $dao = new CRM_Contribute_DAO_Contribution();
                 $dao->trxn_id = $value;
                 if ($dao->find(TRUE)) {
                     preg_match('/(\\d+)$/', $name, $matches);
                     $seq = $matches[1];
                     $email = $result["l_email{$seq}"];
                     $amt = $result["l_amt{$seq}"];
                     CRM_Core_Error::debug_log_message("Skipped (already recorded) - {$email}, {$amt}, {$value} ..<p>", TRUE);
                     continue;
                 }
                 $keyArgs['transactionid'] = $value;
                 $trxnDetails = CRM_Core_Payment_PayPalImpl::invokeAPI($keyArgs, $url);
                 if (is_a($trxnDetails, 'CRM_Core_Error')) {
                     echo "PAYPAL ERROR: Skipping transaction id: {$value}<p>";
                     continue;
                 }
                 // only process completed payments
                 if (strtolower($trxnDetails['paymentstatus']) != 'completed') {
                     continue;
                 }
                 // only process receipts, not payments
                 if (strtolower($trxnDetails['transactiontype']) == 'sendmoney') {
                     continue;
                 }
                 $params = self::formatAPIParams($trxnDetails, self::$_paypalParamsMapper, 'paypal');
                 if ($paymentMode == 'test') {
                     $params['transaction']['is_test'] = 1;
                 } else {
                     $params['transaction']['is_test'] = 0;
                 }
                 if (self::processAPIContribution($params)) {
                     CRM_Core_Error::debug_log_message("Processed - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
                 } else {
                     CRM_Core_Error::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
                 }
             }
         }
         if ($result['l_errorcode0'] == '11002') {
             $end = $result['l_timestamp99'];
             $end_time = strtotime("{$end}", time());
             $end_date = date('Y-m-d\\T00:00:00.00\\Z', $end_time);
             $args['enddate'] = $end_date;
         }
     } while ($result['l_errorcode0'] == '11002');
 }
Exemplo n.º 29
0
 function updateRecurLinkedPledge(&$contribution)
 {
     $returnProperties = array('id', 'pledge_id');
     $paymentDetails = $paymentIDs = array();
     if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id, $paymentDetails, $returnProperties)) {
         foreach ($paymentDetails as $key => $value) {
             $paymentIDs[] = $value['id'];
             $pledgeId = $value['pledge_id'];
         }
     } else {
         //payment is not already linked - if it is linked with a pledge we need to create a link.
         // return if it is not recurring contribution
         if (!$contribution->contribution_recur_id) {
             return;
         }
         $relatedContributions = new CRM_Contribute_DAO_Contribution();
         $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
         $relatedContributions->find();
         while ($relatedContributions->fetch()) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id, $paymentDetails, $returnProperties);
         }
         if (empty($paymentDetails)) {
             // payment is not linked with a pledge and neither are any other contributions on this
             return;
         }
         foreach ($paymentDetails as $key => $value) {
             $pledgeId = $value['pledge_id'];
         }
         // we have a pledge now we need to get the oldest unpaid payment
         $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
         if (empty($paymentDetails['id'])) {
             // we can assume this pledge is now completed
             // return now so we don't create a core error & roll back
             return;
         }
         $paymentDetails['contribution_id'] = $contribution->id;
         $paymentDetails['status_id'] = $contribution->contribution_status_id;
         $paymentDetails['actual_amount'] = $contribution->total_amount;
         // put contribution against it
         $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
         $paymentIDs[] = $payment->id;
     }
     // update pledge and corresponding payment statuses
     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id, NULL, $contribution->total_amount);
 }
Exemplo n.º 30
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return None
  */
 function postProcess()
 {
     // ensure the user has permission to issue the tax receipt.
     if (!CRM_Core_Permission::check('issue cdn tax receipts')) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page', array('domain' => 'org.civicrm.cdntaxreceipts')));
     }
     // load the contribution
     $contributionId = $this->get('contribution_id');
     $contactId = $this->get('contact_id');
     $contribution = new CRM_Contribute_DAO_Contribution();
     $contribution->id = $contributionId;
     if (!$contribution->find(TRUE)) {
         CRM_Core_Error::fatal("CDNTaxReceipts: Could not retrieve details for this contribution");
     }
     // issue tax receipt, or report error if ineligible
     if (!cdntaxreceipts_eligibleForReceipt($contribution->id)) {
         $statusMsg = ts('This contribution is not tax deductible and/or not completed. No receipt has been issued.', array('domain' => 'org.civicrm.cdntaxreceipts'));
         CRM_Core_Session::setStatus($statusMsg);
     } else {
         list($result, $method, $pdf) = cdntaxreceipts_issueTaxReceipt($contribution);
         if ($result == TRUE) {
             if ($method == 'email') {
                 $statusMsg = ts('Tax Receipt has been emailed to the contributor.', array('domain' => 'org.civicrm.cdntaxreceipts'));
             } else {
                 $statusMsg = ts('Tax Receipt has been generated for printing.', array('domain' => 'org.civicrm.cdntaxreceipts'));
             }
             CRM_Core_Session::setStatus($statusMsg);
         } else {
             $statusMsg = ts('Encountered an error. Tax receipt has not been issued.', array('domain' => 'org.civicrm.cdntaxreceipts'));
             CRM_Core_Session::setStatus($statusMsg);
             unset($pdf);
         }
     }
     // refresh the form, with file stored in session if we need it.
     $urlParams = array('reset=1', 'cid=' . $contactId, 'id=' . $contributionId);
     if ($method == 'print' && isset($pdf)) {
         $session = CRM_Core_Session::singleton();
         $session->set("pdf_file_" . $contributionId . "_" . $contactId, $pdf, 'cdntaxreceipts');
         $urlParams[] = 'file=1';
     }
     $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), implode('&', $urlParams));
     CRM_Utils_System::redirect($url);
 }