function savePdf($pdfContent, $obj, $contributionID, $pdf_delete_flag)
{
    // getting contribution contact id
    require_once 'CRM/Contribute/DAO/Contribution.php';
    $contribution = new CRM_Contribute_DAO_Contribution();
    $contribution->get($contributionID);
    $contactID = $contribution->contact_id;
    // Set the path to save the PDFs
    $pdf_path = PDF_FILE_PATH;
    ##############################################
    // save pdf file
    $fileName = "{$obj->invoice_no}.pdf";
    $filePathName = "{$pdf_path}/{$fileName}";
    $handle = fopen($filePathName, 'w');
    file_put_contents($filePathName, $pdfContent);
    fclose($handle);
    ## getting from email
    $query = "SELECT v.label FROM civicrm_option_group g, civicrm_option_value v WHERE g.name = 'from_email_address' AND g.id = v.option_group_id AND v.is_default=1";
    $dao = CRM_Core_DAO::executeQuery($query);
    if (!$dao->fetch()) {
        print "Not able to get FROM Email Address";
        exit;
    }
    $fromEmail = $dao->label;
    // send mail
    sendInvoiceMail($obj->email_invoice_address, $obj->attention_of, $fromEmail, $fileName, $filePathName, $obj, $contactID, $contribution);
    if ($pdf_delete_flag) {
        //delete pdf
        @unlink($filePathName);
    }
}
Ejemplo n.º 2
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;
 }
Ejemplo 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]);
         }
     }
 }
Ejemplo n.º 4
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);
     }
 }
Ejemplo n.º 5
0
 public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQueryEvent $e)
 {
     if ($e->mapping->getEntity() !== 'civicrm_contribution') {
         return;
     }
     $fields = CRM_Contribute_DAO_Contribution::fields();
     foreach ($this->getPassthruTokens() as $token) {
         $e->query->select("e." . $fields[$token]['name'] . " AS contrib_{$token}");
     }
     foreach ($this->getAliasTokens() as $alias => $orig) {
         $e->query->select("e." . $fields[$orig]['name'] . " AS contrib_{$alias}");
     }
 }
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
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);
 }
Ejemplo n.º 8
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_CONTRIBUTE_IMPORT_PARSER_VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     //for date-Formats
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'receive_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'cancel_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'receipt_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'thankyou_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
             }
         }
     }
     //date-Format part ends
     $formatted = array();
     if ($GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['indieFields'] == null) {
         require_once 'CRM/Contribute/DAO/Contribution.php';
         $tempIndieFields =& CRM_Contribute_DAO_Contribution::import();
         $GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['indieFields'] = $tempIndieFields;
     }
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $value = array($key => $field);
         _crm_add_formatted_contrib_param($value, $formatted);
     }
     if ($this->_contactIdIndex < 0) {
         if ($GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['cIndieFields'] == null) {
             require_once 'CRM/Contact/BAO/Contact.php';
             $cTempIndieFields = CRM_Contact_BAO_Contact::importableFields('Individual', null);
             $GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['cIndieFields'] = $cTempIndieFields;
         }
         foreach ($params as $key => $field) {
             if ($field == null || $field === '') {
                 continue;
             }
             if (is_array($field)) {
                 foreach ($field as $value) {
                     $break = false;
                     if (is_array($value)) {
                         foreach ($value as $name => $testForEmpty) {
                             if ($name !== 'phone_type' && ($testForEmpty === '' || $testForEmpty == null)) {
                                 $break = true;
                                 break;
                             }
                         }
                     } else {
                         $break = true;
                     }
                     if (!$break) {
                         _crm_add_formatted_param($value, $contactFormatted);
                     }
                 }
                 continue;
             }
             $value = array($key => $field);
             if (array_key_exists($key, $GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['cIndieFields'])) {
                 $value['contact_type'] = 'Individual';
             }
             _crm_add_formatted_param($value, $contactFormatted);
         }
         $contactFormatted['contact_type'] = 'Individual';
         $error = _crm_duplicate_formatted_contact($contactFormatted);
         $matchedIDs = explode(',', $error->_errors[0]['params'][0]);
         if (CRM_Contribute_Import_Parser_Contribution::isDuplicate($error)) {
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The contribution was not imported");
                 return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 $newContribution = crm_create_contribution_formatted($formatted, $onDuplicate);
                 if (is_a($newContribution, CRM_Core_Error)) {
                     array_unshift($values, $newContribution->_errors[0]['message']);
                     return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
                 }
                 $this->_newContributions[] = $newContribution->id;
                 return CRM_CONTRIBUTE_IMPORT_PARSER_VALID;
             }
         } else {
             require_once 'CRM/Core/DAO/DupeMatch.php';
             $dao =& new CRM_Core_DAO_DupeMatch();
             $dao->find(true);
             $fieldsArray = explode('AND', $dao->rule);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
         }
     } else {
         $newContribution = crm_create_contribution_formatted($formatted, $onDuplicate);
         if (is_a($newContribution, CRM_Core_Error)) {
             array_unshift($values, $newContribution->_errors[0]['message']);
             return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
         }
         $this->_newContributions[] = $newContribution->id;
         return CRM_CONTRIBUTE_IMPORT_PARSER_VALID;
     }
 }
Ejemplo n.º 9
0
 /**
  * Check if there is a contribution with the params passed in.
  * Used for trxn_id,invoice_id and contribution_id
  *
  * @param array  $params (reference ) an assoc array of name/value pairs
  *
  * @return array contribution id if success else NULL
  * @access public
  * static
  */
 static function checkDuplicateIds($params)
 {
     $dao = new CRM_Contribute_DAO_Contribution();
     $clause = array();
     $input = array();
     foreach ($params as $k => $v) {
         if ($v) {
             $clause[] = "{$k} = '{$v}'";
         }
     }
     $clause = implode(' AND ', $clause);
     $query = "SELECT id FROM civicrm_contribution WHERE {$clause}";
     $dao =& CRM_Core_DAO::executeQuery($query, $input);
     while ($dao->fetch()) {
         $result = $dao->id;
         return $result;
     }
     return NULL;
 }
Ejemplo n.º 10
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;
 }
Ejemplo n.º 11
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']);
         }
     }
 }
Ejemplo n.º 12
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;
 }
Ejemplo n.º 13
0
/**
 * This function adds the contribution variable in $values to the
 * parameter list $params.  For most cases, $values should have length 1.
 *
 * @param array  $values    The variable(s) to be added
 * @param array  $params    The structured parameter list
 * 
 * @return bool|CRM_Utils_Error
 * @access public
 */
function _crm_add_formatted_contrib_param(&$values, &$params)
{
    /* Cache the various object fields */
    static $fields = null;
    if ($fields == null) {
        $fields = array();
    }
    //print_r($values);
    //print_r($params);
    if (isset($values['contribution_type'])) {
        $params['contribution_type'] = $values['contribution_type'];
        return true;
    }
    if (isset($values['payment_instrument'])) {
        $params['payment_instrument'] = $values['payment_instrument'];
        return true;
    }
    /* Check for custom field values */
    if ($fields['custom'] == null) {
        $fields['custom'] =& CRM_Core_BAO_CustomField::getFields('Contribution');
    }
    foreach ($values as $key => $value) {
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            /* check if it's a valid custom field id */
            if (!array_key_exists($customFieldID, $fields['custom'])) {
                return _crm_error('Invalid custom field ID');
            }
            if (!isset($params['custom'])) {
                $params['custom'] = array();
            }
            // fixed for Import
            $newMulValues = array();
            if ($fields['custom'][$customFieldID][3] == 'CheckBox' || $fields['custom'][$customFieldID][3] == 'Multi-Select') {
                $value = str_replace("|", ",", $value);
                $mulValues = explode(',', $value);
                $custuomOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                foreach ($mulValues as $v1) {
                    foreach ($custuomOption as $v2) {
                        if (strtolower($v2['label']) == strtolower(trim($v1))) {
                            $newMulValues[] = $v2['value'];
                        }
                    }
                }
                $value = implode(CRM_CORE_BAO_CUSTOMOPTION_VALUE_SEPERATOR, $newMulValues);
            } else {
                if ($fields['custom'][$customFieldID][3] == 'Select' || $fields['custom'][$customFieldID][3] == 'Radio') {
                    $custuomOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                    foreach ($custuomOption as $v2) {
                        if (strtolower($v2['label']) == strtolower(trim($value))) {
                            $value = $v2['value'];
                            break;
                        }
                    }
                }
            }
            $customBlock = count($params['custom']) + 1;
            $params['custom'][$customBlock] = array('custom_field_id' => $customFieldID, 'value' => $value, 'type' => $fields['custom'][$customFieldID][2], 'name' => $fields['custom'][$customFieldID][0]);
        }
    }
    /* Finally, check for contribution fields */
    if (!isset($fields['Contribution'])) {
        $fields['Contribution'] =& CRM_Contribute_DAO_Contribution::fields();
    }
    _crm_store_values($fields['Contribution'], $values, $params);
}
Ejemplo n.º 14
0
 /**
  * Function to get list of contribution fields for profile
  * For now we only allow custom contribution fields to be in
  * profile
  *
  * @return return the list of contribution fields
  * @static
  * @access public
  */
 function getContributionFields()
 {
     $contributionFields =& CRM_Contribute_DAO_Contribution::export();
     foreach ($contributionFields as $key => $var) {
         if ($key == 'contact_id') {
             continue;
         }
         $fields[$key] = $var;
     }
     // $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
     $fields = CRM_Core_BAO_CustomField::getFieldsForImport('Contribution');
     return $fields;
 }
 /**
  * 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;
 }
 /**
  * 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.
 }
Ejemplo n.º 17
0
 /**
  * Handle the values in import mode.
  *
  * @param int $onDuplicate
  *   The code for what action to take on duplicates.
  * @param array $values
  *   The array of values belonging to this line.
  *
  * @return bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('version' => 3);
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     //for date-Formats
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution';
     $customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
     //CRM-10994
     if (isset($params['total_amount']) && $params['total_amount'] == 0) {
         $params['total_amount'] = '0.00';
     }
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'receive_date':
                 case 'cancel_date':
                 case 'receipt_date':
                 case 'thankyou_date':
                     $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType);
                     break;
                 case 'pledge_payment':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $tempIndieFields = CRM_Contribute_DAO_Contribution::import();
         $indieFields = $tempIndieFields;
     }
     $paramValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $paramValues[$key] = $field;
     }
     //import contribution record according to select contact type
     if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP && (!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && (!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (!empty($params['soft_credit'])) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (!empty($paramValues['pledge_payment'])) {
         $paramValues['contact_type'] = $this->_contactType;
     }
     //need to pass $onDuplicate to check import mode.
     if (!empty($paramValues['pledge_payment'])) {
         $paramValues['onDuplicate'] = $onDuplicate;
     }
     require_once 'CRM/Utils/DeprecatedUtils.php';
     $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR;
         } elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') {
             return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR;
         }
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Contribution');
     } else {
         //fix for CRM-2219 - Update Contribution
         // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
         if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) {
             $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues));
             $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds);
             if ($ids['contribution']) {
                 $formatted['id'] = $ids['contribution'];
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatted['id'], 'Contribution');
                 //process note
                 if (!empty($paramValues['note'])) {
                     $noteID = array();
                     $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
                     $daoNote = new CRM_Core_BAO_Note();
                     $daoNote->entity_table = 'civicrm_contribution';
                     $daoNote->entity_id = $ids['contribution'];
                     if ($daoNote->find(TRUE)) {
                         $noteID['id'] = $daoNote->id;
                     }
                     $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID);
                     CRM_Core_BAO_Note::add($noteParams, $noteID);
                     unset($formatted['note']);
                 }
                 //need to check existing soft credit contribution, CRM-3968
                 if (!empty($formatted['soft_credit'])) {
                     $dupeSoftCredit = array('contact_id' => $formatted['soft_credit'], 'contribution_id' => $ids['contribution']);
                     //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null
                     $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']);
                     if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) {
                         foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) {
                             if (!empty($existingSoftCreditValues['soft_credit_id'])) {
                                 $deleteParams = array('id' => $existingSoftCreditValues['soft_credit_id'], 'pcp_id' => NULL);
                                 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
                             }
                         }
                     }
                 }
                 $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids);
                 $this->_newContributions[] = $newContribution->id;
                 //return soft valid since we need to show how soft credits were added
                 if (!empty($formatted['soft_credit'])) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Import_Parser::VALID;
             } else {
                 $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID');
                 foreach ($dupeIds as $k => $v) {
                     if ($v) {
                         $errorMsg[] = "{$labels[$k]} {$v}";
                     }
                 }
                 $errorMsg = implode(' AND ', $errorMsg);
                 array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         // set the contact type if its not set
         if (!isset($paramValues['contact_type'])) {
             $paramValues['contact_type'] = $this->_contactType;
         }
         $paramValues['version'] = 3;
         //retrieve contact id using contact dedupe rule
         require_once 'CRM/Utils/DeprecatedUtils.php';
         $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported');
                 return CRM_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 $newContribution = civicrm_api('contribution', 'create', $formatted);
                 if (civicrm_error($newContribution)) {
                     if (is_array($newContribution['error_message'])) {
                         array_unshift($values, $newContribution['error_message']['message']);
                         if ($newContribution['error_message']['params'][0]) {
                             return CRM_Import_Parser::DUPLICATE;
                         }
                     } else {
                         array_unshift($values, $newContribution['error_message']);
                         return CRM_Import_Parser::ERROR;
                     }
                 }
                 $this->_newContributions[] = $newContribution['id'];
                 $formatted['contribution_id'] = $newContribution['id'];
                 //return soft valid since we need to show how soft credits were added
                 if (!empty($formatted['soft_credit'])) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = NULL;
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($paramValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $paramValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newContribution = civicrm_api('contribution', 'create', $formatted);
         if (civicrm_error($newContribution)) {
             if (is_array($newContribution['error_message'])) {
                 array_unshift($values, $newContribution['error_message']['message']);
                 if ($newContribution['error_message']['params'][0]) {
                     return CRM_Import_Parser::DUPLICATE;
                 }
             } else {
                 array_unshift($values, $newContribution['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $this->_newContributions[] = $newContribution['id'];
         $formatted['contribution_id'] = $newContribution['id'];
         //return soft valid since we need to show how soft credits were added
         if (!empty($formatted['soft_credit'])) {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT;
         }
         // process pledge payment assoc w/ the contribution
         return self::processPledgePayments($formatted);
         return CRM_Import_Parser::VALID;
     }
 }
Ejemplo 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);
     }
 }
Ejemplo 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']);
 }
Ejemplo n.º 22
0
 /**
  * returns the list of fields that can be exported
  *
  * @access public
  * return array
  */
 function &export($prefix = false)
 {
     if (!self::$_export) {
         self::$_export = array();
         $fields =& self::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     self::$_export['contribution'] =& $fields[$name];
                 } else {
                     self::$_export[$name] =& $fields[$name];
                 }
             }
         }
     }
     return self::$_export;
 }
Ejemplo 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);
 }
 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;*/
 }
Ejemplo 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];
 }
Ejemplo n.º 26
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');
 }
Ejemplo 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;
     }
 }
Ejemplo n.º 28
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();
 }
Ejemplo 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);
 }
Ejemplo n.º 30
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
 *                            '
 * @return array|CRM_Error
 * @access public
 */
function _crm_format_contrib_params(&$params, &$values, $create = false)
{
    // copy all the contribution fields as is
    $fields =& CRM_Contribute_DAO_Contribution::fields();
    _crm_store_values($fields, $params, $values);
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        switch ($key) {
            case 'contribution_contact_id':
                if (!CRM_Utils_Rule::integer($value)) {
                    return _crm_error("contact_id not valid: {$value}");
                }
                $dao =& new CRM_Core_DAO();
                $qParams = array();
                $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams);
                if (!$svq) {
                    return _crm_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                }
                $values['contact_id'] = $values['contribution_contact_id'];
                unset($values['contribution_contact_id']);
                break;
            case 'receive_date':
            case 'cancel_date':
            case 'receipt_date':
            case 'thankyou_date':
                if (!CRM_Utils_Rule::date($value)) {
                    return _crm_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 _crm_error("{$key} not a valid amount: {$value}");
                }
                break;
            case 'currency':
                if (!CRM_Utils_Rule::currencyCode($value)) {
                    return _crm_error("currency not a valid code: {$value}");
                }
                break;
            case 'contribution_type':
                require_once 'CRM/Contribute/PseudoConstant.php';
                $values['contribution_type_id'] = CRM_Utils_Array::key(ucfirst($value), CRM_Contribute_PseudoConstant::contributionType());
                break;
            case 'payment_instrument':
                require_once 'CRM/Core/OptionGroup.php';
                $values['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', $value);
                break;
            case 'contribution_status_id':
                require_once 'CRM/Core/OptionGroup.php';
                $values['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', $value);
                break;
            default:
                break;
        }
    }
    if (array_key_exists('note', $params)) {
        $values['note'] = $params['note'];
    }
    _crm_format_custom_params($params, $values, 'Contribution');
    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;
}